1
0

test.cc 851 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359
  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_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 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. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1701. EXPECT_FALSE(
  1702. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1703. EXPECT_TRUE(ranges.empty());
  1704. }
  1705. {
  1706. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1707. // remainder of the representation, so it stays accepted.
  1708. Ranges ranges;
  1709. auto ret =
  1710. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1711. EXPECT_TRUE(ret);
  1712. ASSERT_EQ(1u, ranges.size());
  1713. EXPECT_EQ(0, ranges[0].first);
  1714. EXPECT_EQ(-1, ranges[0].second);
  1715. }
  1716. }
  1717. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1718. Request req;
  1719. req.set_header("Accept-Encoding", "gzip");
  1720. Response res;
  1721. res.set_header("Content-Type", "text/plain");
  1722. auto ret = detail::encoding_type(req, res);
  1723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #else
  1726. EXPECT_TRUE(ret == detail::EncodingType::None);
  1727. #endif
  1728. }
  1729. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1730. Request req;
  1731. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1732. Response res;
  1733. res.set_header("Content-Type", "text/plain");
  1734. auto ret = detail::encoding_type(req, res);
  1735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1736. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1737. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1738. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1739. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1740. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1741. #else
  1742. EXPECT_TRUE(ret == detail::EncodingType::None);
  1743. #endif
  1744. }
  1745. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1746. Request req;
  1747. req.set_header("Accept-Encoding",
  1748. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1749. Response res;
  1750. res.set_header("Content-Type", "text/plain");
  1751. auto ret = detail::encoding_type(req, res);
  1752. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1753. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1754. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1755. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1756. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1757. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1758. #else
  1759. EXPECT_TRUE(ret == detail::EncodingType::None);
  1760. #endif
  1761. }
  1762. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1763. // All supported encodings rejected with q=0 should return None
  1764. Request req;
  1765. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1766. Response res;
  1767. res.set_header("Content-Type", "text/plain");
  1768. auto ret = detail::encoding_type(req, res);
  1769. EXPECT_TRUE(ret == detail::EncodingType::None);
  1770. }
  1771. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1772. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1773. Request req;
  1774. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1775. Response res;
  1776. res.set_header("Content-Type", "text/plain");
  1777. auto ret = detail::encoding_type(req, res);
  1778. EXPECT_TRUE(ret == detail::EncodingType::None);
  1779. }
  1780. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1781. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1782. Request req;
  1783. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1784. Response res;
  1785. res.set_header("Content-Type", "text/plain");
  1786. auto ret = detail::encoding_type(req, res);
  1787. EXPECT_TRUE(ret == detail::EncodingType::None);
  1788. }
  1789. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1790. // RFC 7231: Accept-Encoding values are case-insensitive
  1791. Request req;
  1792. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1793. Response res;
  1794. res.set_header("Content-Type", "text/plain");
  1795. auto ret = detail::encoding_type(req, res);
  1796. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1797. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1798. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1800. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1801. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1802. #else
  1803. EXPECT_TRUE(ret == detail::EncodingType::None);
  1804. #endif
  1805. }
  1806. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1807. // q value should determine priority, not hardcoded order
  1808. Request req;
  1809. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1810. Response res;
  1811. res.set_header("Content-Type", "text/plain");
  1812. auto ret = detail::encoding_type(req, res);
  1813. // gzip has highest q=1.0, so it should be selected even though
  1814. // br and zstd are also supported
  1815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1816. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1817. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1818. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1819. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1820. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1821. #else
  1822. EXPECT_TRUE(ret == detail::EncodingType::None);
  1823. #endif
  1824. }
  1825. TEST(BufferStreamTest, read) {
  1826. detail::BufferStream strm1;
  1827. Stream &strm = strm1;
  1828. EXPECT_EQ(5, strm.write("hello"));
  1829. char buf[512];
  1830. EXPECT_EQ(2, strm.read(buf, 2));
  1831. EXPECT_EQ('h', buf[0]);
  1832. EXPECT_EQ('e', buf[1]);
  1833. EXPECT_EQ(2, strm.read(buf, 2));
  1834. EXPECT_EQ('l', buf[0]);
  1835. EXPECT_EQ('l', buf[1]);
  1836. EXPECT_EQ(1, strm.read(buf, 1));
  1837. EXPECT_EQ('o', buf[0]);
  1838. EXPECT_EQ(0, strm.read(buf, 1));
  1839. }
  1840. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1841. auto host = "www.httpwatch.com";
  1842. auto ip = hosted_at(host);
  1843. EXPECT_EQ("23.96.13.243", ip);
  1844. std::vector<std::string> addrs;
  1845. hosted_at(host, addrs);
  1846. EXPECT_EQ(1u, addrs.size());
  1847. }
  1848. #if 0 // It depends on each test environment...
  1849. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1850. auto host = "www.youtube.com";
  1851. std::vector<std::string> addrs;
  1852. hosted_at(host, addrs);
  1853. EXPECT_EQ(20u, addrs.size());
  1854. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1855. EXPECT_TRUE(it != addrs.end());
  1856. }
  1857. #endif
  1858. class ChunkedEncodingTest : public ::testing::Test {
  1859. protected:
  1860. ChunkedEncodingTest()
  1861. : cli_(HOST, PORT)
  1862. #ifdef CPPHTTPLIB_SSL_ENABLED
  1863. ,
  1864. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1865. #endif
  1866. {
  1867. cli_.set_connection_timeout(2);
  1868. #ifdef CPPHTTPLIB_SSL_ENABLED
  1869. cli_.enable_server_certificate_verification(false);
  1870. #endif
  1871. }
  1872. virtual void SetUp() {
  1873. read_file("./image.jpg", image_data_);
  1874. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("Hello World!", "text/plain");
  1876. });
  1877. svr_.Get(
  1878. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1879. res.set_chunked_content_provider(
  1880. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1881. size_t remaining = image_data_.size() - offset;
  1882. if (remaining == 0) {
  1883. sink.done();
  1884. } else {
  1885. constexpr size_t CHUNK_SIZE = 1024;
  1886. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1887. sink.write(&image_data_[offset], send_size);
  1888. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1889. }
  1890. return true;
  1891. });
  1892. });
  1893. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1894. svr_.wait_until_ready();
  1895. }
  1896. virtual void TearDown() {
  1897. svr_.stop();
  1898. if (!request_threads_.empty()) {
  1899. std::this_thread::sleep_for(std::chrono::seconds(1));
  1900. for (auto &t : request_threads_) {
  1901. t.join();
  1902. }
  1903. }
  1904. t_.join();
  1905. }
  1906. #ifdef CPPHTTPLIB_SSL_ENABLED
  1907. SSLClient cli_;
  1908. SSLServer svr_;
  1909. #else
  1910. Client cli_;
  1911. Server svr_;
  1912. #endif
  1913. thread t_;
  1914. std::vector<thread> request_threads_;
  1915. std::string image_data_;
  1916. };
  1917. TEST_F(ChunkedEncodingTest, NormalGet) {
  1918. auto res = cli_.Get("/chunked");
  1919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1920. std::string out;
  1921. read_file("./image.jpg", out);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ(out, res->body);
  1924. }
  1925. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1926. std::string body;
  1927. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1928. body.append(data, data_length);
  1929. return true;
  1930. });
  1931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1932. std::string out;
  1933. read_file("./image.jpg", out);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ(out, body);
  1936. }
  1937. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1938. std::string body;
  1939. auto res = cli_.Get(
  1940. "/chunked",
  1941. [&](const Response &response) {
  1942. EXPECT_EQ(StatusCode::OK_200, response.status);
  1943. return true;
  1944. },
  1945. [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1950. std::string out;
  1951. read_file("./image.jpg", out);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. EXPECT_EQ(out, body);
  1954. }
  1955. TEST(RangeTest, FromHTTPBin_Online) {
  1956. auto host = "httpbingo.org";
  1957. auto path = std::string{"/range/32"};
  1958. #ifdef CPPHTTPLIB_SSL_ENABLED
  1959. auto port = 443;
  1960. SSLClient cli(host, port);
  1961. #else
  1962. auto port = 80;
  1963. Client cli(host, port);
  1964. #endif
  1965. cli.set_connection_timeout(5);
  1966. {
  1967. auto res = cli.Get(path);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, -1}})};
  1974. auto res = cli.Get(path, headers);
  1975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1976. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1978. }
  1979. {
  1980. Headers headers = {make_range_header({{1, 10}})};
  1981. auto res = cli.Get(path, headers);
  1982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1983. EXPECT_EQ("bcdefghijk", res->body);
  1984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1985. }
  1986. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1987. // entire resource, while the original httpbin returned 200. Both are
  1988. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1989. {
  1990. Headers headers = {make_range_header({{0, 31}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1994. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1995. res->status == StatusCode::PartialContent_206);
  1996. }
  1997. {
  1998. Headers headers = {make_range_header({{0, -1}})};
  1999. auto res = cli.Get(path, headers);
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2002. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2003. res->status == StatusCode::PartialContent_206);
  2004. }
  2005. // go-httpbin returns 206 with clamped range for over-range requests,
  2006. // while the original httpbin returned 416. Both behaviors are observed
  2007. // in real servers, so we only verify the request succeeds.
  2008. {
  2009. Headers headers = {make_range_header({{0, 32}})};
  2010. auto res = cli.Get(path, headers);
  2011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2012. }
  2013. }
  2014. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2015. auto host = "unresolvableaddress.local";
  2016. auto path = std::string{"/"};
  2017. #ifdef CPPHTTPLIB_SSL_ENABLED
  2018. auto port = 443;
  2019. SSLClient cli(host, port);
  2020. #else
  2021. auto port = 80;
  2022. Client cli(host, port);
  2023. #endif
  2024. cli.set_connection_timeout(1);
  2025. {
  2026. auto res = cli.Get(path);
  2027. ASSERT_FALSE(res);
  2028. }
  2029. std::this_thread::sleep_for(std::chrono::seconds(8));
  2030. }
  2031. #if defined(__linux__) && defined(__GLIBC__) && \
  2032. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2033. // Forward declaration: in split builds split.py strips `inline` and moves the
  2034. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2035. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2036. // against the symbol in both header-only and split builds.
  2037. namespace httplib {
  2038. namespace detail {
  2039. int getaddrinfo_with_timeout(const char *node, const char *service,
  2040. const struct addrinfo *hints,
  2041. struct addrinfo **res, time_t timeout_sec);
  2042. } // namespace detail
  2043. } // namespace httplib
  2044. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2045. //
  2046. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2047. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2048. // gai_suspend() call hits the connection timeout the function calls
  2049. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2050. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2051. // still alive and still references the now-destroyed stack frame.
  2052. //
  2053. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2054. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2055. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2056. // and runs them in a container.
  2057. namespace {
  2058. bool should_run_issue_2431_tests() {
  2059. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2060. return v && *v && std::string(v) != "0";
  2061. }
  2062. std::string unique_unresolvable_host(int n) {
  2063. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2064. // glibc still asks the configured nameserver — which is exactly the path
  2065. // we want to exercise. A unique label per call avoids the resolver cache.
  2066. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2067. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2068. std::to_string(n) + ".invalid";
  2069. }
  2070. } // namespace
  2071. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2072. if (!should_run_issue_2431_tests()) {
  2073. GTEST_SKIP()
  2074. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2075. }
  2076. for (int i = 0; i < 8; ++i) {
  2077. struct addrinfo hints;
  2078. memset(&hints, 0, sizeof(hints));
  2079. hints.ai_family = AF_UNSPEC;
  2080. hints.ai_socktype = SOCK_STREAM;
  2081. auto host = unique_unresolvable_host(i);
  2082. struct addrinfo *result = nullptr;
  2083. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2084. &result, /*timeout_sec=*/1);
  2085. if (rc == 0 && result) { freeaddrinfo(result); }
  2086. }
  2087. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2088. // stack region they still believe holds their gaicb.
  2089. std::this_thread::sleep_for(std::chrono::seconds(3));
  2090. }
  2091. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2092. if (!should_run_issue_2431_tests()) {
  2093. GTEST_SKIP()
  2094. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2095. }
  2096. std::atomic<bool> stop{false};
  2097. std::vector<std::thread> threads;
  2098. for (int t = 0; t < 8; ++t) {
  2099. threads.emplace_back([t, &stop] {
  2100. int i = 0;
  2101. while (!stop.load(std::memory_order_relaxed)) {
  2102. struct addrinfo hints;
  2103. memset(&hints, 0, sizeof(hints));
  2104. hints.ai_family = AF_UNSPEC;
  2105. hints.ai_socktype = SOCK_STREAM;
  2106. auto host = unique_unresolvable_host(t * 100000 + i++);
  2107. struct addrinfo *result = nullptr;
  2108. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2109. &result, /*timeout_sec=*/1);
  2110. if (rc == 0 && result) { freeaddrinfo(result); }
  2111. }
  2112. });
  2113. }
  2114. std::this_thread::sleep_for(std::chrono::seconds(8));
  2115. stop.store(true, std::memory_order_relaxed);
  2116. for (auto &th : threads) {
  2117. th.join();
  2118. }
  2119. std::this_thread::sleep_for(std::chrono::seconds(3));
  2120. }
  2121. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2122. if (!should_run_issue_2431_tests()) {
  2123. GTEST_SKIP()
  2124. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2125. }
  2126. std::atomic<bool> stop{false};
  2127. std::vector<std::thread> threads;
  2128. for (int t = 0; t < 8; ++t) {
  2129. threads.emplace_back([t, &stop] {
  2130. int i = 0;
  2131. while (!stop.load(std::memory_order_relaxed)) {
  2132. auto host = unique_unresolvable_host(t * 100000 + i++);
  2133. Client cli(host, 80);
  2134. cli.set_connection_timeout(1, 0);
  2135. cli.set_read_timeout(1, 0);
  2136. cli.set_write_timeout(1, 0);
  2137. (void)cli.Get("/");
  2138. }
  2139. });
  2140. }
  2141. std::this_thread::sleep_for(std::chrono::seconds(8));
  2142. stop.store(true, std::memory_order_relaxed);
  2143. for (auto &th : threads) {
  2144. th.join();
  2145. }
  2146. std::this_thread::sleep_for(std::chrono::seconds(3));
  2147. }
  2148. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2149. TEST(ConnectionErrorTest, InvalidHost) {
  2150. auto host = "-abcde.com";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. auto port = 443;
  2153. SSLClient cli(host, port);
  2154. #else
  2155. auto port = 80;
  2156. Client cli(host, port);
  2157. #endif
  2158. cli.set_connection_timeout(std::chrono::seconds(2));
  2159. auto res = cli.Get("/");
  2160. ASSERT_TRUE(!res);
  2161. EXPECT_EQ(Error::Connection, res.error());
  2162. }
  2163. TEST(ConnectionErrorTest, InvalidHost2) {
  2164. auto host = "httpcan.org/";
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. SSLClient cli(host);
  2167. #else
  2168. Client cli(host);
  2169. #endif
  2170. cli.set_connection_timeout(std::chrono::seconds(2));
  2171. auto res = cli.Get("/");
  2172. ASSERT_TRUE(!res);
  2173. EXPECT_EQ(Error::Connection, res.error());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2176. auto host = "httpcan.org/";
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. SSLClient cli(host);
  2179. #else
  2180. Client cli(host);
  2181. #endif
  2182. cli.set_connection_timeout(std::chrono::seconds(2));
  2183. auto res = cli.Get("/");
  2184. ASSERT_TRUE(!res);
  2185. stringstream s;
  2186. s << "error code: " << res.error();
  2187. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2188. }
  2189. TEST(ConnectionErrorTest, InvalidPort) {
  2190. auto host = "localhost";
  2191. auto port = 44380;
  2192. #ifdef CPPHTTPLIB_SSL_ENABLED
  2193. SSLClient cli(host, port);
  2194. #else
  2195. Client cli(host, port);
  2196. #endif
  2197. cli.set_connection_timeout(std::chrono::seconds(2));
  2198. auto res = cli.Get("/");
  2199. ASSERT_TRUE(!res);
  2200. EXPECT_TRUE(Error::Connection == res.error() ||
  2201. Error::ConnectionTimeout == res.error());
  2202. }
  2203. TEST(ConnectionErrorTest, Timeout_Online) {
  2204. auto host = "google.com";
  2205. #ifdef CPPHTTPLIB_SSL_ENABLED
  2206. auto port = 44380;
  2207. SSLClient cli(host, port);
  2208. #else
  2209. auto port = 8080;
  2210. Client cli(host, port);
  2211. #endif
  2212. cli.set_connection_timeout(std::chrono::seconds(2));
  2213. // only probe one address type so that the error reason
  2214. // correlates to the timed-out IPv4, not the unsupported
  2215. // IPv6 connection attempt
  2216. cli.set_address_family(AF_INET);
  2217. auto res = cli.Get("/");
  2218. ASSERT_TRUE(!res);
  2219. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2220. }
  2221. TEST(CancelTest, NoCancel_Online) {
  2222. auto host = "httpbingo.org";
  2223. auto path = std::string{"/range/32"};
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. auto port = 443;
  2226. SSLClient cli(host, port);
  2227. #else
  2228. auto port = 80;
  2229. Client cli(host, port);
  2230. #endif
  2231. cli.set_connection_timeout(std::chrono::seconds(5));
  2232. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. }
  2237. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2238. // Use /bytes with a large payload so that the DownloadProgress callback
  2239. // (which only fires for Content-Length responses) is invoked before the
  2240. // entire body is received, giving cancellation a chance to fire.
  2241. auto host = "httpbingo.org";
  2242. auto path = std::string{"/bytes/524288"};
  2243. #ifdef CPPHTTPLIB_SSL_ENABLED
  2244. auto port = 443;
  2245. SSLClient cli(host, port);
  2246. #else
  2247. auto port = 80;
  2248. Client cli(host, port);
  2249. #endif
  2250. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. ASSERT_TRUE(!res);
  2253. EXPECT_EQ(Error::Canceled, res.error());
  2254. }
  2255. TEST(CancelTest, WithCancelLargePayload_Online) {
  2256. auto host = "httpbingo.org";
  2257. auto path = std::string{"/bytes/524288"};
  2258. #ifdef CPPHTTPLIB_SSL_ENABLED
  2259. auto port = 443;
  2260. SSLClient cli(host, port);
  2261. #else
  2262. auto port = 80;
  2263. Client cli(host, port);
  2264. #endif
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. uint32_t count = 0;
  2267. auto res =
  2268. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_EQ(Error::Canceled, res.error());
  2271. }
  2272. TEST(CancelTest, NoCancelPost) {
  2273. Server svr;
  2274. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2275. res.set_content("Hello World!", "text/plain");
  2276. });
  2277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2278. auto se = detail::scope_exit([&] {
  2279. svr.stop();
  2280. thread.join();
  2281. ASSERT_FALSE(svr.is_running());
  2282. });
  2283. svr.wait_until_ready();
  2284. Client cli(HOST, PORT);
  2285. cli.set_connection_timeout(std::chrono::seconds(5));
  2286. auto res =
  2287. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2288. "application/json", [](uint64_t, uint64_t) { return true; });
  2289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. EXPECT_EQ(StatusCode::OK_200, res->status);
  2292. }
  2293. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2294. Server svr;
  2295. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!", "text/plain");
  2297. });
  2298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2299. auto se = detail::scope_exit([&] {
  2300. svr.stop();
  2301. thread.join();
  2302. ASSERT_FALSE(svr.is_running());
  2303. });
  2304. svr.wait_until_ready();
  2305. Client cli(HOST, PORT);
  2306. cli.set_connection_timeout(std::chrono::seconds(5));
  2307. auto res =
  2308. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2309. "application/json", [](uint64_t, uint64_t) { return false; });
  2310. ASSERT_TRUE(!res);
  2311. EXPECT_EQ(Error::Canceled, res.error());
  2312. }
  2313. TEST(CancelTest, WithCancelLargePayloadPost) {
  2314. Server svr;
  2315. svr.set_payload_max_length(200 * 1024 * 1024);
  2316. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2317. res.set_content(LARGE_DATA, "text/plain");
  2318. });
  2319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2320. auto se = detail::scope_exit([&] {
  2321. svr.stop();
  2322. thread.join();
  2323. ASSERT_FALSE(svr.is_running());
  2324. });
  2325. svr.wait_until_ready();
  2326. Client cli(HOST, PORT);
  2327. cli.set_payload_max_length(200 * 1024 * 1024);
  2328. cli.set_connection_timeout(std::chrono::seconds(5));
  2329. auto res =
  2330. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2331. "application/json", [](uint64_t, uint64_t) { return false; });
  2332. ASSERT_TRUE(!res);
  2333. EXPECT_EQ(Error::Canceled, res.error());
  2334. }
  2335. TEST(CancelTest, NoCancelPut) {
  2336. Server svr;
  2337. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!", "text/plain");
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. Client cli(HOST, PORT);
  2348. cli.set_connection_timeout(std::chrono::seconds(5));
  2349. auto res =
  2350. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2351. "application/json", [](uint64_t, uint64_t) { return true; });
  2352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2353. EXPECT_EQ("Hello World!", res->body);
  2354. EXPECT_EQ(StatusCode::OK_200, res->status);
  2355. }
  2356. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2357. Server svr;
  2358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2359. res.set_content("Hello World!", "text/plain");
  2360. });
  2361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2362. auto se = detail::scope_exit([&] {
  2363. svr.stop();
  2364. thread.join();
  2365. ASSERT_FALSE(svr.is_running());
  2366. });
  2367. svr.wait_until_ready();
  2368. Client cli(HOST, PORT);
  2369. cli.set_connection_timeout(std::chrono::seconds(5));
  2370. auto res =
  2371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2372. "application/json", [](uint64_t, uint64_t) { return false; });
  2373. ASSERT_TRUE(!res);
  2374. EXPECT_EQ(Error::Canceled, res.error());
  2375. }
  2376. TEST(CancelTest, WithCancelLargePayloadPut) {
  2377. Server svr;
  2378. svr.set_payload_max_length(200 * 1024 * 1024);
  2379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2380. res.set_content(LARGE_DATA, "text/plain");
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. Client cli(HOST, PORT);
  2390. cli.set_payload_max_length(200 * 1024 * 1024);
  2391. cli.set_connection_timeout(std::chrono::seconds(5));
  2392. auto res =
  2393. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2394. "application/json", [](uint64_t, uint64_t) { return false; });
  2395. ASSERT_TRUE(!res);
  2396. EXPECT_EQ(Error::Canceled, res.error());
  2397. }
  2398. TEST(CancelTest, NoCancelPatch) {
  2399. Server svr;
  2400. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2401. res.set_content("Hello World!", "text/plain");
  2402. });
  2403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2404. auto se = detail::scope_exit([&] {
  2405. svr.stop();
  2406. thread.join();
  2407. ASSERT_FALSE(svr.is_running());
  2408. });
  2409. svr.wait_until_ready();
  2410. Client cli(HOST, PORT);
  2411. cli.set_connection_timeout(std::chrono::seconds(5));
  2412. auto res =
  2413. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2414. "application/json", [](uint64_t, uint64_t) { return true; });
  2415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2416. EXPECT_EQ("Hello World!", res->body);
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. }
  2419. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2420. Server svr;
  2421. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2422. res.set_content("Hello World!", "text/plain");
  2423. });
  2424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2425. auto se = detail::scope_exit([&] {
  2426. svr.stop();
  2427. thread.join();
  2428. ASSERT_FALSE(svr.is_running());
  2429. });
  2430. svr.wait_until_ready();
  2431. Client cli(HOST, PORT);
  2432. cli.set_connection_timeout(std::chrono::seconds(5));
  2433. auto res =
  2434. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2435. "application/json", [](uint64_t, uint64_t) { return false; });
  2436. ASSERT_TRUE(!res);
  2437. EXPECT_EQ(Error::Canceled, res.error());
  2438. }
  2439. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2440. Server svr;
  2441. svr.set_payload_max_length(200 * 1024 * 1024);
  2442. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content(LARGE_DATA, "text/plain");
  2444. });
  2445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2446. auto se = detail::scope_exit([&] {
  2447. svr.stop();
  2448. thread.join();
  2449. ASSERT_FALSE(svr.is_running());
  2450. });
  2451. svr.wait_until_ready();
  2452. Client cli(HOST, PORT);
  2453. cli.set_payload_max_length(200 * 1024 * 1024);
  2454. cli.set_connection_timeout(std::chrono::seconds(5));
  2455. auto res =
  2456. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2457. "application/json", [](uint64_t, uint64_t) { return false; });
  2458. ASSERT_TRUE(!res);
  2459. EXPECT_EQ(Error::Canceled, res.error());
  2460. }
  2461. TEST(CancelTest, NoCancelDelete) {
  2462. Server svr;
  2463. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2464. res.set_content("Hello World!", "text/plain");
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. Client cli(HOST, PORT);
  2474. cli.set_connection_timeout(std::chrono::seconds(5));
  2475. auto res =
  2476. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2477. "application/json", [](uint64_t, uint64_t) { return true; });
  2478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2479. EXPECT_EQ("Hello World!", res->body);
  2480. EXPECT_EQ(StatusCode::OK_200, res->status);
  2481. }
  2482. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2483. Server svr;
  2484. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2485. res.set_content("Hello World!", "text/plain");
  2486. });
  2487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. thread.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. Client cli(HOST, PORT);
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. auto res =
  2497. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2498. "application/json", [](uint64_t, uint64_t) { return false; });
  2499. ASSERT_TRUE(!res);
  2500. EXPECT_EQ(Error::Canceled, res.error());
  2501. }
  2502. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2503. Server svr;
  2504. svr.set_payload_max_length(200 * 1024 * 1024);
  2505. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2506. res.set_content(LARGE_DATA, "text/plain");
  2507. });
  2508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. Client cli(HOST, PORT);
  2516. cli.set_payload_max_length(200 * 1024 * 1024);
  2517. cli.set_connection_timeout(std::chrono::seconds(5));
  2518. auto res =
  2519. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2520. "application/json", [](uint64_t, uint64_t) { return false; });
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::Canceled, res.error());
  2523. }
  2524. static std::string remove_whitespace(const std::string &input) {
  2525. std::string output;
  2526. output.reserve(input.size());
  2527. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2528. [](unsigned char c) { return !std::isspace(c); });
  2529. return output;
  2530. }
  2531. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2532. auto host = "httpbingo.org";
  2533. auto path = std::string{"/basic-auth/hello/world"};
  2534. #ifdef CPPHTTPLIB_SSL_ENABLED
  2535. auto port = 443;
  2536. SSLClient cli(host, port);
  2537. #else
  2538. auto port = 80;
  2539. Client cli(host, port);
  2540. #endif
  2541. {
  2542. auto res = cli.Get(path);
  2543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2544. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2545. }
  2546. {
  2547. auto res = cli.Get(
  2548. path, Headers{make_basic_authentication_header("hello", "world")});
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. auto body = remove_whitespace(res->body);
  2551. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2552. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. {
  2556. cli.set_basic_auth("hello", "world");
  2557. auto res = cli.Get(path);
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. auto body = remove_whitespace(res->body);
  2560. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2561. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. {
  2565. cli.set_basic_auth("hello", "bad");
  2566. auto res = cli.Get(path);
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2569. }
  2570. {
  2571. cli.set_basic_auth("bad", "world");
  2572. auto res = cli.Get(path);
  2573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2574. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2575. }
  2576. }
  2577. #ifdef CPPHTTPLIB_SSL_ENABLED
  2578. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2581. auto paths = std::vector<std::string>{
  2582. "/digest-auth/auth/hello/world/MD5",
  2583. "/digest-auth/auth/hello/world/SHA-256",
  2584. };
  2585. auto port = 443;
  2586. SSLClient cli(host, port);
  2587. {
  2588. auto res = cli.Get(unauth_path);
  2589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2591. }
  2592. {
  2593. cli.set_digest_auth("hello", "world");
  2594. for (const auto &path : paths) {
  2595. auto res = cli.Get(path.c_str());
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. auto body = remove_whitespace(res->body);
  2598. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2599. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2600. EXPECT_EQ(StatusCode::OK_200, res->status);
  2601. }
  2602. cli.set_digest_auth("hello", "bad");
  2603. for (const auto &path : paths) {
  2604. auto res = cli.Get(path.c_str());
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2607. }
  2608. }
  2609. }
  2610. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2611. // comma-separated list of challenges, and each challenge may itself carry a
  2612. // comma-separated auth-param list, so a server can legally offer Basic
  2613. // before Digest, either as two field lines or packed into one. Runs one 401
  2614. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2615. // value() joins them in receipt order) and checks that the retry carries a
  2616. // well-formed Digest Authorization header naming expected_realm.
  2617. static void
  2618. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2619. const std::string &expected_realm) {
  2620. std::atomic<int> hits{0};
  2621. Server svr;
  2622. svr.Get("/x", [&](const Request &req, Response &res) {
  2623. if (++hits == 1) {
  2624. res.status = StatusCode::Unauthorized_401;
  2625. for (const auto &challenge : challenges) {
  2626. res.set_header("WWW-Authenticate", challenge);
  2627. }
  2628. } else {
  2629. auto authorization = req.get_header_value("Authorization");
  2630. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2631. EXPECT_NE(std::string::npos,
  2632. authorization.find("realm=\"" + expected_realm + "\""));
  2633. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2634. res.set_content("ok", "text/plain");
  2635. }
  2636. });
  2637. auto port = svr.bind_to_any_port(HOST);
  2638. std::thread t([&]() { svr.listen_after_bind(); });
  2639. auto se = detail::scope_exit([&] {
  2640. svr.stop();
  2641. t.join();
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, port);
  2645. cli.set_digest_auth("hello", "world");
  2646. auto res = cli.Get("/x");
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(2, hits.load());
  2649. }
  2650. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2651. static const char *kDigestChallenge =
  2652. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2653. "algorithm=MD5";
  2654. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2655. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2656. "testrealm");
  2657. }
  2658. // Same challenge list with the schemes in the opposite order, to make sure
  2659. // the fix above didn't just special-case "Basic first".
  2660. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2661. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2662. "testrealm");
  2663. }
  2664. // A comma inside a quoted auth-param value must not be mistaken for the
  2665. // separator between two challenges (or two auth-params).
  2666. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2667. run_digest_challenge_list_test(
  2668. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2669. "algorithm=MD5"},
  2670. "test,realm");
  2671. }
  2672. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2673. // make_digest_authentication_header() dereferences both unconditionally, so
  2674. // a server sending a challenge missing either one must not be treated as
  2675. // usable -- doing so used to crash the client with std::out_of_range.
  2676. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2677. Server svr;
  2678. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2679. res.status = StatusCode::Unauthorized_401;
  2680. res.set_header("WWW-Authenticate", challenge);
  2681. });
  2682. auto port = svr.bind_to_any_port(HOST);
  2683. std::thread t([&]() { svr.listen_after_bind(); });
  2684. auto se = detail::scope_exit([&] {
  2685. svr.stop();
  2686. t.join();
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, port);
  2690. cli.set_digest_auth("hello", "world");
  2691. auto res = cli.Get("/x");
  2692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2694. }
  2695. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2696. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2697. }
  2698. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2699. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2700. }
  2701. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2702. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2703. }
  2704. #endif
  2705. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2706. auto host = "google.com";
  2707. auto another_host = "example.com";
  2708. auto wrong_ip = "0.0.0.0";
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host);
  2711. #else
  2712. Client cli(host);
  2713. #endif
  2714. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2715. auto res = cli.Get("/");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2718. }
  2719. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2720. auto host = "google.com";
  2721. auto wrong_ip = "0.0.0.0";
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. SSLClient cli(host);
  2724. #else
  2725. Client cli(host);
  2726. #endif
  2727. cli.set_hostname_addr_map({{host, wrong_ip}});
  2728. auto res = cli.Get("/");
  2729. ASSERT_TRUE(!res);
  2730. EXPECT_EQ(Error::Connection, res.error());
  2731. }
  2732. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2733. // A mapped value that is not an IP literal must be resolved. "localhost"
  2734. // resolves from the hosts file, so this test needs no external DNS.
  2735. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2736. auto host = "target.invalid";
  2737. Server svr;
  2738. std::string received_host;
  2739. svr.Get("/hi", [&](const Request &req, Response &res) {
  2740. received_host = req.get_header_value("Host");
  2741. res.set_content("Hello World!", "text/plain");
  2742. });
  2743. auto port = svr.bind_to_any_port(HOST);
  2744. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2745. auto se = detail::scope_exit([&] {
  2746. svr.stop();
  2747. thread.join();
  2748. ASSERT_FALSE(svr.is_running());
  2749. });
  2750. svr.wait_until_ready();
  2751. Client cli(host, port);
  2752. cli.set_hostname_addr_map({{host, HOST}});
  2753. auto res = cli.Get("/hi");
  2754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. // The mapping only redirects the connection; the identity stays host_.
  2757. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2758. }
  2759. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2760. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2761. auto host = "target.invalid";
  2762. Server svr;
  2763. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto port = svr.bind_to_any_port("127.0.0.1");
  2767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. Client cli(host, port);
  2775. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2776. auto res = cli.Get("/hi");
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ(StatusCode::OK_200, res->status);
  2779. }
  2780. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2781. // An empty mapped value must leave host_ as the connection target. Without
  2782. // that guard the empty value would become the host argument, getaddrinfo
  2783. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2784. // loopback - silently connecting somewhere the caller never asked for.
  2785. // The server listens on loopback, so such a fallback would succeed and is
  2786. // therefore observable as a failure of this test.
  2787. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2788. Server svr;
  2789. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2790. res.set_content("Hello World!", "text/plain");
  2791. });
  2792. auto port = svr.bind_to_any_port(HOST);
  2793. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. thread.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. Client cli(blackhole, port);
  2801. cli.set_hostname_addr_map({{blackhole, ""}});
  2802. cli.set_connection_timeout(1);
  2803. auto res = cli.Get("/hi");
  2804. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2805. }
  2806. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/absolute-redirect/3"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. SSLClient cli(host);
  2811. #else
  2812. Client cli(host);
  2813. #endif
  2814. cli.set_follow_location(true);
  2815. auto res = cli.Get(path);
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ(StatusCode::OK_200, res->status);
  2818. }
  2819. TEST(RedirectTest, Redirect_Online) {
  2820. auto host = "httpbingo.org";
  2821. auto path = std::string{"/redirect/3"};
  2822. #ifdef CPPHTTPLIB_SSL_ENABLED
  2823. SSLClient cli(host);
  2824. #else
  2825. Client cli(host);
  2826. #endif
  2827. cli.set_follow_location(true);
  2828. auto res = cli.Get(path);
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(RelativeRedirectTest, Redirect_Online) {
  2833. auto host = "httpbingo.org";
  2834. auto path = std::string{"/relative-redirect/3"};
  2835. #ifdef CPPHTTPLIB_SSL_ENABLED
  2836. SSLClient cli(host);
  2837. #else
  2838. Client cli(host);
  2839. #endif
  2840. cli.set_follow_location(true);
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::OK_200, res->status);
  2844. }
  2845. TEST(TooManyRedirectTest, Redirect_Online) {
  2846. auto host = "httpbingo.org";
  2847. auto path = std::string{"/redirect/21"};
  2848. #ifdef CPPHTTPLIB_SSL_ENABLED
  2849. SSLClient cli(host);
  2850. #else
  2851. Client cli(host);
  2852. #endif
  2853. cli.set_follow_location(true);
  2854. auto res = cli.Get(path);
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2857. }
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. TEST(YahooRedirectTest, Redirect_Online) {
  2860. Client cli("yahoo.com");
  2861. auto res = cli.Get("/");
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2864. cli.set_follow_location(true);
  2865. res = cli.Get("/");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::OK_200, res->status);
  2868. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2869. }
  2870. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2871. #define REDIR_HOST "httpbingo.org"
  2872. #define REDIR_PATH "/redirect-to"
  2873. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2874. SSLClient cli(REDIR_HOST);
  2875. cli.set_follow_location(true);
  2876. auto res =
  2877. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2882. SSLClient cli(REDIR_HOST);
  2883. cli.set_follow_location(true);
  2884. Params params;
  2885. params.emplace("url", "http://example.com");
  2886. params.emplace("status_code", "302");
  2887. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(StatusCode::OK_200, res->status);
  2899. }
  2900. TEST(UrlWithSpace, Redirect_Online) {
  2901. SSLClient cli("edge.forgecdn.net");
  2902. cli.set_follow_location(true);
  2903. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2907. }
  2908. #endif
  2909. #if !defined(_WIN32) && !defined(_WIN64)
  2910. TEST(ReceiveSignals, Signal) {
  2911. auto setupSignalHandlers = []() {
  2912. struct sigaction act;
  2913. sigemptyset(&act.sa_mask);
  2914. act.sa_flags = SA_SIGINFO;
  2915. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2916. switch (sig) {
  2917. case SIGINT:
  2918. default: break;
  2919. }
  2920. };
  2921. ::sigaction(SIGINT, &act, nullptr);
  2922. };
  2923. Server svr;
  2924. int port = 0;
  2925. auto thread = std::thread([&]() {
  2926. setupSignalHandlers();
  2927. port = svr.bind_to_any_port(HOST);
  2928. svr.listen_after_bind();
  2929. });
  2930. auto se = detail::scope_exit([&] {
  2931. svr.stop();
  2932. thread.join();
  2933. ASSERT_FALSE(svr.is_running());
  2934. });
  2935. svr.wait_until_ready();
  2936. ASSERT_TRUE(svr.is_running());
  2937. pthread_kill(thread.native_handle(), SIGINT);
  2938. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2939. ASSERT_TRUE(svr.is_running());
  2940. }
  2941. #endif
  2942. TEST(RedirectToDifferentPort, Redirect) {
  2943. Server svr1;
  2944. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2945. res.set_content("Hello World!", "text/plain");
  2946. });
  2947. int svr1_port = 0;
  2948. auto thread1 = std::thread([&]() {
  2949. svr1_port = svr1.bind_to_any_port(HOST);
  2950. svr1.listen_after_bind();
  2951. });
  2952. Server svr2;
  2953. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2954. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2955. });
  2956. int svr2_port = 0;
  2957. auto thread2 = std::thread([&]() {
  2958. svr2_port = svr2.bind_to_any_port(HOST);
  2959. svr2.listen_after_bind();
  2960. });
  2961. auto se = detail::scope_exit([&] {
  2962. svr2.stop();
  2963. thread2.join();
  2964. svr1.stop();
  2965. thread1.join();
  2966. ASSERT_FALSE(svr2.is_running());
  2967. ASSERT_FALSE(svr1.is_running());
  2968. });
  2969. svr1.wait_until_ready();
  2970. svr2.wait_until_ready();
  2971. Client cli("localhost", svr2_port);
  2972. cli.set_follow_location(true);
  2973. auto res = cli.Get("/2");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. EXPECT_EQ("Hello World!", res->body);
  2977. }
  2978. static void
  2979. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2980. Server svr1;
  2981. std::string captured_authorization;
  2982. svr1.Get("/target", [&](const Request &req, Response &res) {
  2983. captured_authorization = req.get_header_value("Authorization");
  2984. res.set_content("OK", "text/plain");
  2985. });
  2986. int svr1_port = 0;
  2987. auto thread1 = std::thread([&]() {
  2988. svr1_port = svr1.bind_to_any_port(HOST);
  2989. svr1.listen_after_bind();
  2990. });
  2991. Server svr2;
  2992. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2993. res.set_redirect(
  2994. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2995. });
  2996. int svr2_port = 0;
  2997. auto thread2 = std::thread([&]() {
  2998. svr2_port = svr2.bind_to_any_port(HOST);
  2999. svr2.listen_after_bind();
  3000. });
  3001. auto se = detail::scope_exit([&] {
  3002. svr2.stop();
  3003. thread2.join();
  3004. svr1.stop();
  3005. thread1.join();
  3006. ASSERT_FALSE(svr2.is_running());
  3007. ASSERT_FALSE(svr1.is_running());
  3008. });
  3009. svr1.wait_until_ready();
  3010. svr2.wait_until_ready();
  3011. Client cli("localhost", svr2_port);
  3012. cli.set_follow_location(true);
  3013. set_auth(cli);
  3014. auto res = cli.Get("/redir");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::OK_200, res->status);
  3017. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3018. EXPECT_TRUE(captured_authorization.empty());
  3019. }
  3020. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3021. TestDoNotForwardCredentialsOnRedirect(
  3022. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3023. }
  3024. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3025. TestDoNotForwardCredentialsOnRedirect(
  3026. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3027. }
  3028. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3029. Server svr1;
  3030. std::string captured_cookie;
  3031. bool target_hit = false;
  3032. svr1.Get("/target", [&](const Request &req, Response &res) {
  3033. captured_cookie = req.get_header_value("Cookie");
  3034. target_hit = true;
  3035. res.set_content("OK", "text/plain");
  3036. });
  3037. int svr1_port = 0;
  3038. auto thread1 = std::thread([&]() {
  3039. svr1_port = svr1.bind_to_any_port(HOST);
  3040. svr1.listen_after_bind();
  3041. });
  3042. Server svr2;
  3043. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3044. res.set_redirect(
  3045. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3046. });
  3047. int svr2_port = 0;
  3048. auto thread2 = std::thread([&]() {
  3049. svr2_port = svr2.bind_to_any_port(HOST);
  3050. svr2.listen_after_bind();
  3051. });
  3052. auto se = detail::scope_exit([&] {
  3053. svr2.stop();
  3054. thread2.join();
  3055. svr1.stop();
  3056. thread1.join();
  3057. ASSERT_FALSE(svr2.is_running());
  3058. ASSERT_FALSE(svr1.is_running());
  3059. });
  3060. svr1.wait_until_ready();
  3061. svr2.wait_until_ready();
  3062. Client cli("localhost", svr2_port);
  3063. cli.set_follow_location(true);
  3064. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3065. auto res = cli.Get("/redir", headers);
  3066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3067. EXPECT_EQ(StatusCode::OK_200, res->status);
  3068. EXPECT_TRUE(target_hit);
  3069. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3070. EXPECT_TRUE(captured_cookie.empty());
  3071. }
  3072. TEST(RedirectToSamePort, ForwardCookie) {
  3073. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3074. // header so that ordinary session flows keep working.
  3075. Server svr;
  3076. std::string captured_cookie;
  3077. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3078. res.set_redirect("/target", 302);
  3079. });
  3080. svr.Get("/target", [&](const Request &req, Response &res) {
  3081. captured_cookie = req.get_header_value("Cookie");
  3082. res.set_content("OK", "text/plain");
  3083. });
  3084. auto port = svr.bind_to_any_port(HOST);
  3085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3086. auto se = detail::scope_exit([&] {
  3087. svr.stop();
  3088. thread.join();
  3089. ASSERT_FALSE(svr.is_running());
  3090. });
  3091. svr.wait_until_ready();
  3092. Client cli(HOST, port);
  3093. cli.set_follow_location(true);
  3094. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3095. auto res = cli.Get("/redir", headers);
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::OK_200, res->status);
  3098. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3099. }
  3100. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3101. Server svr;
  3102. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3103. // Port number that overflows int — should not crash
  3104. res.set_redirect("http://localhost:99999999999999999999/target");
  3105. });
  3106. auto port = svr.bind_to_any_port(HOST);
  3107. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3108. auto se = detail::scope_exit([&] {
  3109. svr.stop();
  3110. thread.join();
  3111. ASSERT_FALSE(svr.is_running());
  3112. });
  3113. svr.wait_until_ready();
  3114. Client cli(HOST, port);
  3115. cli.set_follow_location(true);
  3116. auto res = cli.Get("/redir");
  3117. // Should fail gracefully, not crash (no valid response due to bad port)
  3118. EXPECT_FALSE(res);
  3119. }
  3120. TEST(RedirectFromPageWithContent, Redirect) {
  3121. Server svr;
  3122. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3123. res.set_content("___", "text/plain");
  3124. res.set_redirect("/2");
  3125. });
  3126. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3127. res.set_content("Hello World!", "text/plain");
  3128. });
  3129. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3130. auto se = detail::scope_exit([&] {
  3131. svr.stop();
  3132. th.join();
  3133. ASSERT_FALSE(svr.is_running());
  3134. });
  3135. svr.wait_until_ready();
  3136. {
  3137. Client cli("localhost", PORT);
  3138. cli.set_follow_location(true);
  3139. std::string body;
  3140. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3141. body.append(data, data_length);
  3142. return true;
  3143. });
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("Hello World!", body);
  3147. }
  3148. {
  3149. Client cli("localhost", PORT);
  3150. std::string body;
  3151. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3152. body.append(data, data_length);
  3153. return true;
  3154. });
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::Found_302, res->status);
  3157. EXPECT_EQ("___", body);
  3158. }
  3159. }
  3160. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3161. Server svr;
  3162. auto port_str = std::to_string(PORT);
  3163. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3164. auto expected_host = "[::1]:" + port_str;
  3165. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3166. res.set_content("___", "text/plain");
  3167. // res.set_redirect("/2");
  3168. res.set_redirect(redirect_url);
  3169. });
  3170. svr.Get("/2", [&](const Request &req, Response &res) {
  3171. auto host_header = req.headers.find("Host");
  3172. ASSERT_TRUE(host_header != req.headers.end());
  3173. EXPECT_EQ(expected_host, host_header->second);
  3174. res.set_content("Hello World!", "text/plain");
  3175. });
  3176. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3177. auto se = detail::scope_exit([&] {
  3178. svr.stop();
  3179. th.join();
  3180. ASSERT_FALSE(svr.is_running());
  3181. });
  3182. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3183. // actually starts anything, so the condition !svr.is_running() will
  3184. // always remain true, and the loop never stops.
  3185. // This basically counts how many milliseconds have passed since the
  3186. // call to svr.listen(), and if after 5 seconds nothing started yet
  3187. // aborts the test.
  3188. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3189. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3190. ASSERT_LT(milliseconds, 5000U);
  3191. }
  3192. {
  3193. Client cli("::1", PORT);
  3194. cli.set_follow_location(true);
  3195. std::string body;
  3196. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3197. body.append(data, data_length);
  3198. return true;
  3199. });
  3200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. EXPECT_EQ("Hello World!", body);
  3203. }
  3204. {
  3205. Client cli("::1", PORT);
  3206. std::string body;
  3207. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3208. body.append(data, data_length);
  3209. return true;
  3210. });
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ(StatusCode::Found_302, res->status);
  3213. EXPECT_EQ("___", body);
  3214. }
  3215. }
  3216. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3217. Server svr;
  3218. svr.Get("/foo", [](const Request &req, Response &res) {
  3219. auto a = req.params.find("a");
  3220. if (a != req.params.end()) {
  3221. res.set_content((*a).second, "text/plain");
  3222. res.status = StatusCode::OK_200;
  3223. } else {
  3224. res.status = StatusCode::BadRequest_400;
  3225. }
  3226. });
  3227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3228. auto se = detail::scope_exit([&] {
  3229. svr.stop();
  3230. thread.join();
  3231. ASSERT_FALSE(svr.is_running());
  3232. });
  3233. svr.wait_until_ready();
  3234. {
  3235. Client cli(HOST, PORT);
  3236. cli.set_path_encode(false);
  3237. auto res = cli.Get("/foo?a=explicitly+encoded");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::OK_200, res->status);
  3240. // This expects it back with a space, as the `+` won't have been
  3241. // url-encoded, and server-side the params get decoded turning `+`
  3242. // into spaces.
  3243. EXPECT_EQ("explicitly encoded", res->body);
  3244. }
  3245. }
  3246. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3247. // When path encoding is disabled the client must transmit the supplied
  3248. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3249. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3250. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3251. // than a space (0x20). Assert on the raw wire target to catch this.
  3252. Server svr;
  3253. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3254. svr.Get("/foo", [&](const Request &req, Response &res) {
  3255. EXPECT_EQ(expected_target, req.target);
  3256. res.status = StatusCode::OK_200;
  3257. });
  3258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3259. auto se = detail::scope_exit([&] {
  3260. svr.stop();
  3261. thread.join();
  3262. ASSERT_FALSE(svr.is_running());
  3263. });
  3264. svr.wait_until_ready();
  3265. {
  3266. Client cli(HOST, PORT);
  3267. cli.set_path_encode(false);
  3268. auto res = cli.Get(expected_target.c_str());
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. }
  3273. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3274. // `open_stream()` used to skip the path encoding that the buffered send
  3275. // path applies, so the same `path` produced different bytes in the request
  3276. // line depending on which API was used. Assert the two agree.
  3277. Server svr;
  3278. std::string target;
  3279. svr.Get(".*", [&](const Request &req, Response &res) {
  3280. target = req.target;
  3281. res.status = StatusCode::OK_200;
  3282. });
  3283. auto port = svr.bind_to_any_port(HOST);
  3284. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3285. auto se = detail::scope_exit([&] {
  3286. svr.stop();
  3287. thread.join();
  3288. ASSERT_FALSE(svr.is_running());
  3289. });
  3290. svr.wait_until_ready();
  3291. struct {
  3292. const char *path;
  3293. const char *expected;
  3294. } cases[] = {
  3295. {"/a b?x=1", "/a%20b?x=1"},
  3296. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3297. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3298. };
  3299. for (const auto &c : cases) {
  3300. Client cli(HOST, port);
  3301. target.clear();
  3302. auto res = cli.Get(c.path);
  3303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3304. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3305. auto buffered_target = target;
  3306. target.clear();
  3307. auto handle = cli.open_stream("GET", c.path);
  3308. EXPECT_TRUE(handle.is_valid())
  3309. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3310. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3311. }
  3312. }
  3313. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3314. // The `set_path_encode(false)` contract — transmit the supplied target
  3315. // verbatim — must hold for the streaming API too.
  3316. Server svr;
  3317. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3318. std::string target;
  3319. svr.Get("/foo", [&](const Request &req, Response &res) {
  3320. target = req.target;
  3321. res.status = StatusCode::OK_200;
  3322. });
  3323. auto port = svr.bind_to_any_port(HOST);
  3324. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3325. auto se = detail::scope_exit([&] {
  3326. svr.stop();
  3327. thread.join();
  3328. ASSERT_FALSE(svr.is_running());
  3329. });
  3330. svr.wait_until_ready();
  3331. {
  3332. Client cli(HOST, port);
  3333. cli.set_path_encode(false);
  3334. auto handle = cli.open_stream("GET", expected_target);
  3335. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3336. EXPECT_EQ(expected_target, target);
  3337. }
  3338. }
  3339. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3340. // With path encoding enabled a CR/LF in the target is percent-encoded
  3341. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3342. // write_request_line still backstops `set_path_encode(false)`, which is
  3343. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3344. Server svr;
  3345. // Captured before routing: the decoded path contains a newline, which a
  3346. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3347. std::string target;
  3348. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3349. target = req.target;
  3350. res.status = StatusCode::OK_200;
  3351. return Server::HandlerResponse::Handled;
  3352. });
  3353. auto port = svr.bind_to_any_port(HOST);
  3354. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3355. auto se = detail::scope_exit([&] {
  3356. svr.stop();
  3357. thread.join();
  3358. ASSERT_FALSE(svr.is_running());
  3359. });
  3360. svr.wait_until_ready();
  3361. {
  3362. Client cli(HOST, port);
  3363. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3364. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3365. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3366. }
  3367. }
  3368. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3369. // Nothing may reach the wire: a raw CR/LF target would split the request
  3370. // line and inject headers.
  3371. Server svr;
  3372. // Pre-routing so that "not called" means nothing reached the server at all,
  3373. // rather than merely failing to match a handler pattern.
  3374. auto handler_called = false;
  3375. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3376. handler_called = true;
  3377. res.status = StatusCode::OK_200;
  3378. return Server::HandlerResponse::Handled;
  3379. });
  3380. auto port = svr.bind_to_any_port(HOST);
  3381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3382. auto se = detail::scope_exit([&] {
  3383. svr.stop();
  3384. thread.join();
  3385. ASSERT_FALSE(svr.is_running());
  3386. });
  3387. svr.wait_until_ready();
  3388. {
  3389. Client cli(HOST, port);
  3390. cli.set_path_encode(false);
  3391. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3392. EXPECT_FALSE(handle.is_valid());
  3393. EXPECT_EQ(Error::Write, handle.error);
  3394. EXPECT_FALSE(handler_called);
  3395. }
  3396. }
  3397. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3398. // Which of the two branches runs is decided by whether the query component
  3399. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3400. // an empty query and must still fall back to building one from
  3401. // `req.params`, while a non-empty query must win over `req.params`.
  3402. Server svr;
  3403. std::string target;
  3404. svr.Get("/foo", [&](const Request &req, Response &res) {
  3405. target = req.target;
  3406. res.status = StatusCode::OK_200;
  3407. });
  3408. auto port = svr.bind_to_any_port(HOST);
  3409. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3410. auto se = detail::scope_exit([&] {
  3411. svr.stop();
  3412. thread.join();
  3413. ASSERT_FALSE(svr.is_running());
  3414. });
  3415. svr.wait_until_ready();
  3416. {
  3417. // Trailing `?` -> empty query component -> `req.params` is used.
  3418. Client cli(HOST, port);
  3419. Request req;
  3420. req.method = "GET";
  3421. req.path = "/foo?";
  3422. req.params.emplace("a", "1");
  3423. target.clear();
  3424. auto res = cli.send(req);
  3425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3426. EXPECT_EQ("/foo?a=1", target);
  3427. }
  3428. {
  3429. // Non-empty query in `req.path` -> `req.params` is not appended.
  3430. Client cli(HOST, port);
  3431. Request req;
  3432. req.method = "GET";
  3433. req.path = "/foo?b=2";
  3434. req.params.emplace("a", "1");
  3435. target.clear();
  3436. auto res = cli.send(req);
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ("/foo?b=2", target);
  3439. }
  3440. }
  3441. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3442. Server svr;
  3443. svr.Get("/", [](const Request &req, Response &) {
  3444. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3445. });
  3446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3447. auto se = detail::scope_exit([&] {
  3448. svr.stop();
  3449. thread.join();
  3450. ASSERT_FALSE(svr.is_running());
  3451. });
  3452. svr.wait_until_ready();
  3453. {
  3454. Client cli(HOST, PORT);
  3455. cli.set_path_encode(false);
  3456. auto res = cli.Get("/?something=%0A");
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. }
  3460. }
  3461. TEST(BindServerTest, BindDualStack) {
  3462. Server svr;
  3463. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3464. res.set_content("Hello World!", "text/plain");
  3465. });
  3466. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. {
  3474. Client cli("127.0.0.1", PORT);
  3475. auto res = cli.Get("/1");
  3476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("Hello World!", res->body);
  3479. }
  3480. {
  3481. Client cli("::1", PORT);
  3482. auto res = cli.Get("/1");
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ("Hello World!", res->body);
  3486. }
  3487. }
  3488. TEST(BindServerTest, BindAndListenSeparately) {
  3489. Server svr;
  3490. int port = svr.bind_to_any_port("0.0.0.0");
  3491. ASSERT_TRUE(svr.is_valid());
  3492. ASSERT_TRUE(port > 0);
  3493. svr.stop();
  3494. }
  3495. // Reports whether anything is still listening on a loopback port. A plain
  3496. // connect() is used instead of a Client request because a socket left bound by
  3497. // mistake accepts the connection into its backlog and never answers, which
  3498. // would hang the test instead of failing it.
  3499. static bool is_loopback_port_accepting(int port) {
  3500. sockaddr_in addr{};
  3501. addr.sin_family = AF_INET;
  3502. addr.sin_port = htons(static_cast<uint16_t>(port));
  3503. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3504. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3505. EXPECT_NE(sock, INVALID_SOCKET);
  3506. if (sock == INVALID_SOCKET) { return false; }
  3507. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3508. static_cast<socklen_t>(sizeof(addr)));
  3509. detail::close_socket(sock);
  3510. return ret == 0;
  3511. }
  3512. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3513. Server svr;
  3514. auto port = svr.bind_to_any_port("127.0.0.1");
  3515. ASSERT_TRUE(port > 0);
  3516. svr.stop();
  3517. // bind_to_any_port() already called listen(2), so until stop() closed the
  3518. // descriptor the port kept accepting connections into the backlog. ASSERT
  3519. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3520. // below blocks forever in the accept loop.
  3521. ASSERT_FALSE(is_loopback_port_accepting(port));
  3522. // Nothing is left to accept on, so listen_after_bind() must report failure
  3523. // instead of returning success without ever serving.
  3524. EXPECT_FALSE(svr.listen_after_bind());
  3525. // The failed listen marks the server decommissioned, so a waiter returns
  3526. // instead of spinning forever.
  3527. svr.wait_until_ready();
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3532. CLIENT_CA_CERT_DIR);
  3533. int port = svr.bind_to_any_port("0.0.0.0");
  3534. ASSERT_TRUE(svr.is_valid());
  3535. ASSERT_TRUE(port > 0);
  3536. svr.stop();
  3537. }
  3538. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3539. // or a rejected CustomRoute() registration would not stop the server binding.
  3540. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3542. CLIENT_CA_CERT_DIR);
  3543. ASSERT_TRUE(svr.is_valid());
  3544. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3545. EXPECT_FALSE(svr.is_valid());
  3546. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3547. }
  3548. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3549. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3550. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3551. int port = svr.bind_to_any_port("0.0.0.0");
  3552. ASSERT_TRUE(svr.is_valid());
  3553. ASSERT_TRUE(port > 0);
  3554. svr.stop();
  3555. }
  3556. TEST(BindServerTest, UpdateCertsPem) {
  3557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3558. int port = svr.bind_to_any_port("0.0.0.0");
  3559. ASSERT_TRUE(svr.is_valid());
  3560. ASSERT_TRUE(port > 0);
  3561. // Read PEM files
  3562. std::string cert_pem, key_pem, ca_pem;
  3563. read_file(SERVER_CERT_FILE, cert_pem);
  3564. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3565. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3566. // Update server certificates using PEM API
  3567. ASSERT_TRUE(
  3568. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3569. ASSERT_TRUE(svr.is_valid());
  3570. svr.stop();
  3571. }
  3572. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3573. // Start server with client CA (enables client auth)
  3574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3575. ASSERT_TRUE(svr.is_valid());
  3576. bool handler_called = false;
  3577. svr.Get("/test", [&](const Request &req, Response &res) {
  3578. handler_called = true;
  3579. // Verify client certificate is present
  3580. auto cert = req.peer_cert();
  3581. EXPECT_TRUE(static_cast<bool>(cert));
  3582. res.set_content("ok", "text/plain");
  3583. });
  3584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3585. auto se = detail::scope_exit([&] {
  3586. svr.stop();
  3587. t.join();
  3588. ASSERT_FALSE(svr.is_running());
  3589. });
  3590. svr.wait_until_ready();
  3591. // Read PEM files
  3592. std::string cert_pem, key_pem, ca_pem;
  3593. read_file(SERVER_CERT_FILE, cert_pem);
  3594. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3595. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3596. // Update server certificates and client CA using PEM API while server running
  3597. ASSERT_TRUE(
  3598. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3599. // Connect with client certificate
  3600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3601. cli.enable_server_certificate_verification(false);
  3602. cli.set_connection_timeout(30);
  3603. auto res = cli.Get("/test");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_TRUE(handler_called);
  3607. EXPECT_EQ("ok", res->body);
  3608. }
  3609. #endif
  3610. TEST(ErrorHandlerTest, ContentLength) {
  3611. Server svr;
  3612. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3613. res.status = StatusCode::OK_200;
  3614. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3615. "text/html"); // <= Content-Length still 13
  3616. });
  3617. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!\n", "text/plain");
  3619. res.status = 524;
  3620. });
  3621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. thread.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. svr.wait_until_ready();
  3628. {
  3629. Client cli(HOST, PORT);
  3630. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3634. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3635. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3636. }
  3637. }
  3638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3639. TEST(ExceptionTest, WithoutExceptionHandler) {
  3640. Server svr;
  3641. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3642. throw std::runtime_error("exception...");
  3643. });
  3644. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3645. throw std::runtime_error("exception\r\n...");
  3646. });
  3647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3648. auto se = detail::scope_exit([&] {
  3649. svr.stop();
  3650. listen_thread.join();
  3651. ASSERT_FALSE(svr.is_running());
  3652. });
  3653. svr.wait_until_ready();
  3654. Client cli("localhost", PORT);
  3655. {
  3656. auto res = cli.Get("/exception");
  3657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3659. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3660. }
  3661. {
  3662. auto res = cli.Get("/unknown");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3665. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3666. }
  3667. }
  3668. TEST(ExceptionTest, WithExceptionHandler) {
  3669. Server svr;
  3670. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3671. std::exception_ptr ep) {
  3672. EXPECT_FALSE(ep == nullptr);
  3673. try {
  3674. std::rethrow_exception(ep);
  3675. } catch (std::exception &e) {
  3676. EXPECT_EQ("abc", std::string(e.what()));
  3677. } catch (...) {}
  3678. res.status = StatusCode::InternalServerError_500;
  3679. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3680. "text/html"); // <= Content-Length still 13 at this point
  3681. });
  3682. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3683. res.set_content("Hello World!\n", "text/plain");
  3684. throw std::runtime_error("abc");
  3685. });
  3686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. for (size_t i = 0; i < 10; i++) {
  3694. Client cli(HOST, PORT);
  3695. for (size_t j = 0; j < 100; j++) {
  3696. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3699. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3700. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3701. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3702. }
  3703. cli.set_keep_alive(true);
  3704. for (size_t j = 0; j < 100; j++) {
  3705. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3708. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3709. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3711. }
  3712. }
  3713. }
  3714. TEST(ExceptionTest, AndErrorHandler) {
  3715. Server svr;
  3716. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3717. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3718. });
  3719. svr.set_exception_handler(
  3720. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3721. EXPECT_FALSE(ep == nullptr);
  3722. try {
  3723. std::rethrow_exception(ep);
  3724. } catch (std::exception &e) {
  3725. res.set_content(e.what(), "text/html");
  3726. } catch (...) {}
  3727. res.status = StatusCode::InternalServerError_500;
  3728. });
  3729. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3730. throw std::runtime_error("EXCEPTION");
  3731. });
  3732. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3733. res.set_content("ERROR", "text/html");
  3734. res.status = StatusCode::InternalServerError_500;
  3735. });
  3736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. Client cli(HOST, PORT);
  3744. {
  3745. auto res = cli.Get("/exception");
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3748. EXPECT_EQ("EXCEPTION", res->body);
  3749. }
  3750. {
  3751. auto res = cli.Get("/error");
  3752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3753. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3754. EXPECT_EQ("ERROR", res->body);
  3755. }
  3756. {
  3757. auto res = cli.Get("/invalid");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3760. EXPECT_EQ("NOT_FOUND", res->body);
  3761. }
  3762. }
  3763. #endif
  3764. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3765. // process_request() wraps only routing() in a try/catch, so an exception from
  3766. // any other user callback used to unwind into the task queue - which does not
  3767. // catch - and terminate the process. Each test below runs the server on a
  3768. // single worker thread: a guard that catches the exception but still loses the
  3769. // thread would otherwise be hidden by a spare worker serving the follow-up
  3770. // request. Note that a regression here aborts the whole test binary rather
  3771. // than failing one test.
  3772. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3773. Server svr;
  3774. svr.new_task_queue = [] { return new ThreadPool(1); };
  3775. std::atomic<int> reported{0};
  3776. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3777. if (err == Error::UserCallbackException) { reported++; }
  3778. });
  3779. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3780. res.set_content_provider(
  3781. 1024, "text/plain",
  3782. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3783. sink.write("hello", 5);
  3784. throw std::runtime_error("from the content provider");
  3785. });
  3786. });
  3787. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3788. res.set_content("ok", "text/plain");
  3789. });
  3790. auto port = svr.bind_to_any_port(HOST);
  3791. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3792. auto se = detail::scope_exit([&] {
  3793. svr.stop();
  3794. listen_thread.join();
  3795. ASSERT_FALSE(svr.is_running());
  3796. });
  3797. svr.wait_until_ready();
  3798. {
  3799. Client cli(HOST, port);
  3800. cli.set_read_timeout(5, 0);
  3801. EXPECT_FALSE(cli.Get("/throw"));
  3802. }
  3803. EXPECT_TRUE(svr.is_running());
  3804. EXPECT_EQ(1, reported.load());
  3805. // A request on a fresh connection is still served.
  3806. {
  3807. Client cli(HOST, port);
  3808. auto res = cli.Get("/ok");
  3809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. EXPECT_EQ("ok", res->body);
  3812. }
  3813. }
  3814. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3815. Server svr;
  3816. svr.new_task_queue = [] { return new ThreadPool(1); };
  3817. std::atomic<bool> should_throw{true};
  3818. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3819. res.set_content("hi", "text/plain");
  3820. });
  3821. svr.set_post_routing_handler(
  3822. [&](const Request & /*req*/, Response & /*res*/) {
  3823. if (should_throw) {
  3824. throw std::runtime_error("from the post-routing handler");
  3825. }
  3826. });
  3827. auto port = svr.bind_to_any_port(HOST);
  3828. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. listen_thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. {
  3836. Client cli(HOST, port);
  3837. cli.set_read_timeout(5, 0);
  3838. EXPECT_FALSE(cli.Get("/hi"));
  3839. }
  3840. EXPECT_TRUE(svr.is_running());
  3841. should_throw = false;
  3842. {
  3843. Client cli(HOST, port);
  3844. auto res = cli.Get("/hi");
  3845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. EXPECT_EQ("hi", res->body);
  3848. }
  3849. }
  3850. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3851. // The guard reports the caught exception through the error logger, which is
  3852. // a user callback too. A logger that throws has to be contained as well, or
  3853. // the process would terminate from inside the catch.
  3854. Server svr;
  3855. svr.new_task_queue = [] { return new ThreadPool(1); };
  3856. std::atomic<int> reported{0};
  3857. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3858. if (err == Error::UserCallbackException) {
  3859. reported++;
  3860. throw std::runtime_error("from the error logger");
  3861. }
  3862. });
  3863. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3864. res.set_content_provider(
  3865. 1024, "text/plain",
  3866. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3867. sink.write("hello", 5);
  3868. throw std::runtime_error("from the content provider");
  3869. });
  3870. });
  3871. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3872. res.set_content("ok", "text/plain");
  3873. });
  3874. auto port = svr.bind_to_any_port(HOST);
  3875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. listen_thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. {
  3883. Client cli(HOST, port);
  3884. cli.set_read_timeout(5, 0);
  3885. EXPECT_FALSE(cli.Get("/throw"));
  3886. }
  3887. EXPECT_TRUE(svr.is_running());
  3888. EXPECT_EQ(1, reported.load());
  3889. {
  3890. Client cli(HOST, port);
  3891. auto res = cli.Get("/ok");
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("ok", res->body);
  3895. }
  3896. }
  3897. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3898. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3899. // so the exception unwinds through the ws::WebSocket object on its way to
  3900. // the guard. None of the HTTP cases above cross that.
  3901. Server svr;
  3902. svr.new_task_queue = [] { return new ThreadPool(1); };
  3903. std::atomic<int> reported{0};
  3904. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3905. if (err == Error::UserCallbackException) { reported++; }
  3906. });
  3907. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3908. throw std::runtime_error("from the WebSocket handler");
  3909. });
  3910. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3911. res.set_content("ok", "text/plain");
  3912. });
  3913. auto port = svr.bind_to_any_port(HOST);
  3914. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. listen_thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3923. "/ws");
  3924. auto res = client.connect();
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. // The server dropped the connection instead of dying.
  3927. std::string msg;
  3928. EXPECT_FALSE(client.read(msg));
  3929. client.close();
  3930. }
  3931. EXPECT_TRUE(svr.is_running());
  3932. EXPECT_EQ(1, reported.load());
  3933. {
  3934. Client cli(HOST, port);
  3935. auto res = cli.Get("/ok");
  3936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3937. EXPECT_EQ(StatusCode::OK_200, res->status);
  3938. EXPECT_EQ("ok", res->body);
  3939. }
  3940. }
  3941. #ifdef CPPHTTPLIB_SSL_ENABLED
  3942. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3943. // SSLServer::process_and_close_socket() is a separate overload with its own
  3944. // guard, so it is exercised on its own.
  3945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3946. ASSERT_TRUE(svr.is_valid());
  3947. svr.new_task_queue = [] { return new ThreadPool(1); };
  3948. std::atomic<int> reported{0};
  3949. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3950. if (err == Error::UserCallbackException) { reported++; }
  3951. });
  3952. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3953. res.set_content_provider(
  3954. 1024, "text/plain",
  3955. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3956. sink.write("hello", 5);
  3957. throw std::runtime_error("from the content provider");
  3958. });
  3959. });
  3960. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3961. res.set_content("ok", "text/plain");
  3962. });
  3963. auto port = svr.bind_to_any_port(HOST);
  3964. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3965. auto se = detail::scope_exit([&] {
  3966. svr.stop();
  3967. listen_thread.join();
  3968. ASSERT_FALSE(svr.is_running());
  3969. });
  3970. svr.wait_until_ready();
  3971. {
  3972. SSLClient cli(HOST, port);
  3973. cli.enable_server_certificate_verification(false);
  3974. cli.set_read_timeout(5, 0);
  3975. EXPECT_FALSE(cli.Get("/throw"));
  3976. }
  3977. EXPECT_TRUE(svr.is_running());
  3978. EXPECT_EQ(1, reported.load());
  3979. {
  3980. SSLClient cli(HOST, port);
  3981. cli.enable_server_certificate_verification(false);
  3982. auto res = cli.Get("/ok");
  3983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("ok", res->body);
  3986. }
  3987. }
  3988. #endif
  3989. #endif
  3990. TEST(NoContentTest, ContentLength) {
  3991. Server svr;
  3992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3993. res.status = StatusCode::NoContent_204;
  3994. });
  3995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3996. auto se = detail::scope_exit([&] {
  3997. svr.stop();
  3998. thread.join();
  3999. ASSERT_FALSE(svr.is_running());
  4000. });
  4001. svr.wait_until_ready();
  4002. {
  4003. Client cli(HOST, PORT);
  4004. auto res = cli.Get("/hi");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. }
  4009. }
  4010. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4011. #ifdef CPPHTTPLIB_SSL_ENABLED
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. #else
  4015. Server svr;
  4016. #endif
  4017. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4018. if (req.path == "/routing_handler") {
  4019. res.set_header("PRE_ROUTING", "on");
  4020. res.set_content("Routing Handler", "text/plain");
  4021. return httplib::Server::HandlerResponse::Handled;
  4022. }
  4023. return httplib::Server::HandlerResponse::Unhandled;
  4024. });
  4025. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4026. res.set_content("Error", "text/html");
  4027. });
  4028. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4029. if (req.path == "/routing_handler") {
  4030. res.set_header("POST_ROUTING", "on");
  4031. }
  4032. });
  4033. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4034. res.set_content("Hello World!\n", "text/plain");
  4035. });
  4036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4037. auto se = detail::scope_exit([&] {
  4038. svr.stop();
  4039. thread.join();
  4040. ASSERT_FALSE(svr.is_running());
  4041. });
  4042. svr.wait_until_ready();
  4043. {
  4044. #ifdef CPPHTTPLIB_SSL_ENABLED
  4045. SSLClient cli(HOST, PORT);
  4046. cli.enable_server_certificate_verification(false);
  4047. #else
  4048. Client cli(HOST, PORT);
  4049. #endif
  4050. auto res = cli.Get("/routing_handler");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("Routing Handler", res->body);
  4054. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4055. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4056. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4057. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4058. }
  4059. {
  4060. #ifdef CPPHTTPLIB_SSL_ENABLED
  4061. SSLClient cli(HOST, PORT);
  4062. cli.enable_server_certificate_verification(false);
  4063. #else
  4064. Client cli(HOST, PORT);
  4065. #endif
  4066. auto res = cli.Get("/hi");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. EXPECT_EQ("Hello World!\n", res->body);
  4070. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4071. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4072. }
  4073. {
  4074. #ifdef CPPHTTPLIB_SSL_ENABLED
  4075. SSLClient cli(HOST, PORT);
  4076. cli.enable_server_certificate_verification(false);
  4077. #else
  4078. Client cli(HOST, PORT);
  4079. #endif
  4080. auto res = cli.Get("/aaa");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4083. EXPECT_EQ("Error", res->body);
  4084. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4085. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4086. }
  4087. }
  4088. TEST(RequestHandlerTest, PreRequestHandler) {
  4089. auto route_path = "/user/:user";
  4090. Server svr;
  4091. svr.Get("/hi", [](const Request &, Response &res) {
  4092. res.set_content("hi", "text/plain");
  4093. });
  4094. svr.Get(route_path, [](const Request &req, Response &res) {
  4095. res.set_content(req.path_params.at("user"), "text/plain");
  4096. });
  4097. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4098. if (req.matched_route == route_path) {
  4099. auto user = req.path_params.at("user");
  4100. if (user != "john") {
  4101. res.status = StatusCode::Forbidden_403;
  4102. res.set_content("error", "text/html");
  4103. return Server::HandlerResponse::Handled;
  4104. }
  4105. }
  4106. return Server::HandlerResponse::Unhandled;
  4107. });
  4108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4109. auto se = detail::scope_exit([&] {
  4110. svr.stop();
  4111. thread.join();
  4112. ASSERT_FALSE(svr.is_running());
  4113. });
  4114. svr.wait_until_ready();
  4115. Client cli(HOST, PORT);
  4116. {
  4117. auto res = cli.Get("/hi");
  4118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("hi", res->body);
  4121. }
  4122. {
  4123. auto res = cli.Get("/user/john");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. EXPECT_EQ("john", res->body);
  4127. }
  4128. {
  4129. auto res = cli.Get("/user/invalid-user");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4132. EXPECT_EQ("error", res->body);
  4133. }
  4134. }
  4135. // The pre-request handler must run before the request body is read, so a
  4136. // rejected request never forces the server to buffer a (potentially large)
  4137. // body. Here the posted body is larger than the payload limit: if the body
  4138. // were read first the server would answer 413, but because the pre-request
  4139. // handler runs first it answers 403 and the body is never read.
  4140. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4141. Server svr;
  4142. svr.set_payload_max_length(8);
  4143. auto handler_ran = false;
  4144. svr.Post("/reject", [&](const Request &req, Response &res) {
  4145. handler_ran = true;
  4146. res.set_content(req.body, "text/plain");
  4147. });
  4148. svr.Post("/accept", [](const Request &req, Response &res) {
  4149. res.set_content(req.body, "text/plain");
  4150. });
  4151. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4152. if (req.matched_route == "/reject") {
  4153. res.status = StatusCode::Forbidden_403;
  4154. res.set_content("denied", "text/plain");
  4155. return Server::HandlerResponse::Handled;
  4156. }
  4157. return Server::HandlerResponse::Unhandled;
  4158. });
  4159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4160. auto se = detail::scope_exit([&] {
  4161. svr.stop();
  4162. thread.join();
  4163. ASSERT_FALSE(svr.is_running());
  4164. });
  4165. svr.wait_until_ready();
  4166. Client cli(HOST, PORT);
  4167. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4168. // rejects with 403 before the body is read, so 413 is never reached.
  4169. {
  4170. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4173. EXPECT_EQ("denied", res->body);
  4174. EXPECT_FALSE(handler_ran);
  4175. }
  4176. // An approved route still reads the body and enforces the payload limit.
  4177. {
  4178. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4180. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4181. }
  4182. }
  4183. TEST(UserDataTest, BasicOperations) {
  4184. httplib::UserData ud;
  4185. // Initially empty
  4186. EXPECT_FALSE(ud.has("key"));
  4187. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4188. // set and get
  4189. ud.set("key", 42);
  4190. EXPECT_TRUE(ud.has("key"));
  4191. auto *p = ud.get<int>("key");
  4192. ASSERT_NE(nullptr, p);
  4193. EXPECT_EQ(42, *p);
  4194. // Type mismatch → nullptr
  4195. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4196. // Overwrite with different type
  4197. ud.set("key", std::string("hello"));
  4198. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4199. auto *s = ud.get<std::string>("key");
  4200. ASSERT_NE(nullptr, s);
  4201. EXPECT_EQ("hello", *s);
  4202. // erase
  4203. ud.erase("key");
  4204. EXPECT_FALSE(ud.has("key"));
  4205. // clear
  4206. ud.set("a", 1);
  4207. ud.set("b", 2);
  4208. ud.clear();
  4209. EXPECT_FALSE(ud.has("a"));
  4210. EXPECT_FALSE(ud.has("b"));
  4211. }
  4212. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4213. struct AuthCtx {
  4214. std::string user_id;
  4215. };
  4216. Server svr;
  4217. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4218. res.user_data.set("auth", AuthCtx{"alice"});
  4219. return Server::HandlerResponse::Unhandled;
  4220. });
  4221. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4222. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4223. ASSERT_NE(nullptr, ctx);
  4224. res.set_content("Hello " + ctx->user_id, "text/plain");
  4225. });
  4226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. Client cli(HOST, PORT);
  4234. auto res = cli.Get("/me");
  4235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4236. EXPECT_EQ(StatusCode::OK_200, res->status);
  4237. EXPECT_EQ("Hello alice", res->body);
  4238. }
  4239. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4240. struct RoleCtx {
  4241. std::string role;
  4242. };
  4243. Server svr;
  4244. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4245. res.user_data.set("role", RoleCtx{"admin"});
  4246. return Server::HandlerResponse::Unhandled;
  4247. });
  4248. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4249. auto *ctx = res.user_data.get<RoleCtx>("role");
  4250. ASSERT_NE(nullptr, ctx);
  4251. res.set_content(ctx->role, "text/plain");
  4252. });
  4253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4254. auto se = detail::scope_exit([&] {
  4255. svr.stop();
  4256. thread.join();
  4257. ASSERT_FALSE(svr.is_running());
  4258. });
  4259. svr.wait_until_ready();
  4260. Client cli(HOST, PORT);
  4261. auto res = cli.Get("/role");
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("admin", res->body);
  4265. }
  4266. TEST(InvalidFormatTest, StatusCode) {
  4267. Server svr;
  4268. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("Hello World!\n", "text/plain");
  4270. res.status = 9999; // Status should be a three-digit code...
  4271. });
  4272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. Client cli(HOST, PORT);
  4281. auto res = cli.Get("/hi");
  4282. ASSERT_FALSE(res);
  4283. }
  4284. }
  4285. TEST(URLFragmentTest, WithFragment) {
  4286. Server svr;
  4287. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4288. EXPECT_TRUE(req.target == "/hi");
  4289. });
  4290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4291. auto se = detail::scope_exit([&] {
  4292. svr.stop();
  4293. thread.join();
  4294. ASSERT_FALSE(svr.is_running());
  4295. });
  4296. svr.wait_until_ready();
  4297. {
  4298. Client cli(HOST, PORT);
  4299. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4300. EXPECT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. res = cli.Get("/hi%23key1=val1=key2=val2");
  4303. EXPECT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. }
  4307. TEST(HeaderWriter, SetHeaderWriter) {
  4308. Server svr;
  4309. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4310. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4311. return detail::write_headers(strm, hdrs);
  4312. });
  4313. svr.Get("/hi", [](const Request &req, Response &res) {
  4314. auto it = req.headers.find("CustomClientHeader");
  4315. EXPECT_TRUE(it != req.headers.end());
  4316. EXPECT_EQ(it->second, "CustomClientValue");
  4317. res.set_content("Hello World!\n", "text/plain");
  4318. });
  4319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. {
  4327. Client cli(HOST, PORT);
  4328. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4329. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4330. return detail::write_headers(strm, hdrs);
  4331. });
  4332. auto res = cli.Get("/hi");
  4333. EXPECT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. auto it = res->headers.find("CustomServerHeader");
  4336. EXPECT_TRUE(it != res->headers.end());
  4337. EXPECT_EQ(it->second, "CustomServerValue");
  4338. }
  4339. }
  4340. class ServerTest : public ::testing::Test {
  4341. protected:
  4342. ServerTest()
  4343. : cli_(HOST, PORT)
  4344. #ifdef CPPHTTPLIB_SSL_ENABLED
  4345. ,
  4346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4347. #endif
  4348. {
  4349. #ifdef CPPHTTPLIB_SSL_ENABLED
  4350. cli_.enable_server_certificate_verification(false);
  4351. #endif
  4352. // Allow LARGE_DATA (100MB) responses
  4353. cli_.set_payload_max_length(200 * 1024 * 1024);
  4354. }
  4355. virtual void SetUp() {
  4356. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4357. svr_.set_payload_max_length(200 * 1024 * 1024);
  4358. svr_.set_mount_point("/", "./www");
  4359. svr_.set_mount_point("/mount", "./www2");
  4360. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4361. svr_.Get("/hi",
  4362. [&](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!", "text/plain");
  4364. })
  4365. .Get("/file_content",
  4366. [&](const Request & /*req*/, Response &res) {
  4367. res.set_file_content("./www/dir/test.html");
  4368. })
  4369. .Get("/file_content_with_content_type",
  4370. [&](const Request & /*req*/, Response &res) {
  4371. res.set_file_content("./www/file", "text/plain");
  4372. })
  4373. .Get("/invalid_file_content",
  4374. [&](const Request & /*req*/, Response &res) {
  4375. res.set_file_content("./www/dir/invalid_file_path");
  4376. })
  4377. .Get("/http_response_splitting",
  4378. [&](const Request & /*req*/, Response &res) {
  4379. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4380. EXPECT_EQ(0U, res.headers.size());
  4381. EXPECT_FALSE(res.has_header("a"));
  4382. res.set_header("a", "1\nSet-Cookie: a=1");
  4383. EXPECT_EQ(0U, res.headers.size());
  4384. EXPECT_FALSE(res.has_header("a"));
  4385. res.set_header("a", "1\rSet-Cookie: a=1");
  4386. EXPECT_EQ(0U, res.headers.size());
  4387. EXPECT_FALSE(res.has_header("a"));
  4388. res.set_header("a\r\nb", "0");
  4389. EXPECT_EQ(0U, res.headers.size());
  4390. EXPECT_FALSE(res.has_header("a"));
  4391. res.set_header("a\rb", "0");
  4392. EXPECT_EQ(0U, res.headers.size());
  4393. EXPECT_FALSE(res.has_header("a"));
  4394. res.set_header("a\nb", "0");
  4395. EXPECT_EQ(0U, res.headers.size());
  4396. EXPECT_FALSE(res.has_header("a"));
  4397. res.set_redirect("1\r\nSet-Cookie: a=1");
  4398. EXPECT_EQ(0U, res.headers.size());
  4399. EXPECT_FALSE(res.has_header("Location"));
  4400. })
  4401. .Get("/slow",
  4402. [&](const Request & /*req*/, Response &res) {
  4403. std::this_thread::sleep_for(std::chrono::seconds(4));
  4404. res.set_content("slow", "text/plain");
  4405. })
  4406. #if 0
  4407. .Post("/slowpost",
  4408. [&](const Request & /*req*/, Response &res) {
  4409. std::this_thread::sleep_for(std::chrono::seconds(2));
  4410. res.set_content("slow", "text/plain");
  4411. })
  4412. #endif
  4413. .Get("/remote_addr",
  4414. [&](const Request &req, Response &res) {
  4415. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4416. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4417. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4418. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4419. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4420. #endif
  4421. res.set_content(req.remote_addr, "text/plain");
  4422. })
  4423. .Get("/local_addr",
  4424. [&](const Request &req, Response &res) {
  4425. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4426. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4428. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4429. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4430. #endif
  4431. auto local_addr = req.local_addr;
  4432. auto local_port = std::to_string(req.local_port);
  4433. res.set_content(local_addr.append(":").append(local_port),
  4434. "text/plain");
  4435. })
  4436. .Get("/endwith%",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!", "text/plain");
  4439. })
  4440. .Get("/a\\+\\+b",
  4441. [&](const Request &req, Response &res) {
  4442. ASSERT_TRUE(req.has_param("a +b"));
  4443. auto val = req.get_param_value("a +b");
  4444. res.set_content(val, "text/plain");
  4445. })
  4446. .Get("/", [&](const Request & /*req*/,
  4447. Response &res) { res.set_redirect("/hi"); })
  4448. .Post("/1",
  4449. [](const Request & /*req*/, Response &res) {
  4450. res.set_redirect("/2", StatusCode::SeeOther_303);
  4451. })
  4452. .Get("/2",
  4453. [](const Request & /*req*/, Response &res) {
  4454. res.set_content("redirected.", "text/plain");
  4455. res.status = StatusCode::OK_200;
  4456. })
  4457. .Post("/person",
  4458. [&](const Request &req, Response &res) {
  4459. if (req.has_param("name") && req.has_param("note")) {
  4460. persons_[req.get_param_value("name")] =
  4461. req.get_param_value("note");
  4462. } else {
  4463. res.status = StatusCode::BadRequest_400;
  4464. }
  4465. })
  4466. .Put("/person",
  4467. [&](const Request &req, Response &res) {
  4468. if (req.has_param("name") && req.has_param("note")) {
  4469. persons_[req.get_param_value("name")] =
  4470. req.get_param_value("note");
  4471. } else {
  4472. res.status = StatusCode::BadRequest_400;
  4473. }
  4474. })
  4475. .Get("/person/(.*)",
  4476. [&](const Request &req, Response &res) {
  4477. string name = req.matches[1];
  4478. if (persons_.find(name) != persons_.end()) {
  4479. auto note = persons_[name];
  4480. res.set_content(note, "text/plain");
  4481. } else {
  4482. res.status = StatusCode::NotFound_404;
  4483. }
  4484. })
  4485. .Delete("/person",
  4486. [&](const Request &req, Response &res) {
  4487. if (req.has_param("name")) {
  4488. string name = req.get_param_value("name");
  4489. if (persons_.find(name) != persons_.end()) {
  4490. persons_.erase(name);
  4491. res.set_content("DELETED", "text/plain");
  4492. } else {
  4493. res.status = StatusCode::NotFound_404;
  4494. }
  4495. } else {
  4496. res.status = StatusCode::BadRequest_400;
  4497. }
  4498. })
  4499. .Post("/x-www-form-urlencoded-json",
  4500. [&](const Request &req, Response &res) {
  4501. auto json = req.get_param_value("json");
  4502. ASSERT_EQ(JSON_DATA, json);
  4503. res.set_content(json, "appliation/json");
  4504. res.status = StatusCode::OK_200;
  4505. })
  4506. .Get("/streamed-chunked",
  4507. [&](const Request & /*req*/, Response &res) {
  4508. res.set_chunked_content_provider(
  4509. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4510. sink.os << "123";
  4511. sink.os << "456";
  4512. sink.os << "789";
  4513. sink.done();
  4514. return true;
  4515. });
  4516. })
  4517. .Get("/streamed-chunked-with-prohibited-trailer",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. auto i = new int(0);
  4520. // Declare both a prohibited trailer (Content-Length) and an
  4521. // allowed one
  4522. res.set_header("Trailer", "Content-Length, X-Allowed");
  4523. res.set_chunked_content_provider(
  4524. "text/plain",
  4525. [i](size_t /*offset*/, DataSink &sink) {
  4526. switch (*i) {
  4527. case 0: sink.os << "123"; break;
  4528. case 1: sink.os << "456"; break;
  4529. case 2: sink.os << "789"; break;
  4530. case 3: {
  4531. sink.done_with_trailer(
  4532. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4533. } break;
  4534. }
  4535. (*i)++;
  4536. return true;
  4537. },
  4538. [i](bool success) {
  4539. EXPECT_TRUE(success);
  4540. delete i;
  4541. });
  4542. })
  4543. .Get("/streamed-chunked2",
  4544. [&](const Request & /*req*/, Response &res) {
  4545. auto i = new int(0);
  4546. res.set_chunked_content_provider(
  4547. "text/plain",
  4548. [i](size_t /*offset*/, DataSink &sink) {
  4549. switch (*i) {
  4550. case 0: sink.os << "123"; break;
  4551. case 1: sink.os << "456"; break;
  4552. case 2: sink.os << "789"; break;
  4553. case 3: sink.done(); break;
  4554. }
  4555. (*i)++;
  4556. return true;
  4557. },
  4558. [i](bool success) {
  4559. EXPECT_TRUE(success);
  4560. delete i;
  4561. });
  4562. })
  4563. .Get("/streamed-chunked-with-trailer",
  4564. [&](const Request & /*req*/, Response &res) {
  4565. auto i = new int(0);
  4566. res.set_header("Trailer", "Dummy1, Dummy2");
  4567. res.set_chunked_content_provider(
  4568. "text/plain",
  4569. [i](size_t /*offset*/, DataSink &sink) {
  4570. switch (*i) {
  4571. case 0: sink.os << "123"; break;
  4572. case 1: sink.os << "456"; break;
  4573. case 2: sink.os << "789"; break;
  4574. case 3: {
  4575. sink.done_with_trailer(
  4576. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4577. } break;
  4578. }
  4579. (*i)++;
  4580. return true;
  4581. },
  4582. [i](bool success) {
  4583. EXPECT_TRUE(success);
  4584. delete i;
  4585. });
  4586. })
  4587. .Get("/streamed",
  4588. [&](const Request & /*req*/, Response &res) {
  4589. res.set_content_provider(
  4590. 6, "text/plain",
  4591. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4592. sink.os << (offset < 3 ? "a" : "b");
  4593. return true;
  4594. });
  4595. })
  4596. .Get("/streamed-without-length",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. auto data = new std::string("abcdefg");
  4599. res.set_content_provider(
  4600. "text/plain",
  4601. [data](size_t offset, DataSink &sink) {
  4602. if (offset < data->size()) {
  4603. sink.os << data->substr(offset);
  4604. }
  4605. sink.done();
  4606. return true;
  4607. },
  4608. [data](bool success) {
  4609. EXPECT_TRUE(success);
  4610. delete data;
  4611. });
  4612. })
  4613. .Get("/streamed-with-range",
  4614. [&](const Request &req, Response &res) {
  4615. auto data = new std::string("abcdefg");
  4616. // An explicit status keeps the server from picking the 206 it
  4617. // would otherwise choose for a ranged request, so the response
  4618. // is not a partial representation.
  4619. auto status = req.get_param_value("status");
  4620. if (status == "200") {
  4621. res.status = StatusCode::OK_200;
  4622. } else if (status == "403") {
  4623. res.status = StatusCode::Forbidden_403;
  4624. }
  4625. res.set_content_provider(
  4626. data->size(), "text/plain",
  4627. [data](size_t offset, size_t length, DataSink &sink) {
  4628. size_t DATA_CHUNK_SIZE = 4;
  4629. const auto &d = *data;
  4630. auto out_len =
  4631. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4632. auto ret =
  4633. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4634. EXPECT_TRUE(ret);
  4635. return true;
  4636. },
  4637. [data, &req](bool success) {
  4638. EXPECT_EQ(success, !req.has_param("error"));
  4639. delete data;
  4640. });
  4641. })
  4642. .Get("/streamed-cancel",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content_provider(
  4645. size_t(-1), "text/plain",
  4646. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4647. sink.os << "data_chunk";
  4648. return true;
  4649. });
  4650. })
  4651. .Get("/regex-with-delimiter",
  4652. [&](const Request &req, Response & /*res*/) {
  4653. ASSERT_TRUE(req.has_param("key"));
  4654. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4655. })
  4656. .Get("/with-range",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. res.set_content("abcdefg", "text/plain");
  4659. })
  4660. .Get("/test-start-time",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. EXPECT_NE(req.start_time_,
  4663. std::chrono::steady_clock::time_point::min());
  4664. })
  4665. .Get("/with-range-customized-response",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. res.status = StatusCode::BadRequest_400;
  4668. res.set_content(JSON_DATA, "application/json");
  4669. })
  4670. .Post("/chunked",
  4671. [&](const Request &req, Response & /*res*/) {
  4672. EXPECT_EQ(req.body, "dechunked post body");
  4673. })
  4674. .Post("/large-chunked",
  4675. [&](const Request &req, Response & /*res*/) {
  4676. std::string expected(6 * 30 * 1024u, 'a');
  4677. EXPECT_EQ(req.body, expected);
  4678. })
  4679. .Post("/multipart",
  4680. [&](const Request &req, Response & /*res*/) {
  4681. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4682. req.form.get_field_count("text2") +
  4683. req.form.get_field_count("file3") +
  4684. req.form.get_field_count("file4"));
  4685. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4686. req.form.get_file_count("file2"));
  4687. ASSERT_TRUE(!req.form.has_file("???"));
  4688. ASSERT_TRUE(!req.form.has_field("???"));
  4689. ASSERT_TRUE(req.body.empty());
  4690. {
  4691. const auto &text = req.form.get_field("text1");
  4692. EXPECT_EQ("text default", text);
  4693. }
  4694. {
  4695. const auto &text = req.form.get_field("text2");
  4696. EXPECT_EQ("aωb", text);
  4697. }
  4698. {
  4699. const auto &file = req.form.get_file("file1");
  4700. EXPECT_EQ("hello.txt", file.filename);
  4701. EXPECT_EQ("text/plain", file.content_type);
  4702. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4703. }
  4704. {
  4705. const auto &file = req.form.get_file("file2");
  4706. EXPECT_EQ("world.json", file.filename);
  4707. EXPECT_EQ("application/json", file.content_type);
  4708. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4709. }
  4710. {
  4711. const auto &text = req.form.get_field("file3");
  4712. EXPECT_EQ(0u, text.size());
  4713. }
  4714. {
  4715. const auto &text = req.form.get_field("file4");
  4716. EXPECT_EQ(0u, text.size());
  4717. }
  4718. })
  4719. .Post("/multipart/multi_file_values",
  4720. [&](const Request &req, Response & /*res*/) {
  4721. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4722. req.form.get_field_count("multi_text1"));
  4723. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4724. ASSERT_TRUE(!req.form.has_file("???"));
  4725. ASSERT_TRUE(!req.form.has_field("???"));
  4726. ASSERT_TRUE(req.body.empty());
  4727. {
  4728. const auto &text = req.form.get_field("text");
  4729. EXPECT_EQ("default text", text);
  4730. }
  4731. {
  4732. const auto &text1_values = req.form.get_fields("multi_text1");
  4733. EXPECT_EQ(2u, text1_values.size());
  4734. EXPECT_EQ("aaaaa", text1_values[0]);
  4735. EXPECT_EQ("bbbbb", text1_values[1]);
  4736. }
  4737. {
  4738. const auto &file1_values = req.form.get_files("multi_file1");
  4739. EXPECT_EQ(2u, file1_values.size());
  4740. auto file1 = file1_values[0];
  4741. EXPECT_EQ(file1.filename, "hello.txt");
  4742. EXPECT_EQ(file1.content_type, "text/plain");
  4743. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4744. auto file2 = file1_values[1];
  4745. EXPECT_EQ(file2.filename, "world.json");
  4746. EXPECT_EQ(file2.content_type, "application/json");
  4747. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4748. }
  4749. })
  4750. .Post("/empty",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("empty", "text/plain");
  4756. })
  4757. .Post("/empty-no-content-type",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_FALSE(req.has_header("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. res.set_content("empty-no-content-type", "text/plain");
  4763. })
  4764. .Post("/path-only",
  4765. [&](const Request &req, Response &res) {
  4766. EXPECT_EQ(req.body, "");
  4767. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4768. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4769. res.set_content("path-only", "text/plain");
  4770. })
  4771. .Post("/path-headers-only",
  4772. [&](const Request &req, Response &res) {
  4773. EXPECT_EQ(req.body, "");
  4774. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4775. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4776. EXPECT_EQ("world", req.get_header_value("hello"));
  4777. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4778. res.set_content("path-headers-only", "text/plain");
  4779. })
  4780. .Post("/post-large",
  4781. [&](const Request &req, Response &res) {
  4782. EXPECT_EQ(req.body, LARGE_DATA);
  4783. res.set_content(req.body, "text/plain");
  4784. })
  4785. .Post("/post-loopback",
  4786. [&](const Request &, Response &res,
  4787. ContentReader const &content_reader) {
  4788. std::string body;
  4789. content_reader([&](const char *data, size_t data_length) {
  4790. body.append(data, data_length);
  4791. return true;
  4792. });
  4793. res.set_content(body, "text/plain");
  4794. })
  4795. .Put("/put-loopback",
  4796. [&](const Request &, Response &res,
  4797. ContentReader const &content_reader) {
  4798. std::string body;
  4799. content_reader([&](const char *data, size_t data_length) {
  4800. body.append(data, data_length);
  4801. return true;
  4802. });
  4803. res.set_content(body, "text/plain");
  4804. })
  4805. .Patch("/patch-loopback",
  4806. [&](const Request &, Response &res,
  4807. ContentReader const &content_reader) {
  4808. std::string body;
  4809. content_reader([&](const char *data, size_t data_length) {
  4810. body.append(data, data_length);
  4811. return true;
  4812. });
  4813. res.set_content(body, "text/plain");
  4814. })
  4815. .Put("/empty-no-content-type",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, "");
  4818. EXPECT_FALSE(req.has_header("Content-Type"));
  4819. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4820. res.set_content("empty-no-content-type", "text/plain");
  4821. })
  4822. .Put("/put",
  4823. [&](const Request &req, Response &res) {
  4824. EXPECT_EQ(req.body, "PUT");
  4825. res.set_content(req.body, "text/plain");
  4826. })
  4827. .Put("/put-large",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, LARGE_DATA);
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Patch("/patch",
  4833. [&](const Request &req, Response &res) {
  4834. EXPECT_EQ(req.body, "PATCH");
  4835. res.set_content(req.body, "text/plain");
  4836. })
  4837. .Delete("/delete",
  4838. [&](const Request & /*req*/, Response &res) {
  4839. res.set_content("DELETE", "text/plain");
  4840. })
  4841. .Delete("/delete-body",
  4842. [&](const Request &req, Response &res) {
  4843. EXPECT_EQ(req.body, "content");
  4844. res.set_content(req.body, "text/plain");
  4845. })
  4846. .Options(R"(\*)",
  4847. [&](const Request & /*req*/, Response &res) {
  4848. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4849. })
  4850. .CustomRoute("PROPFIND", "/dav/:id",
  4851. [&](const Request &req, Response &res) {
  4852. res.set_header("x-body-size",
  4853. std::to_string(req.body.size()));
  4854. res.set_header("x-matched-route", req.matched_route);
  4855. res.set_header("x-dav-id", req.path_params.at("id"));
  4856. res.status = StatusCode::MultiStatus_207;
  4857. res.set_content(req.body, "application/xml");
  4858. })
  4859. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4860. [&](const Request &req, Response &res) {
  4861. res.set_header("x-dav-match", req.matches[1]);
  4862. res.status = StatusCode::MultiStatus_207;
  4863. })
  4864. .CustomRoute("MKCOL", "/dav-mkcol",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_TRUE(req.body.empty());
  4867. res.status = StatusCode::Created_201;
  4868. })
  4869. .CustomRoute(
  4870. "REPORT", "/dav-report",
  4871. [&](const Request & /*req*/, Response &res,
  4872. const ContentReader &content_reader) {
  4873. std::string body;
  4874. content_reader([&](const char *data, size_t data_length) {
  4875. body.append(data, data_length);
  4876. return true;
  4877. });
  4878. res.set_header("x-body-size", std::to_string(body.size()));
  4879. res.status = StatusCode::MultiStatus_207;
  4880. res.set_content(body, "application/xml");
  4881. })
  4882. .Get("/request-target",
  4883. [&](const Request &req, Response & /*res*/) {
  4884. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4885. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4886. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4887. })
  4888. .Get("/long-query-value",
  4889. [&](const Request &req, Response & /*res*/) {
  4890. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4891. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4892. })
  4893. .Get("/too-long-query-value",
  4894. [&](const Request &req, Response & /*res*/) {
  4895. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4896. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4897. })
  4898. .Get("/array-param",
  4899. [&](const Request &req, Response & /*res*/) {
  4900. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4901. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4902. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4903. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4904. })
  4905. .Get("/array-param-values",
  4906. [&](const Request &req, Response & /*res*/) {
  4907. auto values = req.get_param_values("array");
  4908. EXPECT_EQ(3u, values.size());
  4909. EXPECT_EQ("value1", values[0]);
  4910. EXPECT_EQ("value2", values[1]);
  4911. EXPECT_EQ("value3", values[2]);
  4912. auto empty = req.get_param_values("nonexistent");
  4913. EXPECT_TRUE(empty.empty());
  4914. })
  4915. .Post("/validate-no-multiple-headers",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4918. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4919. })
  4920. .Post("/content_receiver",
  4921. [&](const Request &req, Response &res,
  4922. const ContentReader &content_reader) {
  4923. if (req.is_multipart_form_data()) {
  4924. std::vector<FormData> items;
  4925. content_reader(
  4926. [&](const FormData &file) {
  4927. items.push_back(file);
  4928. return true;
  4929. },
  4930. [&](const char *data, size_t data_length) {
  4931. items.back().content.append(data, data_length);
  4932. return true;
  4933. });
  4934. EXPECT_EQ(5u, items.size());
  4935. {
  4936. const auto &file = get_file_value(items, "text1");
  4937. EXPECT_TRUE(file.filename.empty());
  4938. EXPECT_EQ("text default", file.content);
  4939. }
  4940. {
  4941. const auto &file = get_file_value(items, "text2");
  4942. EXPECT_TRUE(file.filename.empty());
  4943. EXPECT_EQ("aωb", file.content);
  4944. }
  4945. {
  4946. const auto &file = get_file_value(items, "file1");
  4947. EXPECT_EQ("hello.txt", file.filename);
  4948. EXPECT_EQ("text/plain", file.content_type);
  4949. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4950. }
  4951. {
  4952. const auto &file = get_file_value(items, "file2");
  4953. EXPECT_EQ("world.json", file.filename);
  4954. EXPECT_EQ("application/json", file.content_type);
  4955. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4956. }
  4957. {
  4958. const auto &file = get_file_value(items, "file3");
  4959. EXPECT_TRUE(file.filename.empty());
  4960. EXPECT_EQ("application/octet-stream", file.content_type);
  4961. EXPECT_EQ(0u, file.content.size());
  4962. }
  4963. } else {
  4964. std::string body;
  4965. content_reader([&](const char *data, size_t data_length) {
  4966. EXPECT_EQ(7U, data_length);
  4967. body.append(data, data_length);
  4968. return true;
  4969. });
  4970. EXPECT_EQ(body, "content");
  4971. res.set_content(body, "text/plain");
  4972. }
  4973. })
  4974. .Put("/content_receiver",
  4975. [&](const Request & /*req*/, Response &res,
  4976. const ContentReader &content_reader) {
  4977. std::string body;
  4978. content_reader([&](const char *data, size_t data_length) {
  4979. body.append(data, data_length);
  4980. return true;
  4981. });
  4982. EXPECT_EQ(body, "content");
  4983. res.set_content(body, "text/plain");
  4984. })
  4985. .Patch("/content_receiver",
  4986. [&](const Request & /*req*/, Response &res,
  4987. const ContentReader &content_reader) {
  4988. std::string body;
  4989. content_reader([&](const char *data, size_t data_length) {
  4990. body.append(data, data_length);
  4991. return true;
  4992. });
  4993. EXPECT_EQ(body, "content");
  4994. res.set_content(body, "text/plain");
  4995. })
  4996. .Post("/query-string-and-body",
  4997. [&](const Request &req, Response & /*res*/) {
  4998. ASSERT_TRUE(req.has_param("key"));
  4999. EXPECT_EQ(req.get_param_value("key"), "value");
  5000. EXPECT_EQ(req.body, "content");
  5001. })
  5002. .Get("/last-request",
  5003. [&](const Request &req, Response & /*res*/) {
  5004. EXPECT_EQ("close", req.get_header_value("Connection"));
  5005. })
  5006. .Get(R"(/redirect/(\d+))",
  5007. [&](const Request &req, Response &res) {
  5008. auto num = std::stoi(req.matches[1]) + 1;
  5009. std::string url = "/redirect/" + std::to_string(num);
  5010. res.set_redirect(url);
  5011. })
  5012. .Post("/binary",
  5013. [&](const Request &req, Response &res) {
  5014. EXPECT_EQ(4U, req.body.size());
  5015. EXPECT_EQ("application/octet-stream",
  5016. req.get_header_value("Content-Type"));
  5017. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5018. res.set_content(req.body, "application/octet-stream");
  5019. })
  5020. .Put("/binary",
  5021. [&](const Request &req, Response &res) {
  5022. EXPECT_EQ(4U, req.body.size());
  5023. EXPECT_EQ("application/octet-stream",
  5024. req.get_header_value("Content-Type"));
  5025. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5026. res.set_content(req.body, "application/octet-stream");
  5027. })
  5028. .Patch("/binary",
  5029. [&](const Request &req, Response &res) {
  5030. EXPECT_EQ(4U, req.body.size());
  5031. EXPECT_EQ("application/octet-stream",
  5032. req.get_header_value("Content-Type"));
  5033. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5034. res.set_content(req.body, "application/octet-stream");
  5035. })
  5036. .Delete("/binary",
  5037. [&](const Request &req, Response &res) {
  5038. EXPECT_EQ(4U, req.body.size());
  5039. EXPECT_EQ("application/octet-stream",
  5040. req.get_header_value("Content-Type"));
  5041. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5042. res.set_content(req.body, "application/octet-stream");
  5043. })
  5044. .Get("/issue1772",
  5045. [&](const Request & /*req*/, Response &res) {
  5046. res.status = 401;
  5047. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5048. })
  5049. .Delete("/issue609",
  5050. [](const httplib::Request &, httplib::Response &res,
  5051. const httplib::ContentReader &) {
  5052. res.set_content("ok", "text/plain");
  5053. })
  5054. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5055. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5056. .Get("/compress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "text/plain");
  5062. })
  5063. .Get("/compress-with-charset",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. res.set_content(
  5066. "12345678901234567890123456789012345678901234567890123456789"
  5067. "01234567890123456789012345678901234567890",
  5068. "application/json; charset=utf-8");
  5069. })
  5070. .Get("/nocompress",
  5071. [&](const Request & /*req*/, Response &res) {
  5072. res.set_content(
  5073. "12345678901234567890123456789012345678901234567890123456789"
  5074. "01234567890123456789012345678901234567890",
  5075. "application/octet-stream");
  5076. })
  5077. .Post("/compress-multipart",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(2u, req.form.fields.size());
  5080. ASSERT_TRUE(!req.form.has_field("???"));
  5081. {
  5082. const auto &text = req.form.get_field("key1");
  5083. EXPECT_EQ("test", text);
  5084. }
  5085. {
  5086. const auto &text = req.form.get_field("key2");
  5087. EXPECT_EQ("--abcdefg123", text);
  5088. }
  5089. })
  5090. #endif
  5091. ;
  5092. persons_["john"] = "programmer";
  5093. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5094. svr_.wait_until_ready();
  5095. }
  5096. virtual void TearDown() {
  5097. svr_.stop();
  5098. if (!request_threads_.empty()) {
  5099. std::this_thread::sleep_for(std::chrono::seconds(1));
  5100. for (auto &t : request_threads_) {
  5101. t.join();
  5102. }
  5103. }
  5104. t_.join();
  5105. }
  5106. map<string, string> persons_;
  5107. #ifdef CPPHTTPLIB_SSL_ENABLED
  5108. SSLClient cli_;
  5109. SSLServer svr_;
  5110. #else
  5111. Client cli_;
  5112. Server svr_;
  5113. #endif
  5114. thread t_;
  5115. std::vector<thread> request_threads_;
  5116. };
  5117. TEST_F(ServerTest, GetMethod200) {
  5118. auto res = cli_.Get("/hi");
  5119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5120. EXPECT_EQ("HTTP/1.1", res->version);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("OK", res->reason);
  5123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5124. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5125. EXPECT_EQ("Hello World!", res->body);
  5126. }
  5127. TEST_F(ServerTest, GetEmptyFile) {
  5128. auto res = cli_.Get("/empty_file");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5133. EXPECT_EQ("", res->body);
  5134. }
  5135. TEST_F(ServerTest, GetFileContent) {
  5136. auto res = cli_.Get("/file_content");
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5140. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5141. EXPECT_EQ("test.html", res->body);
  5142. }
  5143. TEST_F(ServerTest, GetFileContentWithRange) {
  5144. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5147. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5149. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5150. EXPECT_EQ("est", res->body);
  5151. }
  5152. TEST_F(ServerTest, GetFileContentWithContentType) {
  5153. auto res = cli_.Get("/file_content_with_content_type");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5158. EXPECT_EQ("file\n", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetInvalidFileContent) {
  5161. auto res = cli_.Get("/invalid_file_content");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5164. }
  5165. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5166. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5168. EXPECT_EQ("HTTP/1.1", res->version);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5171. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5172. EXPECT_EQ("Hello World!", res->body);
  5173. }
  5174. TEST_F(ServerTest, GetMethod302) {
  5175. auto res = cli_.Get("/");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Found_302, res->status);
  5178. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5179. }
  5180. TEST_F(ServerTest, GetMethod302Redirect) {
  5181. cli_.set_follow_location(true);
  5182. auto res = cli_.Get("/");
  5183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("Hello World!", res->body);
  5186. EXPECT_EQ("/hi", res->location);
  5187. }
  5188. TEST_F(ServerTest, GetMethod404) {
  5189. auto res = cli_.Get("/invalid");
  5190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5192. }
  5193. TEST_F(ServerTest, HeadMethod200) {
  5194. auto res = cli_.Head("/hi");
  5195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, HeadMethod200Static) {
  5201. auto res = cli_.Head("/mount/dir/index.html");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5206. EXPECT_TRUE(res->body.empty());
  5207. }
  5208. TEST_F(ServerTest, HeadMethod404) {
  5209. auto res = cli_.Head("/invalid");
  5210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5212. EXPECT_TRUE(res->body.empty());
  5213. }
  5214. TEST_F(ServerTest, GetMethodPersonJohn) {
  5215. auto res = cli_.Get("/person/john");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. EXPECT_EQ("programmer", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod1) {
  5222. auto res = cli_.Get("/person/john1");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. res = cli_.Post("/person", "name=john1&note=coder",
  5226. "application/x-www-form-urlencoded");
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. ASSERT_EQ(StatusCode::OK_200, res->status);
  5229. res = cli_.Get("/person/john1");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. ASSERT_EQ(StatusCode::OK_200, res->status);
  5232. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. ASSERT_EQ("coder", res->body);
  5234. }
  5235. TEST_F(ServerTest, PostMethod2) {
  5236. auto res = cli_.Get("/person/john2");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5239. Params params;
  5240. params.emplace("name", "john2");
  5241. params.emplace("note", "coder");
  5242. res = cli_.Post("/person", params);
  5243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5244. ASSERT_EQ(StatusCode::OK_200, res->status);
  5245. res = cli_.Get("/person/john2");
  5246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5247. ASSERT_EQ(StatusCode::OK_200, res->status);
  5248. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. ASSERT_EQ("coder", res->body);
  5250. }
  5251. TEST_F(ServerTest, PutMethod3) {
  5252. auto res = cli_.Get("/person/john3");
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5255. Params params;
  5256. params.emplace("name", "john3");
  5257. params.emplace("note", "coder");
  5258. res = cli_.Put("/person", params);
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. ASSERT_EQ(StatusCode::OK_200, res->status);
  5261. res = cli_.Get("/person/john3");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5265. ASSERT_EQ("coder", res->body);
  5266. }
  5267. TEST_F(ServerTest, DeleteMethod1) {
  5268. auto res = cli_.Get("/person/john4");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5271. Params params;
  5272. params.emplace("name", "john4");
  5273. params.emplace("note", "coder");
  5274. res = cli_.Post("/person", params);
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::OK_200, res->status);
  5277. res = cli_.Get("/person/john4");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5281. ASSERT_EQ("coder", res->body);
  5282. Params delete_params;
  5283. delete_params.emplace("name", "john4");
  5284. res = cli_.Delete("/person", delete_params);
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ("DELETED", res->body);
  5288. res = cli_.Get("/person/john4");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5291. }
  5292. TEST_F(ServerTest, DeleteMethod2) {
  5293. auto res = cli_.Get("/person/john5");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5296. Params params;
  5297. params.emplace("name", "john5");
  5298. params.emplace("note", "developer");
  5299. res = cli_.Post("/person", params);
  5300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5301. ASSERT_EQ(StatusCode::OK_200, res->status);
  5302. res = cli_.Get("/person/john5");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. ASSERT_EQ(StatusCode::OK_200, res->status);
  5305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. ASSERT_EQ("developer", res->body);
  5307. Params delete_params;
  5308. delete_params.emplace("name", "john5");
  5309. Headers headers;
  5310. headers.emplace("Custom-Header", "test-value");
  5311. res = cli_.Delete("/person", headers, delete_params);
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. ASSERT_EQ(StatusCode::OK_200, res->status);
  5314. ASSERT_EQ("DELETED", res->body);
  5315. res = cli_.Get("/person/john5");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5318. }
  5319. TEST_F(ServerTest, DeleteMethod3) {
  5320. auto res = cli_.Get("/person/john6");
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5323. Params params;
  5324. params.emplace("name", "john6");
  5325. params.emplace("note", "tester");
  5326. res = cli_.Post("/person", params);
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john6");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("tester", res->body);
  5334. Params delete_params;
  5335. delete_params.emplace("name", "john6");
  5336. Headers headers;
  5337. headers.emplace("Custom-Header", "test-value");
  5338. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5340. ASSERT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ("DELETED", res->body);
  5342. res = cli_.Get("/person/john6");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5347. Params params;
  5348. params.emplace("json", JSON_DATA);
  5349. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. ASSERT_EQ(StatusCode::OK_200, res->status);
  5352. ASSERT_EQ(JSON_DATA, res->body);
  5353. }
  5354. TEST_F(ServerTest, PostEmptyContent) {
  5355. auto res = cli_.Post("/empty", "", "text/plain");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::OK_200, res->status);
  5358. ASSERT_EQ("empty", res->body);
  5359. }
  5360. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5361. auto res = cli_.Post("/empty-no-content-type");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("empty-no-content-type", res->body);
  5365. }
  5366. TEST_F(ServerTest, PostPathOnly) {
  5367. auto res = cli_.Post("/path-only");
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. ASSERT_EQ(StatusCode::OK_200, res->status);
  5370. ASSERT_EQ("path-only", res->body);
  5371. }
  5372. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5373. auto res = cli_.Post("/path-headers-only",
  5374. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. ASSERT_EQ("path-headers-only", res->body);
  5378. }
  5379. TEST_F(ServerTest, PostLarge) {
  5380. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. ASSERT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ(LARGE_DATA, res->body);
  5384. }
  5385. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5386. auto res = cli_.Put("/empty-no-content-type");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. ASSERT_EQ("empty-no-content-type", res->body);
  5390. }
  5391. TEST_F(ServerTest, GetMethodDir) {
  5392. auto res = cli_.Get("/dir/");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5396. auto body = R"(<html>
  5397. <head>
  5398. </head>
  5399. <body>
  5400. <a href="/dir/test.html">Test</a>
  5401. <a href="/hi">hi</a>
  5402. </body>
  5403. </html>
  5404. )";
  5405. EXPECT_EQ(body, res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodDirTest) {
  5408. auto res = cli_.Get("/dir/test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::OK_200, res->status);
  5411. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5412. EXPECT_EQ("test.html", res->body);
  5413. }
  5414. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5415. auto res = cli_.Get("/dir/../dir/test.html");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("test.html", res->body);
  5420. }
  5421. TEST_F(ServerTest, GetMethodInvalidPath) {
  5422. auto res = cli_.Get("/dir/../test.html");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5425. }
  5426. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5427. auto res = cli_.Get("/../www/dir/test.html");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5430. }
  5431. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5432. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5435. }
  5436. TEST_F(ServerTest, GetMethodDirMountTest) {
  5437. auto res = cli_.Get("/mount/dir/test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5441. EXPECT_EQ("test.html", res->body);
  5442. }
  5443. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5444. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5448. EXPECT_EQ("test.html", res->body);
  5449. }
  5450. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5451. auto res = cli_.Get("/mount/dir/../test.html");
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5454. }
  5455. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5456. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5459. }
  5460. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5461. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5464. }
  5465. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5466. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5471. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, PostMethod303) {
  5476. auto res = cli_.Post("/1", "body", "text/plain");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5479. EXPECT_EQ("/2", res->get_header_value("Location"));
  5480. }
  5481. TEST_F(ServerTest, PostMethod303Redirect) {
  5482. cli_.set_follow_location(true);
  5483. auto res = cli_.Post("/1", "body", "text/plain");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("redirected.", res->body);
  5487. EXPECT_EQ("/2", res->location);
  5488. }
  5489. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5490. auto res = cli_.Get("/dir/test.abcde");
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("abcde", res->body);
  5495. }
  5496. TEST_F(ServerTest, StaticFileRange) {
  5497. auto res =
  5498. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5500. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5501. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(true, res->has_header("Content-Range"));
  5504. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5505. EXPECT_EQ(std::string("cd"), res->body);
  5506. }
  5507. TEST_F(ServerTest, StaticFileRanges) {
  5508. auto res = cli_.Get("/dir/test.abcde",
  5509. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5512. EXPECT_TRUE(
  5513. res->get_header_value("Content-Type")
  5514. .find(
  5515. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5516. 0);
  5517. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5518. }
  5519. TEST_F(ServerTest, StaticFileRangeHead) {
  5520. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5523. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5524. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5525. EXPECT_EQ(true, res->has_header("Content-Range"));
  5526. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5527. }
  5528. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5529. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5533. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5534. EXPECT_EQ(true, res->has_header("Content-Range"));
  5535. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5536. res->get_header_value("Content-Range"));
  5537. EXPECT_EQ("LAST\n", res->body);
  5538. }
  5539. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5540. auto res =
  5541. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5544. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5545. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5546. EXPECT_EQ(true, res->has_header("Content-Range"));
  5547. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5548. }
  5549. TEST_F(ServerTest, StaticFileBigFile) {
  5550. auto res = cli_.Get("/dir/1MB.txt");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5555. }
  5556. TEST_F(ServerTest, InvalidBaseDirMount) {
  5557. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5558. }
  5559. TEST_F(ServerTest, Binary) {
  5560. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5561. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5562. "application/octet-stream");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. ASSERT_EQ(StatusCode::OK_200, res->status);
  5565. ASSERT_EQ(4U, res->body.size());
  5566. res = cli_.Put("/binary", binary.data(), binary.size(),
  5567. "application/octet-stream");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. ASSERT_EQ(StatusCode::OK_200, res->status);
  5570. ASSERT_EQ(4U, res->body.size());
  5571. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5572. "application/octet-stream");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. ASSERT_EQ(StatusCode::OK_200, res->status);
  5575. ASSERT_EQ(4U, res->body.size());
  5576. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5577. "application/octet-stream");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. ASSERT_EQ(4U, res->body.size());
  5581. }
  5582. TEST_F(ServerTest, BinaryString) {
  5583. auto binary = std::string("\x00\x01\x02\x03", 4);
  5584. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. ASSERT_EQ(4U, res->body.size());
  5588. res = cli_.Put("/binary", binary, "application/octet-stream");
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. ASSERT_EQ(StatusCode::OK_200, res->status);
  5591. ASSERT_EQ(4U, res->body.size());
  5592. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. ASSERT_EQ(StatusCode::OK_200, res->status);
  5595. ASSERT_EQ(4U, res->body.size());
  5596. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. ASSERT_EQ(StatusCode::OK_200, res->status);
  5599. ASSERT_EQ(4U, res->body.size());
  5600. }
  5601. TEST_F(ServerTest, EmptyRequest) {
  5602. auto res = cli_.Get("");
  5603. ASSERT_TRUE(!res);
  5604. EXPECT_EQ(Error::Connection, res.error());
  5605. }
  5606. TEST_F(ServerTest, LongRequest) {
  5607. std::string request;
  5608. for (size_t i = 0; i < 545; i++) {
  5609. request += "/TooLongRequest";
  5610. }
  5611. request += "OK";
  5612. auto res = cli_.Get(request.c_str());
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5615. }
  5616. TEST_F(ServerTest, TooLongRequest) {
  5617. std::string request;
  5618. for (size_t i = 0; i < 546; i++) {
  5619. request += "/TooLongRequest";
  5620. }
  5621. request += "_NG";
  5622. auto start = std::chrono::high_resolution_clock::now();
  5623. cli_.set_keep_alive(true);
  5624. auto res = cli_.Get(request.c_str());
  5625. auto end = std::chrono::high_resolution_clock::now();
  5626. auto elapsed =
  5627. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5628. .count();
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5631. EXPECT_LE(elapsed, 1000);
  5632. EXPECT_EQ("close", res->get_header_value("Connection"));
  5633. EXPECT_FALSE(cli_.is_socket_open());
  5634. }
  5635. TEST_F(ServerTest, AlmostTooLongRequest) {
  5636. // test for #2046 - URI length check shouldn't include other content on req
  5637. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5638. // leading /, space, HTTP/1.1)
  5639. std::string request =
  5640. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5641. auto res = cli_.Get(request.c_str());
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5644. }
  5645. TEST_F(ServerTest, LongHeader) {
  5646. Request req;
  5647. req.method = "GET";
  5648. req.path = "/hi";
  5649. std::string host_and_port;
  5650. host_and_port += HOST;
  5651. host_and_port += ":";
  5652. host_and_port += std::to_string(PORT);
  5653. req.headers.emplace("Host", host_and_port.c_str());
  5654. req.headers.emplace("Accept", "*/*");
  5655. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5656. req.headers.emplace(
  5657. "Header-Name",
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@");
  5687. auto res = std::make_shared<Response>();
  5688. auto error = Error::Success;
  5689. auto ret = cli_.send(req, *res, error);
  5690. ASSERT_TRUE(ret);
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. }
  5693. TEST_F(ServerTest, LongQueryValue) {
  5694. auto start = std::chrono::high_resolution_clock::now();
  5695. cli_.set_keep_alive(true);
  5696. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5697. auto end = std::chrono::high_resolution_clock::now();
  5698. auto elapsed =
  5699. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5700. .count();
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5703. EXPECT_LE(elapsed, 1000);
  5704. EXPECT_EQ("close", res->get_header_value("Connection"));
  5705. EXPECT_FALSE(cli_.is_socket_open());
  5706. }
  5707. TEST_F(ServerTest, TooLongQueryValue) {
  5708. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5709. ASSERT_FALSE(res);
  5710. EXPECT_EQ(Error::Read, res.error());
  5711. }
  5712. TEST_F(ServerTest, TooLongHeader) {
  5713. Request req;
  5714. req.method = "GET";
  5715. req.path = "/hi";
  5716. std::string host_and_port;
  5717. host_and_port += HOST;
  5718. host_and_port += ":";
  5719. host_and_port += std::to_string(PORT);
  5720. req.headers.emplace("Host", host_and_port.c_str());
  5721. req.headers.emplace("Accept", "*/*");
  5722. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5723. req.headers.emplace(
  5724. "Header-Name",
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5753. "@@@@@@@@@@@@@@@@@");
  5754. auto res = std::make_shared<Response>();
  5755. auto error = Error::Success;
  5756. auto ret = cli_.send(req, *res, error);
  5757. ASSERT_TRUE(ret);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. }
  5760. TEST_F(ServerTest, HeaderCountAtLimit) {
  5761. // Test with headers just under the 100 limit
  5762. httplib::Headers headers;
  5763. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5764. // This should keep us just under the 100 header limit
  5765. for (int i = 0; i < 95; i++) {
  5766. std::string name = "X-Test-Header-" + std::to_string(i);
  5767. std::string value = "value" + std::to_string(i);
  5768. headers.emplace(name, value);
  5769. }
  5770. // This should work fine as we're under the limit
  5771. auto res = cli_.Get("/hi", headers);
  5772. EXPECT_TRUE(res);
  5773. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5774. }
  5775. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5776. // Test with many headers to exceed the 100 limit
  5777. httplib::Headers headers;
  5778. // Add 150 headers to definitely exceed the 100 limit
  5779. for (int i = 0; i < 150; i++) {
  5780. std::string name = "X-Test-Header-" + std::to_string(i);
  5781. std::string value = "value" + std::to_string(i);
  5782. headers.emplace(name, value);
  5783. }
  5784. // This should fail due to exceeding header count limit
  5785. cli_.set_keep_alive(true);
  5786. auto res = cli_.Get("/hi", headers);
  5787. // The server should respond with 400 Bad Request
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5790. EXPECT_EQ("close", res->get_header_value("Connection"));
  5791. EXPECT_FALSE(cli_.is_socket_open());
  5792. }
  5793. TEST_F(ServerTest, PercentEncoding) {
  5794. auto res = cli_.Get("/e%6edwith%");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, PercentEncodingUnicode) {
  5799. auto res = cli_.Get("/e%u006edwith%");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. }
  5803. TEST_F(ServerTest, InvalidPercentEncoding) {
  5804. auto res = cli_.Get("/%endwith%");
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5807. }
  5808. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5809. auto res = cli_.Get("/%uendwith%");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5814. auto res = cli_.Get("/hello?aaa=bbb%");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, PlusSignEncoding) {
  5819. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("a +b", res->body);
  5823. }
  5824. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5825. // This test simulates a potential DoS attack using many headers
  5826. // to verify our security fix prevents memory exhaustion
  5827. httplib::Headers attack_headers;
  5828. // Attempt to add many headers like an attacker would (200 headers to far
  5829. // exceed limit)
  5830. for (int i = 0; i < 200; i++) {
  5831. std::string name = "X-Attack-Header-" + std::to_string(i);
  5832. std::string value = "attack_payload_" + std::to_string(i);
  5833. attack_headers.emplace(name, value);
  5834. }
  5835. // Try to POST with excessive headers
  5836. cli_.set_keep_alive(true);
  5837. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5838. // Should either fail or return 400 Bad Request due to security limit
  5839. if (res) {
  5840. // If we get a response, it should be 400 Bad Request
  5841. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5842. EXPECT_EQ("close", res->get_header_value("Connection"));
  5843. }
  5844. EXPECT_FALSE(cli_.is_socket_open());
  5845. }
  5846. TEST_F(ServerTest, MultipartFormData) {
  5847. UploadFormDataItems items = {
  5848. {"text1", "text default", "", ""},
  5849. {"text2", "aωb", "", ""},
  5850. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5851. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5852. {"file3", "", "", "application/octet-stream"},
  5853. {"file4", "", "", " application/json tmp-string "}};
  5854. auto res = cli_.Post("/multipart", items);
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. }
  5858. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5859. UploadFormDataItems items = {
  5860. {"text", "default text", "", ""},
  5861. {"multi_text1", "aaaaa", "", ""},
  5862. {"multi_text1", "bbbbb", "", ""},
  5863. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5864. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5865. "application/json"},
  5866. };
  5867. auto res = cli_.Post("/multipart/multi_file_values", items);
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::OK_200, res->status);
  5870. }
  5871. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5872. auto res = cli_.Get("/hi");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::OK_200, res->status);
  5875. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5876. EXPECT_EQ("Hello World!", res->body);
  5877. }
  5878. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5879. Request req;
  5880. req.method = "POST";
  5881. req.path = "/chunked";
  5882. std::string host_and_port;
  5883. host_and_port += HOST;
  5884. host_and_port += ":";
  5885. host_and_port += std::to_string(PORT);
  5886. req.headers.emplace("Host", host_and_port.c_str());
  5887. req.headers.emplace("Accept", "*/*");
  5888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5889. req.headers.emplace("Content-Type", "text/plain");
  5890. req.headers.emplace("Content-Length", "0");
  5891. req.headers.emplace(
  5892. "Transfer-Encoding",
  5893. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5894. // Client does not chunk, so make a chunked body manually.
  5895. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5896. auto res = std::make_shared<Response>();
  5897. auto error = Error::Success;
  5898. auto ret = cli_.send(req, *res, error);
  5899. ASSERT_TRUE(ret);
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. }
  5902. template <typename ClientT>
  5903. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5904. int expected_status) {
  5905. Request req;
  5906. req.method = "POST";
  5907. req.path = "/chunked";
  5908. std::string host_and_port;
  5909. host_and_port += HOST;
  5910. host_and_port += ":";
  5911. host_and_port += std::to_string(PORT);
  5912. req.headers.emplace("Host", host_and_port.c_str());
  5913. req.headers.emplace("Content-Length", "0");
  5914. req.headers.emplace("Transfer-Encoding", "chunked");
  5915. req.body = body;
  5916. auto res = std::make_shared<Response>();
  5917. auto error = Error::Success;
  5918. ASSERT_TRUE(cli.send(req, *res, error));
  5919. EXPECT_EQ(expected_status, res->status);
  5920. }
  5921. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5922. // rather than treat them as valid lengths.
  5923. template <typename ClientT>
  5924. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5925. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5926. }
  5927. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5928. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5929. }
  5930. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5931. expect_chunked_body_rejected(
  5932. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5933. }
  5934. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5935. // chunk-size line carries no CR, LF or other control character ahead of its
  5936. // terminator. Such a line must be refused rather than read as extension text.
  5937. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5938. expect_chunked_body_rejected(
  5939. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5940. }
  5941. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5942. expect_chunked_body_rejected(
  5943. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5944. }
  5945. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5946. expect_chunked_body_rejected(
  5947. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5948. }
  5949. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5950. // The literal stays split: a hex escape consumes every hex digit that
  5951. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5952. expect_chunked_body_rejected(
  5953. cli_, "4;a\x01"
  5954. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5955. }
  5956. TEST_F(ServerTest, AcceptsChunkExtension) {
  5957. expect_chunked_body_status(cli_,
  5958. "4;name=value\r\ndech\r\n"
  5959. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5960. "0;last\r\n\r\n",
  5961. StatusCode::OK_200);
  5962. }
  5963. TEST_F(ServerTest, GetStreamed2) {
  5964. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5967. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5968. EXPECT_EQ(true, res->has_header("Content-Range"));
  5969. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5970. EXPECT_EQ(std::string("ab"), res->body);
  5971. }
  5972. TEST_F(ServerTest, GetStreamed) {
  5973. auto res = cli_.Get("/streamed");
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::OK_200, res->status);
  5976. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5977. EXPECT_EQ(std::string("aaabbb"), res->body);
  5978. }
  5979. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5980. auto res = cli_.Get("/streamed-without-length",
  5981. Headers{make_range_header({{0, -1}})});
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. EXPECT_EQ(false, res->has_header("Content-Length"));
  5985. EXPECT_EQ(false, res->has_header("Content-Range"));
  5986. EXPECT_EQ(std::string("abcdefg"), res->body);
  5987. }
  5988. TEST_F(ServerTest, GetStreamedWithRange1) {
  5989. auto res =
  5990. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5994. EXPECT_EQ(true, res->has_header("Content-Range"));
  5995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5996. EXPECT_EQ(std::string("def"), res->body);
  5997. }
  5998. TEST_F(ServerTest, GetStreamedWithRange2) {
  5999. auto res =
  6000. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6003. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6006. EXPECT_EQ(std::string("bcdefg"), res->body);
  6007. }
  6008. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6009. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6012. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6013. EXPECT_EQ(true, res->has_header("Content-Range"));
  6014. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6015. EXPECT_EQ(std::string("efg"), res->body);
  6016. }
  6017. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6018. auto res =
  6019. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6022. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6023. EXPECT_EQ(false, res->has_header("Content-Range"));
  6024. EXPECT_EQ(0U, res->body.size());
  6025. }
  6026. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6027. // Only a 206 is served as a partial representation. Under any other status
  6028. // `apply_ranges()` reported the full content length, so the body must match
  6029. // that header, and the content provider must never be asked for an offset
  6030. // outside the representation.
  6031. auto check = [&](int status, const char *range) {
  6032. auto path =
  6033. std::string("/streamed-with-range?status=") + std::to_string(status);
  6034. auto ctx = path + " Range: " + range;
  6035. auto res = cli_.Get(path, Headers{{"Range", range}});
  6036. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6037. EXPECT_EQ(status, res->status) << ctx;
  6038. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6040. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6041. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6042. };
  6043. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6044. check(403, "bytes=3-5");
  6045. // The offset is far past the representation.
  6046. check(403, "bytes=100000-100200");
  6047. // `first_pos` is still -1 here, and the bounds asserts in
  6048. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6049. check(403, "bytes=-3");
  6050. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6051. // multipart branch would have written one that is empty.
  6052. check(403, "bytes=1-2, 4-5");
  6053. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6054. // covers the whole representation.
  6055. check(200, "bytes=3-5");
  6056. check(200, "bytes=1-2, 4-5");
  6057. }
  6058. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6059. auto res =
  6060. cli_.Get("/streamed-with-range",
  6061. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6062. "92233720368547758079223372036854775807"}});
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6065. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6066. EXPECT_EQ(false, res->has_header("Content-Range"));
  6067. EXPECT_EQ(0U, res->body.size());
  6068. }
  6069. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6070. auto res = cli_.Get(
  6071. "/with-range",
  6072. Headers{{"Range",
  6073. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6074. {"Accept-Encoding", ""}});
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6077. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6078. EXPECT_EQ(true, res->has_header("Content-Range"));
  6079. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6080. EXPECT_EQ(std::string("abcdefg"), res->body);
  6081. }
  6082. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6083. auto res = cli_.Get("/with-range", Headers{
  6084. {"Range", "bytes=0-"},
  6085. {"Accept-Encoding", ""},
  6086. });
  6087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6089. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6090. EXPECT_EQ(true, res->has_header("Content-Range"));
  6091. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6092. EXPECT_EQ(std::string("abcdefg"), res->body);
  6093. }
  6094. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6095. auto res = cli_.Get("/streamed-with-range",
  6096. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6099. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6100. EXPECT_EQ(false, res->has_header("Content-Range"));
  6101. EXPECT_EQ(267U, res->body.size());
  6102. // Check that both range contents are present
  6103. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6104. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6105. // Check that Content-Range headers are present for both ranges
  6106. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6107. std::string::npos);
  6108. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6109. std::string::npos);
  6110. }
  6111. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6112. Ranges ranges;
  6113. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6114. ranges.emplace_back(0, -1);
  6115. }
  6116. auto res = cli_.Get("/streamed-with-range?error",
  6117. Headers{{make_range_header(ranges)}});
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6120. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6121. EXPECT_EQ(false, res->has_header("Content-Range"));
  6122. EXPECT_EQ(0U, res->body.size());
  6123. }
  6124. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6125. auto res = cli_.Get("/streamed-with-range",
  6126. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6129. EXPECT_EQ(5U, res->body.size());
  6130. // Check that overlapping ranges are coalesced into a single range
  6131. EXPECT_EQ("bcdef", res->body);
  6132. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6133. // Should be single range, not multipart
  6134. EXPECT_TRUE(res->has_header("Content-Range"));
  6135. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6136. }
  6137. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6138. auto res = cli_.Get("/streamed-with-range",
  6139. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6142. EXPECT_EQ(268U, res->body.size());
  6143. // Check that both range contents are present
  6144. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6145. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6146. // Check that Content-Range headers are present for both ranges
  6147. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6148. std::string::npos);
  6149. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6150. std::string::npos);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6153. auto res = cli_.Get("/streamed-with-range",
  6154. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6157. EXPECT_EQ(269U, res->body.size());
  6158. // Check that both duplicate range contents are present
  6159. size_t first_abc = res->body.find("abc\r\n");
  6160. EXPECT_TRUE(first_abc != std::string::npos);
  6161. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6162. EXPECT_TRUE(second_abc != std::string::npos);
  6163. // Check that Content-Range headers are present for both ranges
  6164. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6165. EXPECT_TRUE(first_range != std::string::npos);
  6166. size_t second_range =
  6167. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6168. EXPECT_TRUE(second_range != std::string::npos);
  6169. }
  6170. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6171. auto res =
  6172. cli_.Get("/streamed-with-range?error",
  6173. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6176. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6177. EXPECT_EQ(false, res->has_header("Content-Range"));
  6178. EXPECT_EQ(0U, res->body.size());
  6179. }
  6180. TEST_F(ServerTest, GetStreamedEndless) {
  6181. uint64_t offset = 0;
  6182. auto res = cli_.Get("/streamed-cancel",
  6183. [&](const char * /*data*/, uint64_t data_length) {
  6184. if (offset < 100) {
  6185. offset += data_length;
  6186. return true;
  6187. }
  6188. return false;
  6189. });
  6190. ASSERT_TRUE(!res);
  6191. EXPECT_EQ(Error::Canceled, res.error());
  6192. }
  6193. TEST_F(ServerTest, ClientStop) {
  6194. std::atomic_size_t count{4};
  6195. std::vector<std::thread> threads;
  6196. for (auto i = count.load(); i != 0; --i) {
  6197. threads.emplace_back([&]() {
  6198. auto res = cli_.Get("/streamed-cancel",
  6199. [&](const char *, uint64_t) { return true; });
  6200. --count;
  6201. ASSERT_TRUE(!res);
  6202. EXPECT_TRUE(res.error() == Error::Canceled ||
  6203. res.error() == Error::Read || res.error() == Error::Write);
  6204. });
  6205. }
  6206. std::this_thread::sleep_for(std::chrono::seconds(2));
  6207. while (count != 0) {
  6208. cli_.stop();
  6209. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6210. }
  6211. for (auto &t : threads) {
  6212. t.join();
  6213. }
  6214. }
  6215. TEST_F(ServerTest, GetWithRange1) {
  6216. auto res = cli_.Get("/with-range", Headers{
  6217. make_range_header({{3, 5}}),
  6218. {"Accept-Encoding", ""},
  6219. });
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("def"), res->body);
  6226. }
  6227. TEST_F(ServerTest, GetWithRange2) {
  6228. auto res = cli_.Get("/with-range", Headers{
  6229. make_range_header({{1, -1}}),
  6230. {"Accept-Encoding", ""},
  6231. });
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6235. EXPECT_EQ(true, res->has_header("Content-Range"));
  6236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6237. EXPECT_EQ(std::string("bcdefg"), res->body);
  6238. }
  6239. TEST_F(ServerTest, GetWithRange3) {
  6240. auto res = cli_.Get("/with-range", Headers{
  6241. make_range_header({{0, 0}}),
  6242. {"Accept-Encoding", ""},
  6243. });
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6246. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6247. EXPECT_EQ(true, res->has_header("Content-Range"));
  6248. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6249. EXPECT_EQ(std::string("a"), res->body);
  6250. }
  6251. TEST_F(ServerTest, GetWithRange4) {
  6252. auto res = cli_.Get("/with-range", Headers{
  6253. make_range_header({{-1, 2}}),
  6254. {"Accept-Encoding", ""},
  6255. });
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6258. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6259. EXPECT_EQ(true, res->has_header("Content-Range"));
  6260. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6261. EXPECT_EQ(std::string("fg"), res->body);
  6262. }
  6263. TEST_F(ServerTest, GetWithRange5) {
  6264. auto res = cli_.Get("/with-range", Headers{
  6265. make_range_header({{0, 5}}),
  6266. {"Accept-Encoding", ""},
  6267. });
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6270. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ(true, res->has_header("Content-Range"));
  6272. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6273. EXPECT_EQ(std::string("abcdef"), res->body);
  6274. }
  6275. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6276. auto res =
  6277. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6280. }
  6281. TEST_F(ServerTest, GetWithRangeMultipart) {
  6282. auto res =
  6283. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6286. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6287. EXPECT_EQ(false, res->has_header("Content-Range"));
  6288. EXPECT_EQ(267U, res->body.size());
  6289. }
  6290. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6291. auto res = cli_.Get("/with-range",
  6292. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6295. }
  6296. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6297. auto res = cli_.Get("/with-range-customized-response",
  6298. Headers{{make_range_header({{1, 2}})}});
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6301. EXPECT_EQ(true, res->has_header("Content-Length"));
  6302. EXPECT_EQ(false, res->has_header("Content-Range"));
  6303. EXPECT_EQ(JSON_DATA, res->body);
  6304. }
  6305. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6306. auto res = cli_.Get("/with-range-customized-response",
  6307. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6310. EXPECT_EQ(true, res->has_header("Content-Length"));
  6311. EXPECT_EQ(false, res->has_header("Content-Range"));
  6312. EXPECT_EQ(JSON_DATA, res->body);
  6313. }
  6314. TEST_F(ServerTest, Issue1772) {
  6315. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6318. }
  6319. TEST_F(ServerTest, Issue609) {
  6320. auto res = cli_.Delete("/issue609");
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. EXPECT_EQ(std::string("ok"), res->body);
  6324. }
  6325. TEST_F(ServerTest, GetStreamedChunked) {
  6326. auto res = cli_.Get("/streamed-chunked");
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ(std::string("123456789"), res->body);
  6330. }
  6331. TEST_F(ServerTest, GetStreamedChunked2) {
  6332. auto res = cli_.Get("/streamed-chunked2");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. EXPECT_EQ(StatusCode::OK_200, res->status);
  6335. EXPECT_EQ(std::string("123456789"), res->body);
  6336. }
  6337. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6338. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ(std::string("123456789"), res->body);
  6342. EXPECT_TRUE(res->has_header("Trailer"));
  6343. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6344. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6345. // Trailers are now stored separately from headers (security fix)
  6346. EXPECT_EQ(2U, res->trailers.size());
  6347. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6348. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6349. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6350. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6351. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6352. // Verify trailers are NOT in headers (security verification)
  6353. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6354. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6355. }
  6356. TEST_F(ServerTest, LargeChunkedPost) {
  6357. Request req;
  6358. req.method = "POST";
  6359. req.path = "/large-chunked";
  6360. std::string host_and_port;
  6361. host_and_port += HOST;
  6362. host_and_port += ":";
  6363. host_and_port += std::to_string(PORT);
  6364. req.headers.emplace("Host", host_and_port.c_str());
  6365. req.headers.emplace("Accept", "*/*");
  6366. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6367. req.headers.emplace("Content-Type", "text/plain");
  6368. req.headers.emplace("Content-Length", "0");
  6369. req.headers.emplace("Transfer-Encoding", "chunked");
  6370. std::string long_string(30 * 1024u, 'a');
  6371. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6372. // Attempt to make a large enough post to exceed OS buffers, to test that
  6373. // the server handles short reads if the full chunk data isn't available.
  6374. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6382. auto res = cli_.Get("/remote_addr");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6386. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6387. }
  6388. TEST_F(ServerTest, GetMethodLocalAddr) {
  6389. auto res = cli_.Get("/local_addr");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6393. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6394. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6395. }
  6396. TEST_F(ServerTest, HTTPResponseSplitting) {
  6397. auto res = cli_.Get("/http_response_splitting");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. }
  6401. TEST_F(ServerTest, SlowRequest) {
  6402. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6403. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6404. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6405. }
  6406. #if 0
  6407. TEST_F(ServerTest, SlowPost) {
  6408. char buffer[64 * 1024];
  6409. memset(buffer, 0x42, sizeof(buffer));
  6410. auto res = cli_.Post(
  6411. "/slowpost", 64 * 1024 * 1024,
  6412. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6413. auto ret = sink.write(buffer, sizeof(buffer));
  6414. EXPECT_TRUE(ret);
  6415. return true;
  6416. },
  6417. "text/plain");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. }
  6421. TEST_F(ServerTest, SlowPostFail) {
  6422. char buffer[64 * 1024];
  6423. memset(buffer, 0x42, sizeof(buffer));
  6424. cli_.set_write_timeout(std::chrono::seconds(0));
  6425. auto res = cli_.Post(
  6426. "/slowpost", 64 * 1024 * 1024,
  6427. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6428. sink.write(buffer, sizeof(buffer));
  6429. return true;
  6430. },
  6431. "text/plain");
  6432. ASSERT_TRUE(!res);
  6433. EXPECT_EQ(Error::Write, res.error());
  6434. }
  6435. #endif
  6436. TEST_F(ServerTest, Put) {
  6437. auto res = cli_.Put("/put", "PUT", "text/plain");
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::OK_200, res->status);
  6440. EXPECT_EQ("PUT", res->body);
  6441. }
  6442. TEST_F(ServerTest, PutWithContentProvider) {
  6443. auto res = cli_.Put(
  6444. "/put", 3,
  6445. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6446. sink.os << "PUT";
  6447. return true;
  6448. },
  6449. "text/plain");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. EXPECT_EQ("PUT", res->body);
  6453. }
  6454. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6455. auto res = cli_.Post(
  6456. "/post", 42,
  6457. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6458. return false;
  6459. },
  6460. "text/plain");
  6461. ASSERT_TRUE(!res);
  6462. EXPECT_EQ(Error::Canceled, res.error());
  6463. }
  6464. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6465. auto res = cli_.Put(
  6466. "/put",
  6467. [](size_t /*offset*/, DataSink &sink) {
  6468. sink.os << "PUT";
  6469. sink.done();
  6470. return true;
  6471. },
  6472. "text/plain");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::OK_200, res->status);
  6475. EXPECT_EQ("PUT", res->body);
  6476. }
  6477. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6478. auto res = cli_.Post(
  6479. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6480. "text/plain");
  6481. ASSERT_TRUE(!res);
  6482. EXPECT_EQ(Error::Canceled, res.error());
  6483. }
  6484. TEST_F(ServerTest, PostLoopBack) {
  6485. std::string body;
  6486. auto res = cli_.Post(
  6487. "/post-loopback", 9,
  6488. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6489. EXPECT_EQ(9u, length);
  6490. sink.write("123", 3);
  6491. sink.write("456", 3);
  6492. sink.write("789", 3);
  6493. return true;
  6494. },
  6495. "text/plain",
  6496. [&body](const char *data, size_t data_length) {
  6497. body.append(data, data_length);
  6498. return true;
  6499. });
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::OK_200, res->status);
  6502. EXPECT_EQ("123456789", body);
  6503. }
  6504. TEST_F(ServerTest, PutLoopBack) {
  6505. std::string body;
  6506. auto res = cli_.Put(
  6507. "/put-loopback", 9,
  6508. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6509. EXPECT_EQ(9u, length);
  6510. sink.write("123", 3);
  6511. sink.write("456", 3);
  6512. sink.write("789", 3);
  6513. return true;
  6514. },
  6515. "text/plain",
  6516. [&body](const char *data, size_t data_length) {
  6517. body.append(data, data_length);
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("123456789", body);
  6523. }
  6524. TEST_F(ServerTest, PatchLoopBack) {
  6525. std::string body;
  6526. auto res = cli_.Patch(
  6527. "/patch-loopback", 9,
  6528. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6529. EXPECT_EQ(9u, length);
  6530. sink.write("123", 3);
  6531. sink.write("456", 3);
  6532. sink.write("789", 3);
  6533. return true;
  6534. },
  6535. "text/plain",
  6536. [&body](const char *data, size_t data_length) {
  6537. body.append(data, data_length);
  6538. return true;
  6539. });
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. EXPECT_EQ("123456789", body);
  6543. }
  6544. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6545. std::string body;
  6546. auto res = cli_.Post(
  6547. "/post-loopback",
  6548. [](size_t /*offset*/, DataSink &sink) {
  6549. sink.write("123", 3);
  6550. sink.write("456", 3);
  6551. sink.write("789", 3);
  6552. sink.done();
  6553. return true;
  6554. },
  6555. "text/plain",
  6556. [&body](const char *data, size_t data_length) {
  6557. body.append(data, data_length);
  6558. return true;
  6559. });
  6560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6561. EXPECT_EQ(StatusCode::OK_200, res->status);
  6562. EXPECT_EQ("123456789", body);
  6563. }
  6564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6565. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6566. cli_.set_compress(true);
  6567. auto res = cli_.Put(
  6568. "/put", 3,
  6569. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6570. sink.os << "PUT";
  6571. return true;
  6572. },
  6573. "text/plain");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. EXPECT_EQ("PUT", res->body);
  6577. }
  6578. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6579. cli_.set_compress(true);
  6580. auto res = cli_.Post(
  6581. "/post", 42,
  6582. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6583. return false;
  6584. },
  6585. "text/plain");
  6586. ASSERT_TRUE(!res);
  6587. EXPECT_EQ(Error::Canceled, res.error());
  6588. }
  6589. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6590. cli_.set_compress(true);
  6591. auto res = cli_.Put(
  6592. "/put",
  6593. [](size_t /*offset*/, DataSink &sink) {
  6594. sink.os << "PUT";
  6595. sink.done();
  6596. return true;
  6597. },
  6598. "text/plain");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::OK_200, res->status);
  6601. EXPECT_EQ("PUT", res->body);
  6602. }
  6603. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6604. cli_.set_compress(true);
  6605. auto res = cli_.Post(
  6606. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6607. "text/plain");
  6608. ASSERT_TRUE(!res);
  6609. EXPECT_EQ(Error::Canceled, res.error());
  6610. }
  6611. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6612. cli_.set_compress(true);
  6613. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ(LARGE_DATA, res->body);
  6617. }
  6618. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6619. #ifdef CPPHTTPLIB_SSL_ENABLED
  6620. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6621. Client cli(s.c_str());
  6622. cli.enable_server_certificate_verification(false);
  6623. #else
  6624. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6625. Client cli(s.c_str());
  6626. #endif
  6627. cli.set_compress(true);
  6628. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. EXPECT_EQ(LARGE_DATA, res->body);
  6632. // The compressed size should be less than a 10th of the original. May vary
  6633. // depending on the zlib library.
  6634. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6635. static_cast<uint64_t>(10 * 1024 * 1024));
  6636. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6637. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6638. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6639. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6640. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6641. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6642. #endif
  6643. }
  6644. TEST_F(ServerTest, PutContentWithDeflate) {
  6645. cli_.set_compress(false);
  6646. Headers headers;
  6647. headers.emplace("Content-Encoding", "deflate");
  6648. // PUT in deflate format:
  6649. auto res = cli_.Put("/put", headers,
  6650. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::OK_200, res->status);
  6653. EXPECT_EQ("PUT", res->body);
  6654. }
  6655. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6656. Headers headers;
  6657. headers.emplace("Accept-Encoding", "gzip, deflate");
  6658. auto res = cli_.Get("/streamed-chunked", headers);
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ(std::string("123456789"), res->body);
  6662. }
  6663. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6664. Headers headers;
  6665. headers.emplace("Accept-Encoding", "gzip, deflate");
  6666. auto res = cli_.Get("/streamed-chunked2", headers);
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::OK_200, res->status);
  6669. EXPECT_EQ(std::string("123456789"), res->body);
  6670. }
  6671. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6672. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST(GzipDecompressor, ChunkedDecompression) {
  6677. std::string data;
  6678. for (size_t i = 0; i < 32 * 1024; ++i) {
  6679. data.push_back(static_cast<char>('a' + i % 26));
  6680. }
  6681. std::string compressed_data;
  6682. {
  6683. httplib::detail::gzip_compressor compressor;
  6684. bool result = compressor.compress(
  6685. data.data(), data.size(),
  6686. /*last=*/true,
  6687. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6688. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6689. compressed_data_size);
  6690. return true;
  6691. });
  6692. ASSERT_TRUE(result);
  6693. }
  6694. std::string decompressed_data;
  6695. {
  6696. httplib::detail::gzip_decompressor decompressor;
  6697. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6698. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6699. size_t chunk_size = 130;
  6700. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6701. chunk_begin += chunk_size) {
  6702. size_t current_chunk_size =
  6703. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6704. bool result = decompressor.decompress(
  6705. compressed_data.data() + chunk_begin, current_chunk_size,
  6706. [&](const char *decompressed_data_chunk,
  6707. size_t decompressed_data_chunk_size) {
  6708. decompressed_data.insert(decompressed_data.size(),
  6709. decompressed_data_chunk,
  6710. decompressed_data_chunk_size);
  6711. return true;
  6712. });
  6713. ASSERT_TRUE(result);
  6714. }
  6715. }
  6716. ASSERT_EQ(data, decompressed_data);
  6717. }
  6718. TEST(GzipDecompressor, DeflateDecompression) {
  6719. std::string original_text = "Raw deflate without gzip";
  6720. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6721. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6722. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6723. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6724. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6725. std::string decompressed_data;
  6726. {
  6727. httplib::detail::gzip_decompressor decompressor;
  6728. bool result = decompressor.decompress(
  6729. compressed_data.data(), compressed_data.size(),
  6730. [&](const char *decompressed_data_chunk,
  6731. size_t decompressed_data_chunk_size) {
  6732. decompressed_data.insert(decompressed_data.size(),
  6733. decompressed_data_chunk,
  6734. decompressed_data_chunk_size);
  6735. return true;
  6736. });
  6737. ASSERT_TRUE(result);
  6738. }
  6739. ASSERT_EQ(original_text, decompressed_data);
  6740. }
  6741. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6742. std::string original_text = "Raw deflate without gzip";
  6743. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6744. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6745. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6746. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6747. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6748. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6749. std::string decompressed_data;
  6750. {
  6751. httplib::detail::gzip_decompressor decompressor;
  6752. bool result = decompressor.decompress(
  6753. compressed_data.data(), compressed_data.size(),
  6754. [&](const char *decompressed_data_chunk,
  6755. size_t decompressed_data_chunk_size) {
  6756. decompressed_data.insert(decompressed_data.size(),
  6757. decompressed_data_chunk,
  6758. decompressed_data_chunk_size);
  6759. return true;
  6760. });
  6761. ASSERT_TRUE(result);
  6762. }
  6763. ASSERT_EQ(original_text, decompressed_data);
  6764. }
  6765. #endif
  6766. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6767. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "br");
  6770. auto res = cli_.Get("/streamed-chunked", headers);
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ(std::string("123456789"), res->body);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6776. Headers headers;
  6777. headers.emplace("Accept-Encoding", "br");
  6778. auto res = cli_.Get("/streamed-chunked2", headers);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ(std::string("123456789"), res->body);
  6782. }
  6783. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6784. cli_.set_compress(true);
  6785. auto res = cli_.Put(
  6786. "/put", 3,
  6787. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6788. sink.os << "PUT";
  6789. return true;
  6790. },
  6791. "text/plain");
  6792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6793. EXPECT_EQ(StatusCode::OK_200, res->status);
  6794. EXPECT_EQ("PUT", res->body);
  6795. }
  6796. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6797. cli_.set_compress(true);
  6798. auto res = cli_.Put(
  6799. "/put",
  6800. [](size_t /*offset*/, DataSink &sink) {
  6801. sink.os << "PUT";
  6802. sink.done();
  6803. return true;
  6804. },
  6805. "text/plain");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("PUT", res->body);
  6809. }
  6810. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6811. cli_.set_compress(true);
  6812. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ(LARGE_DATA, res->body);
  6816. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6817. }
  6818. #endif
  6819. TEST_F(ServerTest, Patch) {
  6820. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. EXPECT_EQ("PATCH", res->body);
  6824. }
  6825. TEST_F(ServerTest, Delete) {
  6826. auto res = cli_.Delete("/delete");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("DELETE", res->body);
  6830. }
  6831. TEST_F(ServerTest, DeleteContentReceiver) {
  6832. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::OK_200, res->status);
  6835. EXPECT_EQ("content", res->body);
  6836. }
  6837. TEST_F(ServerTest, Options) {
  6838. auto res = cli_.Options("*");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6842. EXPECT_TRUE(res->body.empty());
  6843. }
  6844. TEST_F(ServerTest, URL) {
  6845. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. TEST_F(ServerTest, ArrayParam) {
  6850. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ(StatusCode::OK_200, res->status);
  6853. }
  6854. TEST_F(ServerTest, ArrayParamValues) {
  6855. auto res =
  6856. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::OK_200, res->status);
  6859. }
  6860. TEST_F(ServerTest, NoMultipleHeaders) {
  6861. Headers headers = {{"Content-Length", "5"}};
  6862. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6863. "text/plain");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. }
  6867. TEST_F(ServerTest, PostContentReceiver) {
  6868. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. ASSERT_EQ(StatusCode::OK_200, res->status);
  6871. ASSERT_EQ("content", res->body);
  6872. }
  6873. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6874. UploadFormDataItems items = {
  6875. {"text1", "text default", "", ""},
  6876. {"text2", "aωb", "", ""},
  6877. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6878. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6879. {"file3", "", "", "application/octet-stream"},
  6880. };
  6881. auto res = cli_.Post("/content_receiver", items);
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. }
  6885. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6886. UploadFormDataItems items = {
  6887. {"text1", "text default", "", ""},
  6888. {"text2", "aωb", "", ""},
  6889. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6890. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6891. {"file3", "", "", "application/octet-stream"},
  6892. };
  6893. auto boundary = std::string("+++++");
  6894. std::string body;
  6895. for (const auto &item : items) {
  6896. body += "--" + boundary + "\r\n";
  6897. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6898. if (!item.filename.empty()) {
  6899. body += "; filename=\"" + item.filename + "\"";
  6900. }
  6901. body += "\r\n";
  6902. if (!item.content_type.empty()) {
  6903. body += "Content-Type: " + item.content_type + "\r\n";
  6904. }
  6905. body += "\r\n";
  6906. body += item.content + "\r\n";
  6907. }
  6908. body += "--" + boundary + "--\r\n";
  6909. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6910. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. }
  6914. TEST(MultipartFormDataTest, FieldEscaping) {
  6915. Server svr;
  6916. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6917. const ContentReader &content_reader) {
  6918. ASSERT_TRUE(req.is_multipart_form_data());
  6919. std::vector<FormData> received;
  6920. content_reader(
  6921. [&](const FormData &file) {
  6922. received.push_back(file);
  6923. return true;
  6924. },
  6925. [&](const char *data, size_t data_length) {
  6926. received.back().content.append(data, data_length);
  6927. return true;
  6928. });
  6929. // '"', CR and LF in names and filenames are escaped following the
  6930. // WHATWG HTML standard, so each part still parses as a single part
  6931. // with no injected headers. Content types get CR/LF escaped too,
  6932. // while '"' (legal there, e.g. quoted charset) is preserved.
  6933. ASSERT_EQ(4U, received.size());
  6934. EXPECT_EQ("na%22me", received[0].name);
  6935. EXPECT_EQ("quoted name", received[0].content);
  6936. EXPECT_EQ("file", received[1].name);
  6937. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6938. received[1].filename);
  6939. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6940. EXPECT_EQ("injected", received[1].content);
  6941. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6942. EXPECT_EQ("my%22file.txt", received[2].filename);
  6943. EXPECT_EQ("cr lf name", received[2].content);
  6944. EXPECT_EQ("typed", received[3].name);
  6945. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6946. received[3].content_type);
  6947. EXPECT_EQ("typed content", received[3].content);
  6948. });
  6949. auto port = svr.bind_to_any_port("localhost");
  6950. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. Client cli("localhost", port);
  6958. UploadFormDataItems items = {
  6959. {"na\"me", "quoted name", "", ""},
  6960. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6961. "application/octet-stream"},
  6962. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6963. {"typed", "typed content", "",
  6964. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6965. };
  6966. auto res = cli.Post("/post", items);
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6971. const UploadFormDataItems items = {
  6972. {"name1", "Content 1", "", ""},
  6973. {"name2", "Content 2", "file2.txt", "text/plain"},
  6974. };
  6975. Server svr;
  6976. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6977. const ContentReader &content_reader) {
  6978. ASSERT_TRUE(req.is_multipart_form_data());
  6979. std::vector<FormData> received;
  6980. content_reader(
  6981. [&](const FormData &file) {
  6982. received.push_back(file);
  6983. return true;
  6984. },
  6985. [&](const char *data, size_t data_length) {
  6986. received.back().content.append(data, data_length);
  6987. return true;
  6988. });
  6989. ASSERT_EQ(2U, received.size());
  6990. EXPECT_EQ("name1", received[0].name);
  6991. EXPECT_EQ("Content 1", received[0].content);
  6992. EXPECT_EQ("name2", received[1].name);
  6993. EXPECT_EQ("Content 2", received[1].content);
  6994. EXPECT_EQ("file2.txt", received[1].filename);
  6995. EXPECT_EQ("text/plain", received[1].content_type);
  6996. });
  6997. auto port = svr.bind_to_any_port("localhost");
  6998. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6999. auto se = detail::scope_exit([&] {
  7000. svr.stop();
  7001. t.join();
  7002. ASSERT_FALSE(svr.is_running());
  7003. });
  7004. svr.wait_until_ready();
  7005. Client cli("localhost", port);
  7006. // Whole-body serialization with a generated boundary
  7007. {
  7008. MultipartFormDataWriter writer;
  7009. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7010. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7011. writer.content_type());
  7012. auto body = writer.serialize(items);
  7013. EXPECT_EQ(body.size(), writer.content_length(items));
  7014. auto res = cli.Post("/post", body, writer.content_type());
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. // Per-part framing with a custom boundary via a content provider
  7019. {
  7020. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7021. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7022. MultipartFormDataWriter writer("custom-boundary_123");
  7023. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7024. std::string body;
  7025. for (const auto &item : items) {
  7026. body += writer.item_begin(item);
  7027. body += item.content;
  7028. body += MultipartFormDataWriter::item_end();
  7029. }
  7030. body += writer.finish();
  7031. EXPECT_EQ(body.size(), writer.content_length(items));
  7032. auto res = cli.Post(
  7033. "/post", body.size(),
  7034. [&](size_t offset, size_t length, DataSink &sink) {
  7035. sink.write(body.data() + offset, length);
  7036. return true;
  7037. },
  7038. writer.content_type());
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. }
  7042. }
  7043. TEST_F(ServerTest, PostContentReceiverGzip) {
  7044. cli_.set_compress(true);
  7045. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. ASSERT_EQ(StatusCode::OK_200, res->status);
  7048. ASSERT_EQ("content", res->body);
  7049. }
  7050. TEST_F(ServerTest, PutContentReceiver) {
  7051. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("content", res->body);
  7055. }
  7056. TEST_F(ServerTest, PatchContentReceiver) {
  7057. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7059. ASSERT_EQ(StatusCode::OK_200, res->status);
  7060. ASSERT_EQ("content", res->body);
  7061. }
  7062. template <typename ClientType>
  7063. void TestWithHeadersAndContentReceiver(
  7064. ClientType &cli,
  7065. std::function<Result(ClientType &, const std::string &, const Headers &,
  7066. const std::string &, const std::string &,
  7067. ContentReceiver, DownloadProgress)>
  7068. request_func) {
  7069. Headers headers;
  7070. headers.emplace("X-Custom-Header", "test-value");
  7071. std::string received_body;
  7072. auto res = request_func(
  7073. cli, "/content_receiver", headers, "content", "application/json",
  7074. [&](const char *data, size_t data_length) {
  7075. received_body.append(data, data_length);
  7076. return true;
  7077. },
  7078. nullptr);
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("content", received_body);
  7082. }
  7083. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7084. #ifdef CPPHTTPLIB_SSL_ENABLED
  7085. using ClientT = SSLClient;
  7086. #else
  7087. using ClientT = Client;
  7088. #endif
  7089. TestWithHeadersAndContentReceiver<ClientT>(
  7090. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7091. const std::string &body, const std::string &content_type,
  7092. ContentReceiver receiver, DownloadProgress progress) {
  7093. return cli.Post(path, headers, body, content_type, receiver, progress);
  7094. });
  7095. }
  7096. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. using ClientT = SSLClient;
  7099. #else
  7100. using ClientT = Client;
  7101. #endif
  7102. TestWithHeadersAndContentReceiver<ClientT>(
  7103. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7104. const std::string &body, const std::string &content_type,
  7105. ContentReceiver receiver, DownloadProgress progress) {
  7106. return cli.Put(path, headers, body, content_type, receiver, progress);
  7107. });
  7108. }
  7109. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7110. #ifdef CPPHTTPLIB_SSL_ENABLED
  7111. using ClientT = SSLClient;
  7112. #else
  7113. using ClientT = Client;
  7114. #endif
  7115. TestWithHeadersAndContentReceiver<ClientT>(
  7116. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7117. const std::string &body, const std::string &content_type,
  7118. ContentReceiver receiver, DownloadProgress progress) {
  7119. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7120. });
  7121. }
  7122. template <typename ClientType>
  7123. void TestWithHeadersAndContentReceiverWithProgress(
  7124. ClientType &cli,
  7125. std::function<Result(ClientType &, const std::string &, const Headers &,
  7126. const std::string &, const std::string &,
  7127. ContentReceiver, DownloadProgress)>
  7128. request_func) {
  7129. Headers headers;
  7130. headers.emplace("X-Test-Header", "progress-test");
  7131. std::string received_body;
  7132. auto progress_called = false;
  7133. auto res = request_func(
  7134. cli, "/content_receiver", headers, "content", "text/plain",
  7135. [&](const char *data, size_t data_length) {
  7136. received_body.append(data, data_length);
  7137. return true;
  7138. },
  7139. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7140. progress_called = true;
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::OK_200, res->status);
  7145. EXPECT_EQ("content", received_body);
  7146. EXPECT_TRUE(progress_called);
  7147. }
  7148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7149. #ifdef CPPHTTPLIB_SSL_ENABLED
  7150. using ClientT = SSLClient;
  7151. #else
  7152. using ClientT = Client;
  7153. #endif
  7154. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7156. const std::string &body, const std::string &content_type,
  7157. ContentReceiver receiver, DownloadProgress progress) {
  7158. return cli.Post(path, headers, body, content_type, receiver, progress);
  7159. });
  7160. }
  7161. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7162. #ifdef CPPHTTPLIB_SSL_ENABLED
  7163. using ClientT = SSLClient;
  7164. #else
  7165. using ClientT = Client;
  7166. #endif
  7167. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7169. const std::string &body, const std::string &content_type,
  7170. ContentReceiver receiver, DownloadProgress progress) {
  7171. return cli.Put(path, headers, body, content_type, receiver, progress);
  7172. });
  7173. }
  7174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7175. #ifdef CPPHTTPLIB_SSL_ENABLED
  7176. using ClientT = SSLClient;
  7177. #else
  7178. using ClientT = Client;
  7179. #endif
  7180. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7182. const std::string &body, const std::string &content_type,
  7183. ContentReceiver receiver, DownloadProgress progress) {
  7184. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7185. });
  7186. }
  7187. template <typename ClientType>
  7188. void TestWithHeadersAndContentReceiverError(
  7189. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7190. const Headers &, const std::string &,
  7191. const std::string &, ContentReceiver)>
  7192. request_func) {
  7193. Headers headers;
  7194. headers.emplace("X-Error-Test", "true");
  7195. std::string received_body;
  7196. auto receiver_failed = false;
  7197. auto res =
  7198. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7199. [&](const char *data, size_t data_length) {
  7200. received_body.append(data, data_length);
  7201. receiver_failed = true;
  7202. return false;
  7203. });
  7204. ASSERT_FALSE(res);
  7205. EXPECT_TRUE(receiver_failed);
  7206. }
  7207. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7208. #ifdef CPPHTTPLIB_SSL_ENABLED
  7209. using ClientT = SSLClient;
  7210. #else
  7211. using ClientT = Client;
  7212. #endif
  7213. TestWithHeadersAndContentReceiverError<ClientT>(
  7214. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7215. const std::string &body, const std::string &content_type,
  7216. ContentReceiver receiver) {
  7217. return cli.Post(path, headers, body, content_type, receiver);
  7218. });
  7219. }
  7220. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7221. #ifdef CPPHTTPLIB_SSL_ENABLED
  7222. using ClientT = SSLClient;
  7223. #else
  7224. using ClientT = Client;
  7225. #endif
  7226. TestWithHeadersAndContentReceiverError<ClientT>(
  7227. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7228. const std::string &body, const std::string &content_type,
  7229. ContentReceiver receiver) {
  7230. return cli.Put(path, headers, body, content_type, receiver);
  7231. });
  7232. }
  7233. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7234. #ifdef CPPHTTPLIB_SSL_ENABLED
  7235. using ClientT = SSLClient;
  7236. #else
  7237. using ClientT = Client;
  7238. #endif
  7239. TestWithHeadersAndContentReceiverError<ClientT>(
  7240. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7241. const std::string &body, const std::string &content_type,
  7242. ContentReceiver receiver) {
  7243. return cli.Patch(path, headers, body, content_type, receiver);
  7244. });
  7245. }
  7246. TEST_F(ServerTest, PostQueryStringAndBody) {
  7247. auto res =
  7248. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. ASSERT_EQ(StatusCode::OK_200, res->status);
  7251. }
  7252. TEST_F(ServerTest, HTTP2Magic) {
  7253. Request req;
  7254. req.method = "PRI";
  7255. req.path = "*";
  7256. req.body = "SM";
  7257. auto res = std::make_shared<Response>();
  7258. auto error = Error::Success;
  7259. auto ret = cli_.send(req, *res, error);
  7260. ASSERT_TRUE(ret);
  7261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7262. }
  7263. TEST_F(ServerTest, KeepAlive) {
  7264. auto res = cli_.Get("/hi");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7268. EXPECT_EQ("Hello World!", res->body);
  7269. res = cli_.Get("/hi");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7273. EXPECT_EQ("Hello World!", res->body);
  7274. res = cli_.Get("/hi");
  7275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7278. EXPECT_EQ("Hello World!", res->body);
  7279. res = cli_.Get("/not-exist");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7282. res = cli_.Post("/empty", "", "text/plain");
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::OK_200, res->status);
  7285. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7286. EXPECT_EQ("empty", res->body);
  7287. EXPECT_EQ("close", res->get_header_value("Connection"));
  7288. res = cli_.Post(
  7289. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7290. "text/plain");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7294. EXPECT_EQ("empty", res->body);
  7295. cli_.set_keep_alive(false);
  7296. res = cli_.Get("/last-request");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. EXPECT_EQ("close", res->get_header_value("Connection"));
  7300. }
  7301. TEST_F(ServerTest, TooManyRedirect) {
  7302. cli_.set_follow_location(true);
  7303. auto res = cli_.Get("/redirect/0");
  7304. ASSERT_TRUE(!res);
  7305. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7306. }
  7307. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7308. Request req;
  7309. req.method = "FOOBAR";
  7310. req.path = "/hi";
  7311. cli_.set_keep_alive(true);
  7312. auto res = cli_.send(req);
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7315. EXPECT_EQ("close", res->get_header_value("Connection"));
  7316. EXPECT_FALSE(cli_.is_socket_open());
  7317. }
  7318. TEST_F(ServerTest, CustomRouteReadsBody) {
  7319. const std::string xml =
  7320. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7321. Request req;
  7322. req.method = "PROPFIND";
  7323. req.path = "/dav/dir";
  7324. req.set_header("Depth", "1");
  7325. req.body = xml;
  7326. auto res = cli_.send(req);
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7329. EXPECT_EQ(xml, res->body);
  7330. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7331. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7332. }
  7333. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7334. Request req;
  7335. req.method = "PROPFIND";
  7336. req.path = "/dav/42";
  7337. auto res = cli_.send(req);
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7340. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7341. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7342. }
  7343. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7344. Request req;
  7345. req.method = "PROPFIND";
  7346. req.path = "/dav-re/123";
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7350. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7351. }
  7352. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7353. Request req;
  7354. req.method = "MKCOL";
  7355. req.path = "/dav-mkcol";
  7356. auto res = cli_.send(req);
  7357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7358. EXPECT_EQ(StatusCode::Created_201, res->status);
  7359. }
  7360. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7361. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7362. Request req;
  7363. req.method = "REPORT";
  7364. req.path = "/dav-report";
  7365. req.body = xml;
  7366. auto res = cli_.send(req);
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7369. EXPECT_EQ(xml, res->body);
  7370. }
  7371. // A content reader route must fire even when the request carries no body,
  7372. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7373. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7374. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7375. Request req;
  7376. req.method = "REPORT";
  7377. req.path = "/dav-report";
  7378. auto res = cli_.send(req);
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7381. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7382. }
  7383. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7384. Request req;
  7385. req.method = "PROPFIND";
  7386. req.path = "/not-dav";
  7387. auto res = cli_.send(req);
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7390. }
  7391. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7392. Request req;
  7393. req.method = "UNLOCK";
  7394. req.path = "/dav/dir";
  7395. cli_.set_keep_alive(true);
  7396. auto res = cli_.send(req);
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. EXPECT_FALSE(cli_.is_socket_open());
  7401. }
  7402. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7403. // The mount point serves this path, but only for GET and HEAD.
  7404. auto get_res = cli_.Get("/dir/index.html");
  7405. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7406. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7407. Request req;
  7408. req.method = "PROPFIND";
  7409. req.path = "/dir/index.html";
  7410. auto res = cli_.send(req);
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7413. }
  7414. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7415. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7416. cli_.set_keep_alive(true);
  7417. for (auto i = 0; i < 2; i++) {
  7418. Request req;
  7419. req.method = "PROPFIND";
  7420. req.path = "/dav/dir";
  7421. req.body = xml;
  7422. auto res = cli_.send(req);
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7425. EXPECT_EQ(xml, res->body);
  7426. EXPECT_TRUE(cli_.is_socket_open());
  7427. }
  7428. // A built-in method must still be served on the same connection.
  7429. cli_.set_keep_alive(false);
  7430. auto res = cli_.Get("/hi");
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. EXPECT_EQ("close", res->get_header_value("Connection"));
  7434. }
  7435. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7436. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7437. Request req;
  7438. req.method = "PROPFIND";
  7439. req.path = "/dav/dir";
  7440. req.set_header("Expect", "100-continue");
  7441. req.body = xml;
  7442. auto res = cli_.send(req);
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7445. EXPECT_EQ(xml, res->body);
  7446. }
  7447. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7449. TEST_F(ServerTest, Gzip) {
  7450. Headers headers;
  7451. headers.emplace("Accept-Encoding", "gzip, deflate");
  7452. auto res = cli_.Get("/compress", headers);
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7456. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7457. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7458. "7890123456789012345678901234567890",
  7459. res->body);
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. }
  7462. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7463. Headers headers;
  7464. headers.emplace("Accept-Encoding", "gzip, deflate");
  7465. auto res = cli_.Get("/compress-with-charset", headers);
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7468. EXPECT_EQ("application/json; charset=utf-8",
  7469. res->get_header_value("Content-Type"));
  7470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7471. "7890123456789012345678901234567890",
  7472. res->body);
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7476. Headers headers;
  7477. headers.emplace("Accept-Encoding", "");
  7478. auto res = cli_.Get("/compress", headers);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7484. "7890123456789012345678901234567890",
  7485. res->body);
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. }
  7488. TEST_F(ServerTest, GzipWithContentReceiver) {
  7489. Headers headers;
  7490. headers.emplace("Accept-Encoding", "gzip, deflate");
  7491. std::string body;
  7492. auto res = cli_.Get("/compress", headers,
  7493. [&](const char *data, uint64_t data_length) {
  7494. EXPECT_EQ(100U, data_length);
  7495. body.append(data, data_length);
  7496. return true;
  7497. });
  7498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7499. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7501. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7503. "7890123456789012345678901234567890",
  7504. body);
  7505. EXPECT_EQ(StatusCode::OK_200, res->status);
  7506. }
  7507. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7508. Headers headers;
  7509. headers.emplace("Accept-Encoding", "gzip, deflate");
  7510. cli_.set_decompress(false);
  7511. auto res = cli_.Get("/compress", headers);
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7515. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7516. EXPECT_EQ(33U, res->body.size());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7520. Headers headers;
  7521. headers.emplace("Accept-Encoding", "");
  7522. std::string body;
  7523. auto res = cli_.Get("/compress", headers,
  7524. [&](const char *data, uint64_t data_length) {
  7525. EXPECT_EQ(100U, data_length);
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7531. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7532. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7534. "7890123456789012345678901234567890",
  7535. body);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. TEST_F(ServerTest, NoGzip) {
  7539. Headers headers;
  7540. headers.emplace("Accept-Encoding", "gzip, deflate");
  7541. auto res = cli_.Get("/nocompress", headers);
  7542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7543. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7544. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7545. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7546. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7547. "7890123456789012345678901234567890",
  7548. res->body);
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. }
  7551. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7552. Headers headers;
  7553. headers.emplace("Accept-Encoding", "gzip, deflate");
  7554. std::string body;
  7555. auto res = cli_.Get("/nocompress", headers,
  7556. [&](const char *data, uint64_t data_length) {
  7557. EXPECT_EQ(100U, data_length);
  7558. body.append(data, data_length);
  7559. return true;
  7560. });
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7563. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7564. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7565. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7566. "7890123456789012345678901234567890",
  7567. body);
  7568. EXPECT_EQ(StatusCode::OK_200, res->status);
  7569. }
  7570. TEST_F(ServerTest, MultipartFormDataGzip) {
  7571. UploadFormDataItems items = {
  7572. {"key1", "test", "", ""},
  7573. {"key2", "--abcdefg123", "", ""},
  7574. };
  7575. cli_.set_compress(true);
  7576. auto res = cli_.Post("/compress-multipart", items);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. #endif
  7581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7582. // Static file compression is opt-in, so these run their own server rather than
  7583. // flipping it on for the shared ServerTest fixture, which would silently
  7584. // rewrite what every other static file test is asserting.
  7585. class StaticFileCompressionTest : public ::testing::Test {
  7586. protected:
  7587. void TearDown() override {
  7588. if (t_.joinable()) {
  7589. svr_.stop();
  7590. t_.join();
  7591. }
  7592. }
  7593. int start(const std::function<void(Server &)> &configure = nullptr) {
  7594. // Serves the same tree as a directory of build-time compressed assets
  7595. // would be served: the mount point names the coding the files are already
  7596. // stored in. Registered before "/" so it is the one that matches.
  7597. svr_.set_mount_point("/pre-encoded", "./www",
  7598. {{"Content-Encoding", "gzip"}});
  7599. svr_.set_mount_point("/", "./www");
  7600. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7601. res.set_file_content("./www/dir/index.html", "text/html");
  7602. });
  7603. svr_.Get("/pre-encoded-file-content",
  7604. [](const Request & /*req*/, Response &res) {
  7605. res.set_header("Content-Encoding", "gzip");
  7606. res.set_file_content("./www/dir/index.html", "text/html");
  7607. });
  7608. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7609. res.set_content_provider(
  7610. 6, "text/plain",
  7611. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7612. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7613. return true;
  7614. });
  7615. });
  7616. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7617. res.set_content_provider(
  7618. 1000, "text/plain",
  7619. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7620. if (offset < 100) {
  7621. std::string data(100, 'A');
  7622. sink.write(data.data(), data.size());
  7623. return true;
  7624. }
  7625. std::this_thread::sleep_for(std::chrono::seconds(2));
  7626. std::string data(900, 'B');
  7627. sink.write(data.data(), data.size());
  7628. return true;
  7629. });
  7630. });
  7631. if (configure) { configure(svr_); }
  7632. auto port = svr_.bind_to_any_port(HOST);
  7633. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7634. svr_.wait_until_ready();
  7635. return port;
  7636. }
  7637. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7638. // Every file under ./www except 1MB.txt is smaller than the default
  7639. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7640. // it out of the way.
  7641. static void enable_without_floor(Server &svr) {
  7642. svr.set_static_file_compression(true);
  7643. svr.set_static_file_compression_min_length(0);
  7644. }
  7645. Server svr_;
  7646. std::thread t_;
  7647. };
  7648. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7649. auto port = start();
  7650. Client cli(HOST, port);
  7651. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7655. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7656. EXPECT_EQ(1048576U, res->body.size());
  7657. }
  7658. TEST_F(StaticFileCompressionTest, MountPoint) {
  7659. auto port = start(enable);
  7660. Client cli(HOST, port);
  7661. cli.set_decompress(false);
  7662. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::OK_200, res->status);
  7665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7666. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7667. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7668. // The response stays self-delimiting: a length, not a chunked body.
  7669. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7670. EXPECT_EQ(std::to_string(res->body.size()),
  7671. res->get_header_value("Content-Length"));
  7672. EXPECT_LT(res->body.size(), 1048576U);
  7673. EXPECT_FALSE(res->body.empty());
  7674. }
  7675. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7676. auto port = start(enable);
  7677. Client cli(HOST, port);
  7678. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7682. EXPECT_EQ(1048576U, res->body.size());
  7683. }
  7684. TEST_F(StaticFileCompressionTest, FileContent) {
  7685. auto port = start(enable_without_floor);
  7686. Client cli(HOST, port);
  7687. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7692. EXPECT_EQ(104U, res->body.size());
  7693. }
  7694. // A handler that serves an already-encoded file names the coding itself. The
  7695. // file-backed path decided its coding from Accept-Encoding and the content
  7696. // type alone, so it compressed the stored bytes a second time and appended a
  7697. // second Content-Encoding field line.
  7698. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7699. auto port = start(enable_without_floor);
  7700. Client cli(HOST, port);
  7701. cli.set_decompress(false);
  7702. auto res = cli.Get("/pre-encoded-file-content",
  7703. Headers{{"Accept-Encoding", "gzip"}});
  7704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7705. EXPECT_EQ(StatusCode::OK_200, res->status);
  7706. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7708. // Vary belongs to a coding the server chose, and it chose none here.
  7709. EXPECT_FALSE(res->has_header("Vary"));
  7710. // The file travels exactly as it is stored on disk.
  7711. EXPECT_EQ(104U, res->body.size());
  7712. }
  7713. // The 1MB file clears the default floor, so this one runs the configuration a
  7714. // deployment would actually have.
  7715. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7716. auto port = start(enable);
  7717. Client cli(HOST, port);
  7718. cli.set_decompress(false);
  7719. auto res =
  7720. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7724. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7725. EXPECT_FALSE(res->has_header("Vary"));
  7726. EXPECT_EQ(1048576U, res->body.size());
  7727. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7728. }
  7729. TEST_F(StaticFileCompressionTest, Head) {
  7730. auto port = start(enable);
  7731. Client cli(HOST, port);
  7732. cli.set_decompress(false);
  7733. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7734. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7735. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7739. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7740. // HEAD still reports the size a GET would return.
  7741. EXPECT_EQ(get->get_header_value("Content-Length"),
  7742. res->get_header_value("Content-Length"));
  7743. EXPECT_TRUE(res->body.empty());
  7744. }
  7745. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7746. auto port = start(enable);
  7747. Client cli(HOST, port);
  7748. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7749. {"Accept-Encoding", "gzip"}});
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7752. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7753. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7754. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7755. EXPECT_EQ("cd", res->body);
  7756. }
  7757. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7758. auto port = start(enable);
  7759. Client cli(HOST, port);
  7760. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7764. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7765. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7766. }
  7767. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7768. auto port = start(enable);
  7769. Client cli(HOST, port);
  7770. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7774. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7775. EXPECT_TRUE(res->body.empty());
  7776. }
  7777. TEST_F(StaticFileCompressionTest, MinLength) {
  7778. auto port = start(enable);
  7779. Client cli(HOST, port);
  7780. // 104 bytes, well under the default floor. Compressing it would add the
  7781. // gzip header and trailer to a body that already fits in one packet.
  7782. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7786. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7787. }
  7788. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7789. auto port = start([](Server &svr) {
  7790. svr.set_static_file_compression(true);
  7791. svr.set_static_file_compression_min_length(1);
  7792. });
  7793. Client cli(HOST, port);
  7794. cli.set_decompress(false);
  7795. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7798. // A 9-byte file comes back larger than it went in, because gzip's header and
  7799. // trailer outweigh anything deflate can save. That is the end of the range
  7800. // the floor exists to keep out.
  7801. EXPECT_GT(res->body.size(), 9U);
  7802. }
  7803. TEST_F(StaticFileCompressionTest, MaxLength) {
  7804. auto port = start([](Server &svr) {
  7805. svr.set_static_file_compression(true);
  7806. svr.set_static_file_compression_min_length(0);
  7807. svr.set_static_file_compression_max_length(1024);
  7808. });
  7809. Client cli(HOST, port);
  7810. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7811. // defines `small` as a macro on Windows.
  7812. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7813. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7814. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7815. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7816. // Under it: compressed.
  7817. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7819. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7820. }
  7821. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7822. auto port = start(enable_without_floor);
  7823. Client cli(HOST, port);
  7824. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7825. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7826. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7827. auto identity_etag = identity->get_header_value("ETag");
  7828. ASSERT_FALSE(identity_etag.empty());
  7829. auto gzipped =
  7830. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7831. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7832. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7833. auto gzip_etag = gzipped->get_header_value("ETag");
  7834. ASSERT_FALSE(gzip_etag.empty());
  7835. // Two representations, two validators.
  7836. EXPECT_NE(identity_etag, gzip_etag);
  7837. // Each one revalidates against the request that would produce it...
  7838. auto fresh =
  7839. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7840. {"If-None-Match", gzip_etag}});
  7841. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7842. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7843. auto fresh_identity =
  7844. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7845. {"If-None-Match", identity_etag}});
  7846. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7847. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7848. // ...and not against the other representation.
  7849. auto crossed =
  7850. cli.Get("/dir/index.html",
  7851. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7852. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7853. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7854. }
  7855. // The opt-in covers responses the server reads off disk itself. A caller's own
  7856. // known-length provider keeps its Content-Length and, more importantly, keeps
  7857. // delivering incrementally: routing it through a compressor would hold every
  7858. // write back until zlib's window filled.
  7859. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7860. auto port = start(enable);
  7861. Client cli(HOST, port);
  7862. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7866. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7867. EXPECT_EQ("aaabbb", res->body);
  7868. }
  7869. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7870. auto port = start(enable);
  7871. Client cli(HOST, port);
  7872. cli.set_read_timeout(1, 0);
  7873. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7874. Headers{{"Accept-Encoding", "gzip"}});
  7875. ASSERT_TRUE(handle.is_valid());
  7876. // The provider writes 100 bytes and then stalls for longer than the read
  7877. // timeout. Those first bytes have to arrive anyway: run the response through
  7878. // a compressor and zlib holds them until its window fills, so the read would
  7879. // come back empty instead.
  7880. char buf[256];
  7881. auto n = handle.read(buf, sizeof(buf));
  7882. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7883. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7884. }
  7885. #endif
  7886. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7887. TEST_F(ServerTest, Brotli) {
  7888. Headers headers;
  7889. headers.emplace("Accept-Encoding", "br");
  7890. auto res = cli_.Get("/compress", headers);
  7891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7894. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7895. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7896. "7890123456789012345678901234567890",
  7897. res->body);
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. }
  7900. #endif
  7901. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7902. TEST_F(ServerTest, Zstd) {
  7903. Headers headers;
  7904. headers.emplace("Accept-Encoding", "zstd");
  7905. auto res = cli_.Get("/compress", headers);
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7909. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7911. "7890123456789012345678901234567890",
  7912. res->body);
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. }
  7915. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7916. Headers headers;
  7917. headers.emplace("Accept-Encoding", "");
  7918. auto res = cli_.Get("/compress", headers);
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7922. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7923. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7924. "7890123456789012345678901234567890",
  7925. res->body);
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7929. Headers headers;
  7930. headers.emplace("Accept-Encoding", "zstd");
  7931. std::string body;
  7932. auto res = cli_.Get("/compress", headers,
  7933. [&](const char *data, uint64_t data_length) {
  7934. EXPECT_EQ(100U, data_length);
  7935. body.append(data, data_length);
  7936. return true;
  7937. });
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7941. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7942. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7943. "7890123456789012345678901234567890",
  7944. body);
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7948. Headers headers;
  7949. headers.emplace("Accept-Encoding", "zstd");
  7950. cli_.set_decompress(false);
  7951. auto res = cli_.Get("/compress", headers);
  7952. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7953. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7954. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7955. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7959. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. ASSERT_EQ(26U, res->body.size());
  7962. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7963. 0);
  7964. }
  7965. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7966. Headers headers;
  7967. headers.emplace("Accept-Encoding", "");
  7968. std::string body;
  7969. auto res = cli_.Get("/compress", headers,
  7970. [&](const char *data, uint64_t data_length) {
  7971. EXPECT_EQ(100U, data_length);
  7972. body.append(data, data_length);
  7973. return true;
  7974. });
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7978. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7979. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7980. "7890123456789012345678901234567890",
  7981. body);
  7982. EXPECT_EQ(StatusCode::OK_200, res->status);
  7983. }
  7984. TEST_F(ServerTest, NoZstd) {
  7985. Headers headers;
  7986. headers.emplace("Accept-Encoding", "zstd");
  7987. auto res = cli_.Get("/nocompress", headers);
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7990. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7991. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7992. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7993. "7890123456789012345678901234567890",
  7994. res->body);
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7998. Headers headers;
  7999. headers.emplace("Accept-Encoding", "zstd");
  8000. std::string body;
  8001. auto res = cli_.Get("/nocompress", headers,
  8002. [&](const char *data, uint64_t data_length) {
  8003. EXPECT_EQ(100U, data_length);
  8004. body.append(data, data_length);
  8005. return true;
  8006. });
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8009. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8010. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8011. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8012. "7890123456789012345678901234567890",
  8013. body);
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. }
  8016. // TODO: How to enable zstd ??
  8017. TEST_F(ServerTest, MultipartFormDataZstd) {
  8018. UploadFormDataItems items = {
  8019. {"key1", "test", "", ""},
  8020. {"key2", "--abcdefg123", "", ""},
  8021. };
  8022. Headers headers;
  8023. headers.emplace("Accept-Encoding", "zstd");
  8024. cli_.set_compress(true);
  8025. auto res = cli_.Post("/compress-multipart", headers, items);
  8026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "zstd");
  8032. cli_.set_compress(true);
  8033. auto res = cli_.Put(
  8034. "/put", headers, 3,
  8035. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8036. sink.os << "PUT";
  8037. return true;
  8038. },
  8039. "text/plain");
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("PUT", res->body);
  8043. }
  8044. // Pre-compression logging tests
  8045. TEST_F(ServerTest, PreCompressionLogging) {
  8046. // Test data for compression (matches the actual /compress endpoint content)
  8047. const std::string test_content =
  8048. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8049. "3456789012345678901234567890";
  8050. // Variables to capture logging data
  8051. std::string pre_compression_body;
  8052. std::string pre_compression_content_type;
  8053. std::string pre_compression_content_encoding;
  8054. std::string post_compression_body;
  8055. std::string post_compression_content_type;
  8056. std::string post_compression_content_encoding;
  8057. // Set up pre-compression logger
  8058. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8059. const Response &res) {
  8060. pre_compression_body = res.body;
  8061. pre_compression_content_type = res.get_header_value("Content-Type");
  8062. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8063. });
  8064. // Set up post-compression logger
  8065. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8066. post_compression_body = res.body;
  8067. post_compression_content_type = res.get_header_value("Content-Type");
  8068. post_compression_content_encoding =
  8069. res.get_header_value("Content-Encoding");
  8070. });
  8071. // Test with gzip compression
  8072. Headers headers;
  8073. headers.emplace("Accept-Encoding", "gzip");
  8074. auto res = cli_.Get("/compress", headers);
  8075. // Verify response was compressed
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8079. // Verify pre-compression logger captured uncompressed content
  8080. EXPECT_EQ(test_content, pre_compression_body);
  8081. EXPECT_EQ("text/plain", pre_compression_content_type);
  8082. EXPECT_TRUE(pre_compression_content_encoding
  8083. .empty()); // No encoding header before compression
  8084. // Verify post-compression logger captured compressed content
  8085. EXPECT_NE(test_content,
  8086. post_compression_body); // Should be different after compression
  8087. EXPECT_EQ("text/plain", post_compression_content_type);
  8088. EXPECT_EQ("gzip", post_compression_content_encoding);
  8089. // Verify compressed content is smaller
  8090. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8091. }
  8092. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8093. const std::string test_content =
  8094. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8095. "3456789012345678901234567890";
  8096. std::string pre_compression_body;
  8097. std::string post_compression_body;
  8098. svr_.set_pre_compression_logger(
  8099. [&](const Request & /*req*/, const Response &res) {
  8100. pre_compression_body = res.body;
  8101. });
  8102. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8103. post_compression_body = res.body;
  8104. });
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "br");
  8107. auto res = cli_.Get("/compress", headers);
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8111. // Verify pre-compression content is uncompressed
  8112. EXPECT_EQ(test_content, pre_compression_body);
  8113. // Verify post-compression content is compressed
  8114. EXPECT_NE(test_content, post_compression_body);
  8115. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8116. }
  8117. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8118. const std::string test_content =
  8119. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8120. "3456789012345678901234567890";
  8121. std::string pre_compression_body;
  8122. std::string post_compression_body;
  8123. svr_.set_pre_compression_logger(
  8124. [&](const Request & /*req*/, const Response &res) {
  8125. pre_compression_body = res.body;
  8126. });
  8127. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8128. post_compression_body = res.body;
  8129. });
  8130. // Request without compression (use /nocompress endpoint)
  8131. Headers headers;
  8132. auto res = cli_.Get("/nocompress", headers);
  8133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8134. EXPECT_EQ(StatusCode::OK_200, res->status);
  8135. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8136. // Pre-compression logger should not be called when no compression is applied
  8137. EXPECT_TRUE(
  8138. pre_compression_body.empty()); // Pre-compression logger not called
  8139. EXPECT_EQ(
  8140. test_content,
  8141. post_compression_body); // Post-compression logger captures final content
  8142. }
  8143. TEST_F(ServerTest, LoggerSeesContentLength) {
  8144. size_t logged_content_length = 0;
  8145. std::string logged_content_length_header;
  8146. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8147. logged_content_length = res.content_length_;
  8148. logged_content_length_header = res.get_header_value("Content-Length");
  8149. });
  8150. auto res = cli_.Get("/nocompress");
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ(res->body.size(), logged_content_length);
  8154. EXPECT_EQ(std::to_string(logged_content_length),
  8155. logged_content_length_header);
  8156. }
  8157. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8158. const std::string test_content =
  8159. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8160. "3456789012345678901234567890";
  8161. std::string pre_compression_body;
  8162. bool pre_logger_called = false;
  8163. // Set only pre-compression logger
  8164. svr_.set_pre_compression_logger(
  8165. [&](const Request & /*req*/, const Response &res) {
  8166. pre_compression_body = res.body;
  8167. pre_logger_called = true;
  8168. });
  8169. Headers headers;
  8170. headers.emplace("Accept-Encoding", "gzip");
  8171. auto res = cli_.Get("/compress", headers);
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(StatusCode::OK_200, res->status);
  8174. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8175. // Verify pre-compression logger was called
  8176. EXPECT_TRUE(pre_logger_called);
  8177. EXPECT_EQ(test_content, pre_compression_body);
  8178. }
  8179. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8180. {
  8181. // Test with Expect: 100-continue header - success case
  8182. // Server returns 100 Continue, client sends body, server returns 200 OK
  8183. Request req;
  8184. req.method = "POST";
  8185. req.path = "/post-large";
  8186. req.set_header("Expect", "100-continue");
  8187. req.body = LARGE_DATA;
  8188. Response res;
  8189. auto error = Error::Success;
  8190. cli_.set_keep_alive(true);
  8191. auto ret = cli_.send(req, res, error);
  8192. EXPECT_TRUE(ret);
  8193. EXPECT_EQ(StatusCode::OK_200, res.status);
  8194. EXPECT_EQ(LARGE_DATA, res.body);
  8195. }
  8196. {
  8197. // Test with Expect: 100-continue header - error case
  8198. // Client should not send the body when server returns an error
  8199. Request req;
  8200. req.method = "POST";
  8201. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8202. req.set_header("Expect", "100-continue");
  8203. req.body = LARGE_DATA;
  8204. Response res;
  8205. auto error = Error::Success;
  8206. auto start = std::chrono::high_resolution_clock::now();
  8207. cli_.set_keep_alive(true);
  8208. auto ret = cli_.send(req, res, error);
  8209. auto end = std::chrono::high_resolution_clock::now();
  8210. auto elapsed =
  8211. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8212. .count();
  8213. // With Expect: 100-continue, request completes successfully but with error
  8214. EXPECT_TRUE(ret);
  8215. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8216. EXPECT_EQ("close", res.get_header_value("Connection"));
  8217. EXPECT_FALSE(cli_.is_socket_open());
  8218. EXPECT_LE(elapsed, 2000);
  8219. }
  8220. {
  8221. // Send an extra GET request to ensure error recovery without hanging
  8222. Request req;
  8223. req.method = "GET";
  8224. req.path = "/hi";
  8225. auto start = std::chrono::high_resolution_clock::now();
  8226. auto res = cli_.send(req);
  8227. auto end = std::chrono::high_resolution_clock::now();
  8228. auto elapsed =
  8229. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8230. .count();
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. EXPECT_EQ("Hello World!", res->body);
  8234. EXPECT_LE(elapsed, 500);
  8235. }
  8236. }
  8237. TEST(ZstdDecompressor, ChunkedDecompression) {
  8238. std::string data;
  8239. for (size_t i = 0; i < 32 * 1024; ++i) {
  8240. data.push_back(static_cast<char>('a' + i % 26));
  8241. }
  8242. std::string compressed_data;
  8243. {
  8244. httplib::detail::zstd_compressor compressor;
  8245. bool result = compressor.compress(
  8246. data.data(), data.size(),
  8247. /*last=*/true,
  8248. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8249. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8250. compressed_data_size);
  8251. return true;
  8252. });
  8253. ASSERT_TRUE(result);
  8254. }
  8255. std::string decompressed_data;
  8256. {
  8257. httplib::detail::zstd_decompressor decompressor;
  8258. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8259. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8260. size_t chunk_size = 130;
  8261. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8262. chunk_begin += chunk_size) {
  8263. size_t current_chunk_size =
  8264. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8265. bool result = decompressor.decompress(
  8266. compressed_data.data() + chunk_begin, current_chunk_size,
  8267. [&](const char *decompressed_data_chunk,
  8268. size_t decompressed_data_chunk_size) {
  8269. decompressed_data.insert(decompressed_data.size(),
  8270. decompressed_data_chunk,
  8271. decompressed_data_chunk_size);
  8272. return true;
  8273. });
  8274. ASSERT_TRUE(result);
  8275. }
  8276. }
  8277. ASSERT_EQ(data, decompressed_data);
  8278. }
  8279. TEST(ZstdDecompressor, Decompress) {
  8280. std::string original_text = "Compressed with ZSTD";
  8281. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8282. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8283. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8284. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8285. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8286. std::string decompressed_data;
  8287. {
  8288. httplib::detail::zstd_decompressor decompressor;
  8289. bool result = decompressor.decompress(
  8290. compressed_data.data(), compressed_data.size(),
  8291. [&](const char *decompressed_data_chunk,
  8292. size_t decompressed_data_chunk_size) {
  8293. decompressed_data.insert(decompressed_data.size(),
  8294. decompressed_data_chunk,
  8295. decompressed_data_chunk_size);
  8296. return true;
  8297. });
  8298. ASSERT_TRUE(result);
  8299. }
  8300. ASSERT_EQ(original_text, decompressed_data);
  8301. }
  8302. #endif
  8303. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8304. // separate chunks so that the server sees each part in its own read(). Used to
  8305. // place a read boundary at a specific offset of a request body.
  8306. static bool send_request_in_parts(time_t read_timeout_sec,
  8307. const std::vector<std::string> &parts,
  8308. std::string *resp = nullptr,
  8309. int port = PORT) {
  8310. auto error = Error::Success;
  8311. auto client_sock = detail::create_client_socket(
  8312. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8313. /*connection_timeout_sec=*/5, 0,
  8314. /*read_timeout_sec=*/5, 0,
  8315. /*write_timeout_sec=*/5, 0, std::string(), error);
  8316. if (client_sock == INVALID_SOCKET) { return false; }
  8317. auto ret = detail::process_client_socket(
  8318. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8319. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8320. for (size_t i = 0; i < parts.size(); i++) {
  8321. const auto &part = parts[i];
  8322. if (part.size() !=
  8323. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8324. return false;
  8325. }
  8326. if (i + 1 < parts.size()) {
  8327. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8328. }
  8329. }
  8330. char buf[512];
  8331. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8332. while (line_reader.getline()) {
  8333. if (resp) { *resp += line_reader.ptr(); }
  8334. }
  8335. return true;
  8336. });
  8337. detail::close_socket(client_sock);
  8338. return ret;
  8339. }
  8340. // Sends a raw request to a server listening at HOST:PORT.
  8341. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8342. std::string *resp = nullptr, int port = PORT) {
  8343. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8344. }
  8345. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8346. Server svr;
  8347. std::string header_value;
  8348. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8349. header_value = req.get_header_value("foo");
  8350. res.set_content("ok", "text/plain");
  8351. });
  8352. thread t = thread([&] { svr.listen(HOST, PORT); });
  8353. auto se = detail::scope_exit([&] {
  8354. svr.stop();
  8355. t.join();
  8356. ASSERT_FALSE(svr.is_running());
  8357. });
  8358. svr.wait_until_ready();
  8359. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8360. // like characters are not treated the same - use vertical tab and escape.
  8361. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8362. "foo: \t \v bar \x1B\t \r\n"
  8363. "Connection: close\r\n"
  8364. "\r\n";
  8365. std::string res;
  8366. ASSERT_TRUE(send_request(5, req, &res));
  8367. EXPECT_EQ(header_value, "");
  8368. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8369. }
  8370. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8371. Server svr;
  8372. std::string received;
  8373. svr.Get("/order", [&](const Request &req, Response &res) {
  8374. received = entries_to_string(req.headers);
  8375. res.set_content("ok", "text/plain");
  8376. });
  8377. auto port = svr.bind_to_any_port(HOST);
  8378. thread t = thread([&] { svr.listen_after_bind(); });
  8379. auto se = detail::scope_exit([&] {
  8380. svr.stop();
  8381. t.join();
  8382. ASSERT_FALSE(svr.is_running());
  8383. });
  8384. svr.wait_until_ready();
  8385. const std::string req = "GET /order HTTP/1.1\r\n"
  8386. "X-First: 1\r\n"
  8387. "X-Dup: a\r\n"
  8388. "X-Second: 2\r\n"
  8389. "X-Dup: b\r\n"
  8390. "Connection: close\r\n"
  8391. "\r\n";
  8392. std::string res;
  8393. ASSERT_TRUE(send_request(5, req, &res, port));
  8394. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8395. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8396. }
  8397. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8398. Server svr;
  8399. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8400. res.set_header("Set-Cookie", "first=1");
  8401. res.set_header("X-Between", "y");
  8402. res.set_header("Set-Cookie", "second=2");
  8403. res.set_content("ok", "text/plain");
  8404. });
  8405. auto port = svr.bind_to_any_port(HOST);
  8406. thread t = thread([&] { svr.listen_after_bind(); });
  8407. auto se = detail::scope_exit([&] {
  8408. svr.stop();
  8409. t.join();
  8410. ASSERT_FALSE(svr.is_running());
  8411. });
  8412. svr.wait_until_ready();
  8413. Client cli(HOST, port);
  8414. auto res = cli.Get("/cookies");
  8415. ASSERT_TRUE(res);
  8416. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8417. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8418. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8419. }
  8420. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8421. Server svr;
  8422. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8423. auto i = new int(0);
  8424. res.set_header("Trailer", "X-Safe, X-Reflected");
  8425. res.set_chunked_content_provider(
  8426. "text/plain",
  8427. [i](size_t /*offset*/, DataSink &sink) {
  8428. if (*i == 0) {
  8429. sink.os << "body";
  8430. } else {
  8431. Headers trailer;
  8432. // A valid trailer that must survive.
  8433. trailer.emplace("X-Safe", "safe");
  8434. // Attacker-controlled value carrying CR/LF (response splitting).
  8435. trailer.emplace("X-Reflected",
  8436. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8437. // Attacker-controlled name carrying CR/LF.
  8438. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8439. sink.done_with_trailer(trailer);
  8440. }
  8441. (*i)++;
  8442. return true;
  8443. },
  8444. [i](bool /*success*/) { delete i; });
  8445. });
  8446. thread t = thread([&] { svr.listen(HOST, PORT); });
  8447. auto se = detail::scope_exit([&] {
  8448. svr.stop();
  8449. t.join();
  8450. ASSERT_FALSE(svr.is_running());
  8451. });
  8452. svr.wait_until_ready();
  8453. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8454. "Host: " + HOST +
  8455. "\r\n"
  8456. "Connection: close\r\n"
  8457. "\r\n";
  8458. std::string res;
  8459. ASSERT_TRUE(send_request(5, req, &res));
  8460. // The injected fields must not appear anywhere in the raw response.
  8461. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8462. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8463. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8464. // Invalid trailers are dropped entirely, matching set_header().
  8465. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8466. // The valid trailer still passes through.
  8467. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8468. }
  8469. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8470. Server svr;
  8471. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8472. // res.headers is a public field an application can populate directly,
  8473. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8474. // A valid header that must survive.
  8475. res.headers.emplace("X-Safe", "safe");
  8476. // Attacker-controlled value carrying CR/LF (response splitting).
  8477. res.headers.emplace("X-Reflected",
  8478. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8479. // Attacker-controlled name carrying CR/LF.
  8480. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8481. res.set_content("body", "text/plain");
  8482. });
  8483. thread t = thread([&] { svr.listen(HOST, PORT); });
  8484. auto se = detail::scope_exit([&] {
  8485. svr.stop();
  8486. t.join();
  8487. ASSERT_FALSE(svr.is_running());
  8488. });
  8489. svr.wait_until_ready();
  8490. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8491. "Host: " + HOST +
  8492. "\r\n"
  8493. "Connection: close\r\n"
  8494. "\r\n";
  8495. std::string res;
  8496. ASSERT_TRUE(send_request(5, req, &res));
  8497. // The injected fields must not appear anywhere in the raw response.
  8498. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8499. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8500. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8501. // Invalid headers are dropped entirely, matching set_header().
  8502. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8503. // The valid header still passes through.
  8504. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8505. }
  8506. // Forward declaration: in split builds split.py strips `inline` and moves the
  8507. // definition into httplib.cc, so detail::write_request_line is not visible from
  8508. // the public httplib.h. Re-declaring it here lets the tests link against the
  8509. // symbol in both header-only and split builds.
  8510. namespace httplib {
  8511. namespace detail {
  8512. ssize_t write_request_line(Stream &strm, const std::string &method,
  8513. const std::string &path);
  8514. } // namespace detail
  8515. } // namespace httplib
  8516. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8517. // A well-formed target is written verbatim.
  8518. {
  8519. detail::BufferStream strm;
  8520. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8521. EXPECT_GT(n, 0);
  8522. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8523. }
  8524. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8525. // otherwise it splits the request line and injects a header or a whole
  8526. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8527. // when path encoding is disabled.
  8528. const std::string evil_targets[] = {
  8529. "/a\r\nInjected: pwned",
  8530. "/a\rInjected",
  8531. "/a\nInjected",
  8532. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8533. };
  8534. for (const auto &evil : evil_targets) {
  8535. detail::BufferStream strm;
  8536. auto n = detail::write_request_line(strm, "GET", evil);
  8537. EXPECT_LT(n, 0);
  8538. EXPECT_TRUE(strm.get_buffer().empty());
  8539. }
  8540. }
  8541. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8542. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8543. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8544. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8545. // client must fail cleanly with Error::Write instead of putting a
  8546. // request-line-less, header-injecting request on the wire.
  8547. Server svr;
  8548. svr.Get("/a", [](const Request &, Response &res) {
  8549. res.set_content("ok", "text/plain");
  8550. });
  8551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8552. auto se = detail::scope_exit([&] {
  8553. svr.stop();
  8554. thread.join();
  8555. ASSERT_FALSE(svr.is_running());
  8556. });
  8557. svr.wait_until_ready();
  8558. {
  8559. Client cli(HOST, PORT);
  8560. cli.set_path_encode(false);
  8561. // The request is rejected before anything is written, so the connection
  8562. // stays silent and the subsequent response read would otherwise block for
  8563. // the full default read timeout. Shorten it -- the assertion is on the
  8564. // error, not the timeout.
  8565. cli.set_read_timeout(1, 0);
  8566. auto res = cli.Get("/a\r\nInjected: pwned");
  8567. EXPECT_FALSE(res);
  8568. EXPECT_EQ(Error::Write, res.error());
  8569. }
  8570. }
  8571. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8572. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8573. // including extension methods.
  8574. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8575. for (const auto &method : good_methods) {
  8576. detail::BufferStream strm;
  8577. auto n = detail::write_request_line(strm, method, "/");
  8578. EXPECT_GT(n, 0);
  8579. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8580. }
  8581. // A method carrying CR/LF would split the request line and smuggle a whole
  8582. // request ahead of the real one. A space or an empty method corrupts the
  8583. // request line. All must be rejected before anything reaches the wire.
  8584. const std::string evil_methods[] = {
  8585. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8586. "GET\r\nInjected: pwned",
  8587. "GET\r",
  8588. "GET\n",
  8589. "GE T",
  8590. "",
  8591. };
  8592. for (const auto &evil : evil_methods) {
  8593. detail::BufferStream strm;
  8594. auto n = detail::write_request_line(strm, evil, "/");
  8595. EXPECT_LT(n, 0);
  8596. EXPECT_TRUE(strm.get_buffer().empty());
  8597. }
  8598. }
  8599. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8600. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8601. // through Client::send must fail with Error::Write and no request, neither
  8602. // the smuggled one nor the real one, may reach the server.
  8603. Server svr;
  8604. std::atomic<int> request_count(0);
  8605. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8606. request_count++;
  8607. res.status = StatusCode::OK_200;
  8608. return Server::HandlerResponse::Handled;
  8609. });
  8610. auto port = svr.bind_to_any_port(HOST);
  8611. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8612. auto se = detail::scope_exit([&] {
  8613. svr.stop();
  8614. thread.join();
  8615. ASSERT_FALSE(svr.is_running());
  8616. });
  8617. svr.wait_until_ready();
  8618. {
  8619. Client cli(HOST, port);
  8620. const std::string evil_methods[] = {
  8621. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8622. "GE T",
  8623. "",
  8624. };
  8625. for (const auto &evil : evil_methods) {
  8626. Request req;
  8627. req.method = evil;
  8628. req.path = "/";
  8629. auto res = cli.send(req);
  8630. EXPECT_FALSE(res);
  8631. EXPECT_EQ(Error::Write, res.error());
  8632. }
  8633. auto handle =
  8634. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8635. EXPECT_FALSE(handle.is_valid());
  8636. EXPECT_EQ(Error::Write, handle.error);
  8637. // A valid request on the same client still goes through.
  8638. auto res = cli.Get("/");
  8639. ASSERT_TRUE(res);
  8640. EXPECT_EQ(StatusCode::OK_200, res->status);
  8641. }
  8642. EXPECT_EQ(1, request_count.load());
  8643. }
  8644. // Sends a raw request and verifies that there isn't a crash or exception.
  8645. static void test_raw_request(const std::string &req,
  8646. std::string *out = nullptr) {
  8647. Server svr;
  8648. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8649. res.set_content("ok", "text/plain");
  8650. });
  8651. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8652. res.set_content("ok", "text/plain");
  8653. });
  8654. svr.Get("/header_field_value_check",
  8655. [&](const Request & /*req*/, Response &res) {
  8656. res.set_content("ok", "text/plain");
  8657. });
  8658. svr.CustomRoute("PROPFIND", "/dav",
  8659. [&](const Request & /*req*/, Response &res) {
  8660. res.status = StatusCode::MultiStatus_207;
  8661. });
  8662. // Server read timeout must be longer than the client read timeout for the
  8663. // bug to reproduce, probably to force the server to process a request
  8664. // without a trailing blank line.
  8665. const time_t client_read_timeout_sec = 1;
  8666. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8667. bool listen_thread_ok = false;
  8668. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8669. auto se = detail::scope_exit([&] {
  8670. svr.stop();
  8671. t.join();
  8672. ASSERT_FALSE(svr.is_running());
  8673. EXPECT_TRUE(listen_thread_ok);
  8674. });
  8675. svr.wait_until_ready();
  8676. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8677. }
  8678. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8679. // A certain header line causes an exception if the header property is parsed
  8680. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8681. test_raw_request(
  8682. "GET /hi HTTP/1.1\r\n"
  8683. " : "
  8684. " "
  8685. " ");
  8686. }
  8687. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8688. // A certain header line causes an exception if the header property *name* is
  8689. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8690. // greedy matcher and requires backtracking when there are a lot of ":"
  8691. // characters.
  8692. // This occurs with libc++ but not libstdc++.
  8693. test_raw_request(
  8694. "GET /hi HTTP/1.1\r\n"
  8695. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8696. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8697. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8698. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8699. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8700. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8701. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8702. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8703. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8704. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8705. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8706. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8707. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8708. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8709. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8710. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8711. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8712. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8713. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8714. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8715. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8716. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8717. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8718. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8719. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8720. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8721. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8722. "&&&%%%");
  8723. }
  8724. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8725. // Make sure this doesn't crash the server.
  8726. // In a previous version of the header line regex, the "\r" rendered the line
  8727. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8728. // a new position where the leading white space ended and the field value
  8729. // began.
  8730. // The crash occurs with libc++ but not libstdc++.
  8731. test_raw_request("GET /hi HTTP/1.1\r\n"
  8732. "a:" +
  8733. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8734. "\r\n"
  8735. "\r\n");
  8736. }
  8737. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8738. std::string out;
  8739. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8740. "Content-Type: text/plain\r\n"
  8741. "Transfer-Encoding: chunked\r\n"
  8742. "\r\n"
  8743. "nothex\r\n",
  8744. &out);
  8745. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8746. }
  8747. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8748. std::string out;
  8749. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8750. "Content-Type: text/plain\r\n"
  8751. "Transfer-Encoding: chunked\r\n"
  8752. "\r\n"
  8753. "3\r\n"
  8754. "xyz\r\n"
  8755. "NaN\r\n",
  8756. &out);
  8757. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8758. }
  8759. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8760. std::string out;
  8761. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8762. "Content-Type: text/plain\r\n"
  8763. "Transfer-Encoding: chunked\r\n"
  8764. "\r\n"
  8765. // Length is too large for 64 bits.
  8766. "1ffffffffffffffff\r\n"
  8767. "xyz\r\n",
  8768. &out);
  8769. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8770. }
  8771. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8772. test_raw_request("GET /hi HTTP/1.1\r\n"
  8773. "Content-Type: text/plain\r\n\r");
  8774. }
  8775. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8776. std::string out;
  8777. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8778. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8779. }
  8780. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8781. Server svr;
  8782. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8783. EXPECT_TRUE(!req.remote_addr.empty());
  8784. });
  8785. thread t = thread([&] { svr.listen(HOST, PORT); });
  8786. auto se = detail::scope_exit([&] {
  8787. svr.stop();
  8788. t.join();
  8789. ASSERT_FALSE(svr.is_running());
  8790. });
  8791. svr.wait_until_ready();
  8792. // Send an invalid request line to trigger Bad Request
  8793. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8794. std::string out;
  8795. ASSERT_TRUE(send_request(5, bad_req, &out));
  8796. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8797. }
  8798. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8799. // answered right away rather than blocking on a read that waits for EOF.
  8800. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8801. std::string out;
  8802. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8803. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8804. }
  8805. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8806. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8807. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8808. for (const auto *method : methods) {
  8809. Server svr;
  8810. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8811. EXPECT_FALSE(svr.is_valid()) << method;
  8812. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8813. }
  8814. }
  8815. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8816. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8817. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8818. for (const auto *method : methods) {
  8819. Server svr;
  8820. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8821. EXPECT_FALSE(svr.is_valid()) << method;
  8822. }
  8823. }
  8824. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8825. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8826. "COPY", "MOVE", "LOCK",
  8827. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8828. Server svr;
  8829. for (const auto *method : methods) {
  8830. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8831. }
  8832. EXPECT_TRUE(svr.is_valid());
  8833. }
  8834. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8835. Server svr;
  8836. svr.CustomRoute("POST", "/x",
  8837. [](const Request &, Response &, const ContentReader &) {});
  8838. EXPECT_FALSE(svr.is_valid());
  8839. }
  8840. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8841. Server svr;
  8842. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8843. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8844. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8845. EXPECT_FALSE(svr.is_valid());
  8846. }
  8847. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8848. Server svr;
  8849. auto captured = Error::Success;
  8850. svr.set_error_logger(
  8851. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8852. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8853. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8854. }
  8855. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8856. std::string out;
  8857. std::string request(
  8858. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8859. test_raw_request(request, &out);
  8860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8861. }
  8862. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8863. std::string out;
  8864. std::string request(
  8865. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8866. test_raw_request(request, &out);
  8867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8868. }
  8869. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8870. std::string out;
  8871. std::string request(
  8872. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8873. test_raw_request(request, &out);
  8874. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8875. }
  8876. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8877. std::string out;
  8878. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8879. "Test: \r\n\r\n",
  8880. &out);
  8881. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8882. }
  8883. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8884. Server svr;
  8885. std::string x_custom;
  8886. std::string cookie;
  8887. std::string xff;
  8888. std::string x_unicode;
  8889. std::string x_iis;
  8890. svr.Get("/check", [&](const Request &req, Response &res) {
  8891. x_custom = req.get_header_value("X-Custom");
  8892. cookie = req.get_header_value("Cookie");
  8893. xff = req.get_header_value("X-Forwarded-For");
  8894. x_unicode = req.get_header_value("X-Unicode");
  8895. x_iis = req.get_header_value("X-IIS");
  8896. res.set_content("ok", "text/plain");
  8897. });
  8898. thread t = thread([&] { svr.listen(HOST, PORT); });
  8899. auto se = detail::scope_exit([&] {
  8900. svr.stop();
  8901. t.join();
  8902. ASSERT_FALSE(svr.is_running());
  8903. });
  8904. svr.wait_until_ready();
  8905. const std::string req = "GET /check HTTP/1.1\r\n"
  8906. "Host: localhost\r\n"
  8907. "X-Custom: a%0D%0AInjected: b\r\n"
  8908. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8909. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8910. "X-Unicode: %E3%81%82\r\n"
  8911. "X-IIS: %u00E9\r\n"
  8912. "Connection: close\r\n"
  8913. "\r\n";
  8914. std::string res;
  8915. ASSERT_TRUE(send_request(5, req, &res));
  8916. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8917. // Every value must be returned verbatim (wire form), with no decoding.
  8918. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8919. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8920. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8921. EXPECT_EQ("%E3%81%82", x_unicode);
  8922. EXPECT_EQ("%u00E9", x_iis);
  8923. }
  8924. // Applications that previously relied on automatic percent-decoding can
  8925. // reproduce the old behavior by explicitly calling decode_path_component()
  8926. // or, for RFC 3986 conformance, decode_uri_component().
  8927. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8928. Server svr;
  8929. std::string decoded;
  8930. svr.Get("/check", [&](const Request &req, Response &res) {
  8931. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8932. res.set_content("ok", "text/plain");
  8933. });
  8934. thread t = thread([&] { svr.listen(HOST, PORT); });
  8935. auto se = detail::scope_exit([&] {
  8936. svr.stop();
  8937. t.join();
  8938. ASSERT_FALSE(svr.is_running());
  8939. });
  8940. svr.wait_until_ready();
  8941. const std::string req = "GET /check HTTP/1.1\r\n"
  8942. "Host: localhost\r\n"
  8943. "X-Custom: hello%20world\r\n"
  8944. "Connection: close\r\n"
  8945. "\r\n";
  8946. std::string res;
  8947. ASSERT_TRUE(send_request(5, req, &res));
  8948. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8949. EXPECT_EQ("hello world", decoded);
  8950. }
  8951. // Regression test for #2033. Browsers send Referer values that include
  8952. // percent-encoded characters such as %0A inside the URL. Decoding the
  8953. // header value would either trip the post-decode CR/LF/NUL guard (the
  8954. // original bug, returning 400) or, after that guard was relaxed, silently
  8955. // store a literal LF — both unacceptable. The wire form must round-trip.
  8956. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8957. Server svr;
  8958. std::string referer;
  8959. svr.Get("/check", [&](const Request &req, Response &res) {
  8960. referer = req.get_header_value("Referer");
  8961. res.set_content("ok", "text/plain");
  8962. });
  8963. thread t = thread([&] { svr.listen(HOST, PORT); });
  8964. auto se = detail::scope_exit([&] {
  8965. svr.stop();
  8966. t.join();
  8967. ASSERT_FALSE(svr.is_running());
  8968. });
  8969. svr.wait_until_ready();
  8970. const std::string req = "GET /check HTTP/1.1\r\n"
  8971. "Host: localhost\r\n"
  8972. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8973. "Connection: close\r\n"
  8974. "\r\n";
  8975. std::string res;
  8976. ASSERT_TRUE(send_request(5, req, &res));
  8977. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8978. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8979. }
  8980. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8981. Server svr;
  8982. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8983. res.set_header("Cache-Control", "no-cache");
  8984. res.set_chunked_content_provider(
  8985. "text/event-stream", [](size_t offset, DataSink &sink) {
  8986. std::string s = "data:";
  8987. s += std::to_string(offset);
  8988. s += "\n\n";
  8989. auto ret = sink.write(s.data(), s.size());
  8990. EXPECT_TRUE(ret);
  8991. std::this_thread::sleep_for(std::chrono::seconds(1));
  8992. return true;
  8993. });
  8994. });
  8995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8996. svr.wait_until_ready();
  8997. Client client(HOST, PORT);
  8998. const Headers headers = {{"Accept", "text/event-stream"}};
  8999. auto get_thread = std::thread([&client, &headers]() {
  9000. auto res = client.Get(
  9001. "/events", headers,
  9002. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9003. });
  9004. auto se = detail::scope_exit([&] {
  9005. svr.stop();
  9006. get_thread.join();
  9007. listen_thread.join();
  9008. ASSERT_FALSE(svr.is_running());
  9009. });
  9010. // Give GET time to get a few messages.
  9011. std::this_thread::sleep_for(std::chrono::seconds(2));
  9012. }
  9013. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9014. httplib::Server svr;
  9015. svr.Post("/hi",
  9016. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9017. res.status = StatusCode::OK_200;
  9018. });
  9019. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9020. svr.wait_until_ready();
  9021. Client cli(HOST, PORT);
  9022. auto res = cli.Post("/hi", "data", "text/plain");
  9023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9024. EXPECT_EQ(StatusCode::OK_200, res->status);
  9025. svr.stop();
  9026. thread.join();
  9027. ASSERT_FALSE(svr.is_running());
  9028. res = cli.Post("/hi", "data", "text/plain");
  9029. ASSERT_FALSE(res);
  9030. }
  9031. TEST(ServerStopTest, ListenFailure) {
  9032. Server svr;
  9033. auto t = thread([&]() {
  9034. auto ret = svr.listen("????", PORT);
  9035. EXPECT_FALSE(ret);
  9036. });
  9037. svr.wait_until_ready();
  9038. svr.stop();
  9039. t.join();
  9040. }
  9041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9042. TEST(ServerStopTest, Decommision) {
  9043. Server svr;
  9044. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9045. for (int i = 0; i < 4; i++) {
  9046. auto is_even = !(i % 2);
  9047. std::thread t{[&] {
  9048. try {
  9049. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9050. if (is_even) {
  9051. throw std::runtime_error("Some thing that happens to go wrong.");
  9052. }
  9053. svr.listen(HOST, PORT);
  9054. } catch (...) { svr.decommission(); }
  9055. }};
  9056. svr.wait_until_ready();
  9057. // Server is up
  9058. {
  9059. Client cli(HOST, PORT);
  9060. auto res = cli.Get("/hi");
  9061. if (is_even) {
  9062. EXPECT_FALSE(res);
  9063. } else {
  9064. EXPECT_TRUE(res);
  9065. EXPECT_EQ("hi...", res->body);
  9066. }
  9067. }
  9068. svr.stop();
  9069. t.join();
  9070. // Server is down...
  9071. {
  9072. Client cli(HOST, PORT);
  9073. auto res = cli.Get("/hi");
  9074. EXPECT_FALSE(res);
  9075. }
  9076. }
  9077. }
  9078. #endif
  9079. // Helper function for string body upload progress tests
  9080. template <typename SetupHandler, typename ClientCall>
  9081. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9082. ClientCall &&client_call,
  9083. const string &body) {
  9084. Server svr;
  9085. setup_handler(svr);
  9086. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9087. auto se = detail::scope_exit([&] {
  9088. svr.stop();
  9089. t.join();
  9090. });
  9091. svr.wait_until_ready();
  9092. Client cli(HOST, PORT);
  9093. vector<uint64_t> progress_values;
  9094. bool progress_called = false;
  9095. auto res =
  9096. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9097. progress_values.push_back(current);
  9098. progress_called = true;
  9099. return true;
  9100. });
  9101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9102. EXPECT_EQ(200, res->status);
  9103. EXPECT_TRUE(progress_called);
  9104. }
  9105. TEST(UploadProgressTest, PostStringBodyBasic) {
  9106. TestStringBodyUploadProgress(
  9107. [](Server &svr) {
  9108. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9109. res.set_content("received", "text/plain");
  9110. });
  9111. },
  9112. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9113. return cli.Post("/test", body, "text/plain", progress_callback);
  9114. },
  9115. "test data for upload progress");
  9116. }
  9117. TEST(UploadProgressTest, PutStringBodyBasic) {
  9118. TestStringBodyUploadProgress(
  9119. [](Server &svr) {
  9120. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9121. res.set_content("put received", "text/plain");
  9122. });
  9123. },
  9124. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9125. return cli.Put("/test", body, "text/plain", progress_callback);
  9126. },
  9127. "put test data for upload progress");
  9128. }
  9129. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9130. TestStringBodyUploadProgress(
  9131. [](Server &svr) {
  9132. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9133. res.set_content("patch received", "text/plain");
  9134. });
  9135. },
  9136. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9137. return cli.Patch("/test", body, "text/plain", progress_callback);
  9138. },
  9139. "patch test data for upload progress");
  9140. }
  9141. // Helper function for content provider upload progress tests
  9142. template <typename SetupHandler, typename ClientCall>
  9143. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9144. ClientCall &&client_call) {
  9145. Server svr;
  9146. setup_handler(svr);
  9147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9148. auto se = detail::scope_exit([&] {
  9149. svr.stop();
  9150. t.join();
  9151. });
  9152. svr.wait_until_ready();
  9153. Client cli(HOST, PORT);
  9154. vector<uint64_t> progress_values;
  9155. auto res =
  9156. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9157. progress_values.push_back(current);
  9158. return true;
  9159. });
  9160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9161. EXPECT_EQ(200, res->status);
  9162. EXPECT_FALSE(progress_values.empty());
  9163. }
  9164. TEST(UploadProgressTest, PostContentProviderProgress) {
  9165. TestContentProviderUploadProgress(
  9166. [](Server &svr) {
  9167. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9168. res.set_content("provider received", "text/plain");
  9169. });
  9170. },
  9171. [](Client &cli, UploadProgress progress_callback) {
  9172. return cli.Post(
  9173. "/test", 10,
  9174. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9175. sink.os << "test data";
  9176. return true;
  9177. },
  9178. "text/plain", progress_callback);
  9179. });
  9180. }
  9181. // Helper function for multipart upload progress tests
  9182. template <typename SetupHandler, typename ClientCall>
  9183. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9184. ClientCall &&client_call,
  9185. const string &endpoint) {
  9186. Server svr;
  9187. setup_handler(svr);
  9188. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9189. auto se = detail::scope_exit([&] {
  9190. svr.stop();
  9191. t.join();
  9192. });
  9193. svr.wait_until_ready();
  9194. Client cli(HOST, PORT);
  9195. vector<uint64_t> progress_values;
  9196. UploadFormDataItems items = {
  9197. {"field1", "value1", "", ""},
  9198. {"field2", "longer value for progress tracking test", "", ""},
  9199. {"file1", "file content data for upload progress", "test.txt",
  9200. "text/plain"}};
  9201. auto res = client_call(cli, endpoint, items,
  9202. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9203. progress_values.push_back(current);
  9204. return true;
  9205. });
  9206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9207. EXPECT_EQ(200, res->status);
  9208. EXPECT_FALSE(progress_values.empty());
  9209. }
  9210. TEST(UploadProgressTest, PostMultipartProgress) {
  9211. TestMultipartUploadProgress(
  9212. [](Server &svr) {
  9213. svr.Post("/multipart", [](const Request &req, Response &res) {
  9214. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9215. res.set_content("multipart received", "text/plain");
  9216. });
  9217. },
  9218. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9219. UploadProgress progress_callback) {
  9220. return cli.Post(endpoint, items, progress_callback);
  9221. },
  9222. "/multipart");
  9223. }
  9224. // Helper function for basic download progress tests
  9225. template <typename SetupHandler, typename ClientCall>
  9226. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9227. ClientCall &&client_call, const string &endpoint,
  9228. size_t expected_content_size) {
  9229. Server svr;
  9230. setup_handler(svr);
  9231. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. t.join();
  9235. });
  9236. svr.wait_until_ready();
  9237. Client cli(HOST, PORT);
  9238. vector<uint64_t> progress_values;
  9239. auto res = client_call(cli, endpoint,
  9240. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9241. progress_values.push_back(current);
  9242. return true;
  9243. });
  9244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9245. EXPECT_EQ(200, res->status);
  9246. EXPECT_FALSE(progress_values.empty());
  9247. EXPECT_EQ(expected_content_size, res->body.size());
  9248. }
  9249. TEST(DownloadProgressTest, GetBasic) {
  9250. TestBasicDownloadProgress(
  9251. [](Server &svr) {
  9252. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9253. string content(1000, 'D');
  9254. res.set_content(content, "text/plain");
  9255. });
  9256. },
  9257. [](Client &cli, const string &endpoint,
  9258. DownloadProgress progress_callback) {
  9259. return cli.Get(endpoint, progress_callback);
  9260. },
  9261. "/download", 1000u);
  9262. }
  9263. // Helper function for content receiver download progress tests
  9264. template <typename SetupHandler, typename ClientCall>
  9265. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9266. ClientCall &&client_call,
  9267. const string &endpoint,
  9268. size_t expected_content_size) {
  9269. Server svr;
  9270. setup_handler(svr);
  9271. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9272. auto se = detail::scope_exit([&] {
  9273. svr.stop();
  9274. t.join();
  9275. });
  9276. svr.wait_until_ready();
  9277. Client cli(HOST, PORT);
  9278. vector<uint64_t> progress_values;
  9279. string received_body;
  9280. auto res = client_call(
  9281. cli, endpoint,
  9282. [&](const char *data, size_t data_length) -> bool {
  9283. received_body.append(data, data_length);
  9284. return true;
  9285. },
  9286. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9287. progress_values.push_back(current);
  9288. return true;
  9289. });
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ(200, res->status);
  9292. EXPECT_FALSE(progress_values.empty());
  9293. EXPECT_EQ(expected_content_size, received_body.size());
  9294. EXPECT_TRUE(res->body.empty());
  9295. }
  9296. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9297. TestContentReceiverDownloadProgress(
  9298. [](Server &svr) {
  9299. svr.Get("/download-receiver",
  9300. [](const Request & /*req*/, Response &res) {
  9301. string content(2000, 'R');
  9302. res.set_content(content, "text/plain");
  9303. });
  9304. },
  9305. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9306. DownloadProgress progress_callback) {
  9307. return cli.Get(endpoint, content_receiver, progress_callback);
  9308. },
  9309. "/download-receiver", 2000u);
  9310. }
  9311. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9312. // A provider reaching a pass with nothing to hand over - an empty buffer
  9313. // popped off a queue, say - must not be taken to mean the body is finished.
  9314. // It used to end the loop with the terminating chunk unwritten while the
  9315. // server still considered the response complete, so the peer waited for an
  9316. // end that never arrived.
  9317. Server svr;
  9318. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9319. auto step = std::make_shared<int>(0);
  9320. res.set_chunked_content_provider("text/plain",
  9321. [step](size_t /*offset*/, DataSink &sink) {
  9322. switch ((*step)++) {
  9323. case 0: sink.write("", 0); break;
  9324. case 1: sink.write("hello", 5); break;
  9325. default: sink.done(); break;
  9326. }
  9327. return true;
  9328. });
  9329. });
  9330. auto port = svr.bind_to_any_port(HOST);
  9331. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9332. auto listen_se = detail::scope_exit([&] {
  9333. svr.stop();
  9334. listen_thread.join();
  9335. ASSERT_FALSE(svr.is_running());
  9336. });
  9337. svr.wait_until_ready();
  9338. Client cli(HOST, port);
  9339. // Without the fix the body is never terminated, so bound the wait rather
  9340. // than letting the test hang on the default read timeout.
  9341. cli.set_read_timeout(5, 0);
  9342. auto res = cli.Get("/stream");
  9343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9344. EXPECT_EQ(StatusCode::OK_200, res->status);
  9345. EXPECT_EQ("hello", res->body);
  9346. }
  9347. TEST(StreamingTest, NoContentLengthStreaming) {
  9348. Server svr;
  9349. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9350. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9351. if (offset < 6) {
  9352. sink.os << (offset < 3 ? "a" : "b");
  9353. } else {
  9354. sink.done();
  9355. }
  9356. return true;
  9357. });
  9358. });
  9359. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9360. auto listen_se = detail::scope_exit([&] {
  9361. svr.stop();
  9362. listen_thread.join();
  9363. ASSERT_FALSE(svr.is_running());
  9364. });
  9365. svr.wait_until_ready();
  9366. Client client(HOST, PORT);
  9367. auto get_thread = std::thread([&client]() {
  9368. std::string s;
  9369. auto res =
  9370. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9371. s += std::string(data, len);
  9372. return true;
  9373. });
  9374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9375. EXPECT_EQ(StatusCode::OK_200, res->status);
  9376. EXPECT_EQ("aaabbb", s);
  9377. });
  9378. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9379. // Give GET time to get a few messages.
  9380. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9381. }
  9382. TEST(MountTest, Unmount) {
  9383. Server svr;
  9384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9385. auto se = detail::scope_exit([&] {
  9386. svr.stop();
  9387. listen_thread.join();
  9388. ASSERT_FALSE(svr.is_running());
  9389. });
  9390. svr.wait_until_ready();
  9391. Client cli("localhost", PORT);
  9392. svr.set_mount_point("/mount2", "./www2");
  9393. auto res = cli.Get("/");
  9394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9396. res = cli.Get("/mount2/dir/test.html");
  9397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9398. EXPECT_EQ(StatusCode::OK_200, res->status);
  9399. svr.set_mount_point("/", "./www");
  9400. res = cli.Get("/dir/");
  9401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9402. EXPECT_EQ(StatusCode::OK_200, res->status);
  9403. svr.remove_mount_point("/");
  9404. res = cli.Get("/dir/");
  9405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9407. svr.remove_mount_point("/mount2");
  9408. res = cli.Get("/mount2/dir/test.html");
  9409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9411. }
  9412. TEST(MountTest, PathSegmentBoundary) {
  9413. Server svr;
  9414. svr.set_mount_point("/mount2", "./www2");
  9415. svr.set_mount_point("/", "./www");
  9416. auto port = svr.bind_to_any_port(HOST);
  9417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9418. auto se = detail::scope_exit([&] {
  9419. svr.stop();
  9420. listen_thread.join();
  9421. ASSERT_FALSE(svr.is_running());
  9422. });
  9423. svr.wait_until_ready();
  9424. Client cli(HOST, port);
  9425. auto res = cli.Get("/mount2/dir/test.html");
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. // "/mount2" must not match part-way through a path segment.
  9429. res = cli.Get("/mount2dir/test.html");
  9430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9432. // A mount point ending in '/' keeps matching every path below it.
  9433. res = cli.Get("/dir/test.html");
  9434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9435. EXPECT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. TEST(MountTest, Redicect) {
  9438. Server svr;
  9439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9440. auto se = detail::scope_exit([&] {
  9441. svr.stop();
  9442. listen_thread.join();
  9443. ASSERT_FALSE(svr.is_running());
  9444. });
  9445. svr.set_mount_point("/", "./www");
  9446. svr.wait_until_ready();
  9447. Client cli("localhost", PORT);
  9448. auto res = cli.Get("/dir/");
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. res = cli.Get("/dir");
  9452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9453. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9454. res = cli.Get("/file");
  9455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9456. EXPECT_EQ(StatusCode::OK_200, res->status);
  9457. res = cli.Get("/file/");
  9458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9460. cli.set_follow_location(true);
  9461. res = cli.Get("/dir");
  9462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9463. EXPECT_EQ(StatusCode::OK_200, res->status);
  9464. }
  9465. TEST(MountTest, MultibytesPathName) {
  9466. Server svr;
  9467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9468. auto se = detail::scope_exit([&] {
  9469. svr.stop();
  9470. listen_thread.join();
  9471. ASSERT_FALSE(svr.is_running());
  9472. });
  9473. svr.set_mount_point("/", "./www");
  9474. svr.wait_until_ready();
  9475. Client cli("localhost", PORT);
  9476. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9478. EXPECT_EQ(StatusCode::OK_200, res->status);
  9479. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9480. }
  9481. #ifdef _WIN32
  9482. // Issue #2435: mmap::open() must succeed even when another handle holds
  9483. // the file open for writing (e.g. an active log file).
  9484. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9485. const char *path = "mmap_concurrent_writer_test.txt";
  9486. const char *content = "hello";
  9487. {
  9488. std::ofstream f(path, std::ios::binary);
  9489. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9490. }
  9491. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9492. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9493. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9494. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9495. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9496. detail::mmap m(path);
  9497. ASSERT_TRUE(m.is_open());
  9498. EXPECT_EQ(strlen(content), m.size());
  9499. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9500. }
  9501. #endif
  9502. #ifndef _WIN32
  9503. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9504. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9505. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9506. TEST(MmapTest, FailedMappingIsNotOpen) {
  9507. const char *path = "./mmap_failed_mapping_test_dir";
  9508. ASSERT_EQ(0, ::mkdir(path, 0755));
  9509. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9510. detail::mmap m(path);
  9511. EXPECT_FALSE(m.is_open());
  9512. EXPECT_EQ(0U, m.size());
  9513. EXPECT_NE(static_cast<const void *>(m.data()),
  9514. static_cast<const void *>(MAP_FAILED));
  9515. }
  9516. #endif
  9517. TEST(KeepAliveTest, ReadTimeout) {
  9518. Server svr;
  9519. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9520. std::this_thread::sleep_for(std::chrono::seconds(2));
  9521. res.set_content("a", "text/plain");
  9522. });
  9523. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9524. res.set_content("b", "text/plain");
  9525. });
  9526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. listen_thread.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. Client cli("localhost", PORT);
  9534. cli.set_keep_alive(true);
  9535. cli.set_read_timeout(std::chrono::seconds(1));
  9536. auto resa = cli.Get("/a");
  9537. ASSERT_FALSE(resa);
  9538. EXPECT_EQ(Error::Read, resa.error());
  9539. auto resb = cli.Get("/b");
  9540. ASSERT_TRUE(resb);
  9541. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9542. EXPECT_EQ("b", resb->body);
  9543. }
  9544. TEST(KeepAliveTest, MaxCount) {
  9545. size_t keep_alive_max_count = 3;
  9546. Server svr;
  9547. svr.set_keep_alive_max_count(keep_alive_max_count);
  9548. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9549. res.set_content("Hello World!", "text/plain");
  9550. });
  9551. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. listen_thread.join();
  9555. ASSERT_FALSE(svr.is_running());
  9556. });
  9557. svr.wait_until_ready();
  9558. Client cli(HOST, PORT);
  9559. cli.set_keep_alive(true);
  9560. for (size_t i = 0; i < 5; i++) {
  9561. auto result = cli.Get("/hi");
  9562. ASSERT_TRUE(result);
  9563. EXPECT_EQ(StatusCode::OK_200, result->status);
  9564. if (i == keep_alive_max_count - 1) {
  9565. EXPECT_EQ("close", result->get_header_value("Connection"));
  9566. } else {
  9567. EXPECT_FALSE(result->has_header("Connection"));
  9568. }
  9569. }
  9570. }
  9571. TEST(KeepAliveTest, Issue1041) {
  9572. Server svr;
  9573. svr.set_keep_alive_timeout(3);
  9574. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9575. res.set_content("Hello World!", "text/plain");
  9576. });
  9577. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. listen_thread.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. Client cli(HOST, PORT);
  9585. cli.set_keep_alive(true);
  9586. auto result = cli.Get("/hi");
  9587. ASSERT_TRUE(result);
  9588. EXPECT_EQ(StatusCode::OK_200, result->status);
  9589. std::this_thread::sleep_for(std::chrono::seconds(5));
  9590. result = cli.Get("/hi");
  9591. ASSERT_TRUE(result);
  9592. EXPECT_EQ(StatusCode::OK_200, result->status);
  9593. }
  9594. TEST(KeepAliveTest, Issue1959) {
  9595. Server svr;
  9596. svr.set_keep_alive_timeout(5);
  9597. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9598. res.set_content("a", "text/plain");
  9599. });
  9600. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. if (!svr.is_running()) return;
  9603. svr.stop();
  9604. listen_thread.join();
  9605. ASSERT_FALSE(svr.is_running());
  9606. });
  9607. svr.wait_until_ready();
  9608. Client cli("localhost", PORT);
  9609. cli.set_keep_alive(true);
  9610. using namespace std::chrono;
  9611. auto start = steady_clock::now();
  9612. cli.Get("/a");
  9613. svr.stop();
  9614. listen_thread.join();
  9615. auto end = steady_clock::now();
  9616. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9617. EXPECT_LT(elapsed, 5000);
  9618. }
  9619. #ifdef CPPHTTPLIB_SSL_ENABLED
  9620. TEST(KeepAliveTest, SSLClientReconnection) {
  9621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9622. ASSERT_TRUE(svr.is_valid());
  9623. svr.set_keep_alive_timeout(1);
  9624. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9625. res.set_content("Hello World!", "text/plain");
  9626. });
  9627. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9628. auto se = detail::scope_exit([&] {
  9629. svr.stop();
  9630. listen_thread.join();
  9631. ASSERT_FALSE(svr.is_running());
  9632. });
  9633. svr.wait_until_ready();
  9634. SSLClient cli(HOST, PORT);
  9635. cli.enable_server_certificate_verification(false);
  9636. cli.set_keep_alive(true);
  9637. auto result = cli.Get("/hi");
  9638. ASSERT_TRUE(result);
  9639. EXPECT_EQ(StatusCode::OK_200, result->status);
  9640. result = cli.Get("/hi");
  9641. ASSERT_TRUE(result);
  9642. EXPECT_EQ(StatusCode::OK_200, result->status);
  9643. std::this_thread::sleep_for(std::chrono::seconds(2));
  9644. // Recoonect
  9645. result = cli.Get("/hi");
  9646. ASSERT_TRUE(result);
  9647. EXPECT_EQ(StatusCode::OK_200, result->status);
  9648. result = cli.Get("/hi");
  9649. ASSERT_TRUE(result);
  9650. EXPECT_EQ(StatusCode::OK_200, result->status);
  9651. }
  9652. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9654. ASSERT_TRUE(svr.is_valid());
  9655. svr.set_keep_alive_timeout(1);
  9656. std::string content = "reconnect";
  9657. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9658. res.set_content("Hello World!", "text/plain");
  9659. });
  9660. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9661. auto se = detail::scope_exit([&] {
  9662. svr.stop();
  9663. listen_thread.join();
  9664. ASSERT_FALSE(svr.is_running());
  9665. });
  9666. svr.wait_until_ready();
  9667. SSLClient cli(HOST, PORT);
  9668. cli.enable_server_certificate_verification(false);
  9669. cli.set_keep_alive(true);
  9670. auto result = cli.Post(
  9671. "/hi", content.size(),
  9672. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9673. sink.write(content.c_str(), content.size());
  9674. return true;
  9675. },
  9676. "text/plain");
  9677. ASSERT_TRUE(result);
  9678. EXPECT_EQ(200, result->status);
  9679. std::this_thread::sleep_for(std::chrono::seconds(2));
  9680. // Recoonect
  9681. result = cli.Post(
  9682. "/hi", content.size(),
  9683. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9684. sink.write(content.c_str(), content.size());
  9685. return true;
  9686. },
  9687. "text/plain");
  9688. ASSERT_TRUE(result);
  9689. EXPECT_EQ(200, result->status);
  9690. result = cli.Post(
  9691. "/hi", content.size(),
  9692. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9693. sink.write(content.c_str(), content.size());
  9694. return true;
  9695. },
  9696. "text/plain");
  9697. ASSERT_TRUE(result);
  9698. EXPECT_EQ(200, result->status);
  9699. }
  9700. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9701. using namespace httplib::tls;
  9702. {
  9703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9704. ASSERT_TRUE(svr.is_valid());
  9705. svr.Get("/sni", [&](const Request &req, Response &res) {
  9706. std::string expected = req.sni();
  9707. EXPECT_EQ(expected, req.get_param_value("expected"));
  9708. res.set_content("ok", "text/plain");
  9709. });
  9710. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9711. auto se = detail::scope_exit([&] {
  9712. svr.stop();
  9713. listen_thread.join();
  9714. ASSERT_FALSE(svr.is_running());
  9715. });
  9716. svr.wait_until_ready();
  9717. {
  9718. SSLClient cli("localhost", PORT);
  9719. cli.enable_server_certificate_verification(false);
  9720. auto res = cli.Get("/sni?expected=localhost");
  9721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9722. }
  9723. {
  9724. SSLClient cli("::1", PORT);
  9725. cli.enable_server_certificate_verification(false);
  9726. auto res = cli.Get("/sni?expected=");
  9727. // NOTE: This may fail if the server is listening on IPv4 only
  9728. // (e.g., when localhost resolves to 127.0.0.1 only)
  9729. if (res) {
  9730. EXPECT_EQ(StatusCode::OK_200, res->status);
  9731. } else {
  9732. EXPECT_EQ(Error::Connection, res.error());
  9733. }
  9734. }
  9735. }
  9736. }
  9737. #endif
  9738. TEST(ClientProblemDetectionTest, ContentProvider) {
  9739. Server svr;
  9740. size_t content_length = 1024 * 1024;
  9741. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9742. res.set_content_provider(
  9743. content_length, "text/plain",
  9744. [&](size_t offset, size_t length, DataSink &sink) {
  9745. auto out_len = std::min(length, static_cast<size_t>(1024));
  9746. std::string out(out_len, '@');
  9747. sink.write(out.data(), out_len);
  9748. return offset < 4096;
  9749. },
  9750. [](bool success) { ASSERT_FALSE(success); });
  9751. });
  9752. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9753. res.set_content_provider(
  9754. 0, "text/plain",
  9755. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9756. EXPECT_TRUE(false);
  9757. return true;
  9758. },
  9759. [](bool success) { ASSERT_FALSE(success); });
  9760. });
  9761. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. listen_thread.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. });
  9767. svr.wait_until_ready();
  9768. Client cli("localhost", PORT);
  9769. {
  9770. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9771. size_t /*data_length*/) { return false; });
  9772. ASSERT_FALSE(res);
  9773. }
  9774. {
  9775. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9776. size_t /*data_length*/) { return false; });
  9777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9778. }
  9779. }
  9780. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9781. // A provider that reports success without writing anything and without
  9782. // calling done() used to be handed the same offset and length again on every
  9783. // pass, so it spun for as long as the peer stayed connected.
  9784. Server svr;
  9785. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9786. res.set_content("ok", "text/plain");
  9787. });
  9788. auto port = svr.bind_to_any_port(HOST);
  9789. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. listen_thread.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. });
  9795. svr.wait_until_ready();
  9796. std::atomic<int> call_count{0};
  9797. Client cli(HOST, port);
  9798. auto res = cli.Post(
  9799. "/", 1024,
  9800. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9801. // Give up after enough passes to show the spin, so that losing the
  9802. // check below fails this test instead of hanging it.
  9803. return ++call_count < 100;
  9804. },
  9805. "text/plain");
  9806. ASSERT_FALSE(res);
  9807. EXPECT_EQ(Error::Write, res.error());
  9808. EXPECT_EQ(1, call_count.load());
  9809. }
  9810. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9811. // A writer only has to assign `write`. The other three used to be left as
  9812. // empty std::functions, so a provider calling one threw
  9813. // std::bad_function_call out of the thread running it and took the whole
  9814. // process down.
  9815. DataSink sink;
  9816. std::string written;
  9817. sink.write = [&](const char *data, size_t data_len) {
  9818. written.append(data, data_len);
  9819. return true;
  9820. };
  9821. EXPECT_TRUE(sink.is_writable());
  9822. sink.done();
  9823. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9824. EXPECT_TRUE(written.empty());
  9825. }
  9826. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9827. // A sink that cannot carry trailers still has to finish.
  9828. DataSink sink;
  9829. auto done_count = 0;
  9830. sink.done = [&]() { done_count++; };
  9831. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9832. EXPECT_EQ(1, done_count);
  9833. }
  9834. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9835. Server svr;
  9836. const std::string body(4096, 'x');
  9837. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9838. res.set_content_provider(body.size(), "text/plain",
  9839. [&](size_t offset, size_t length, DataSink &sink) {
  9840. sink.write(body.data() + offset, length);
  9841. sink.done();
  9842. return true;
  9843. });
  9844. });
  9845. auto port = svr.bind_to_any_port(HOST);
  9846. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9847. auto se = detail::scope_exit([&] {
  9848. svr.stop();
  9849. listen_thread.join();
  9850. ASSERT_FALSE(svr.is_running());
  9851. });
  9852. svr.wait_until_ready();
  9853. Client cli(HOST, port);
  9854. auto res = cli.Get("/");
  9855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. EXPECT_EQ(body, res->body);
  9858. }
  9859. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9860. Server svr;
  9861. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9862. res.set_content_provider(
  9863. 1024, "text/plain",
  9864. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9865. sink.write("hello", 5);
  9866. sink.done(); // short of the 1024 bytes the response promised
  9867. return true;
  9868. });
  9869. });
  9870. auto port = svr.bind_to_any_port(HOST);
  9871. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9872. auto se = detail::scope_exit([&] {
  9873. svr.stop();
  9874. listen_thread.join();
  9875. ASSERT_FALSE(svr.is_running());
  9876. });
  9877. svr.wait_until_ready();
  9878. Client cli(HOST, port);
  9879. cli.set_read_timeout(5, 0);
  9880. // The response is short of its Content-Length, so the client cannot read a
  9881. // complete body. What matters is that this returns at all: a no-op done()
  9882. // would leave the writer looping over a provider that never makes progress.
  9883. auto res = cli.Get("/");
  9884. EXPECT_FALSE(res);
  9885. }
  9886. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9887. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9888. // The compressed path builds the whole body before connecting, so this
  9889. // fails client-side and never reaches a server.
  9890. Client cli(HOST, PORT);
  9891. cli.set_compress(true);
  9892. auto res = cli.Post(
  9893. "/", 1024,
  9894. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9895. sink.write("hello", 5);
  9896. sink.done(); // short of the 1024 bytes the request announced
  9897. return true;
  9898. },
  9899. "text/plain");
  9900. ASSERT_FALSE(res);
  9901. EXPECT_EQ(Error::Write, res.error());
  9902. }
  9903. #endif
  9904. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9905. Server svr;
  9906. svr.set_error_handler([](Request const &, Response &res) -> void {
  9907. res.set_chunked_content_provider(
  9908. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9909. sink.os << "hello";
  9910. sink.os << "world";
  9911. sink.done();
  9912. return true;
  9913. });
  9914. });
  9915. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9916. auto se = detail::scope_exit([&] {
  9917. svr.stop();
  9918. listen_thread.join();
  9919. ASSERT_FALSE(svr.is_running());
  9920. });
  9921. svr.wait_until_ready();
  9922. Client cli("localhost", PORT);
  9923. auto res = cli.Get("/");
  9924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9926. EXPECT_EQ("helloworld", res->body);
  9927. }
  9928. TEST(LongPollingTest, ClientCloseDetection) {
  9929. Server svr;
  9930. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9931. res.set_chunked_content_provider(
  9932. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9933. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9934. sink.os << "hello";
  9935. auto count = 10;
  9936. while (count > 0 && sink.is_writable()) {
  9937. this_thread::sleep_for(chrono::milliseconds(10));
  9938. count--;
  9939. }
  9940. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9941. return true;
  9942. });
  9943. });
  9944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. listen_thread.join();
  9948. ASSERT_FALSE(svr.is_running());
  9949. });
  9950. svr.wait_until_ready();
  9951. Client cli("localhost", PORT);
  9952. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9953. EXPECT_EQ("hello", string(data, data_length));
  9954. return false; // close the socket immediately.
  9955. });
  9956. ASSERT_FALSE(res);
  9957. }
  9958. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9959. Server svr;
  9960. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9961. res.set_chunked_content_provider(
  9962. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9963. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9964. sink.os << "hello";
  9965. EXPECT_TRUE(sink.os.good());
  9966. // Wait for the client to close the connection
  9967. auto count = 10;
  9968. while (count > 0 && sink.is_writable()) {
  9969. this_thread::sleep_for(chrono::milliseconds(10));
  9970. count--;
  9971. }
  9972. // After client disconnect, write repeatedly until the socket
  9973. // write actually fails (small writes may be absorbed by the
  9974. // kernel buffer)
  9975. std::string chunk(1024, 'x');
  9976. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9977. sink.os << chunk;
  9978. }
  9979. EXPECT_TRUE(sink.os.fail());
  9980. return true;
  9981. });
  9982. });
  9983. auto port = svr.bind_to_any_port("localhost");
  9984. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9985. auto se = detail::scope_exit([&] {
  9986. svr.stop();
  9987. listen_thread.join();
  9988. ASSERT_FALSE(svr.is_running());
  9989. });
  9990. svr.wait_until_ready();
  9991. Client cli("localhost", port);
  9992. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9993. EXPECT_EQ("hello", string(data, data_length));
  9994. return false; // close the socket immediately.
  9995. });
  9996. ASSERT_FALSE(res);
  9997. }
  9998. TEST(GetWithParametersTest, GetWithParameters) {
  9999. Server svr;
  10000. svr.Get("/", [&](const Request &req, Response &) {
  10001. EXPECT_EQ("world", req.get_param_value("hello"));
  10002. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10003. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10004. });
  10005. svr.Get("/params", [&](const Request &req, Response &) {
  10006. EXPECT_EQ("world", req.get_param_value("hello"));
  10007. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10008. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10009. });
  10010. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10011. EXPECT_EQ("resource-id", req.matches[1]);
  10012. EXPECT_EQ("foo", req.get_param_value("param1"));
  10013. EXPECT_EQ("bar", req.get_param_value("param2"));
  10014. });
  10015. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10016. EXPECT_EQ("user-id", req.path_params.at("id"));
  10017. EXPECT_EQ("foo", req.get_param_value("param1"));
  10018. EXPECT_EQ("bar", req.get_param_value("param2"));
  10019. });
  10020. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. listen_thread.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. {
  10028. Client cli(HOST, PORT);
  10029. Params params;
  10030. params.emplace("hello", "world");
  10031. params.emplace("hello2", "world2");
  10032. params.emplace("hello3", "world3");
  10033. auto res = cli.Get("/", params, Headers{});
  10034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10035. EXPECT_EQ(StatusCode::OK_200, res->status);
  10036. }
  10037. {
  10038. Client cli(HOST, PORT);
  10039. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10041. EXPECT_EQ(StatusCode::OK_200, res->status);
  10042. }
  10043. {
  10044. Client cli(HOST, PORT);
  10045. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. }
  10049. {
  10050. Client cli(HOST, PORT);
  10051. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10053. EXPECT_EQ(StatusCode::OK_200, res->status);
  10054. }
  10055. }
  10056. TEST(GetWithParametersTest, GetWithParameters2) {
  10057. Server svr;
  10058. svr.Get("/", [&](const Request &req, Response &res) {
  10059. auto text = req.get_param_value("hello");
  10060. res.set_content(text, "text/plain");
  10061. });
  10062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10063. auto se = detail::scope_exit([&] {
  10064. svr.stop();
  10065. listen_thread.join();
  10066. ASSERT_FALSE(svr.is_running());
  10067. });
  10068. svr.wait_until_ready();
  10069. Client cli("localhost", PORT);
  10070. Params params;
  10071. params.emplace("hello", "world");
  10072. std::string body;
  10073. auto res = cli.Get("/", params, Headers{},
  10074. [&](const char *data, size_t data_length) {
  10075. body.append(data, data_length);
  10076. return true;
  10077. });
  10078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10079. EXPECT_EQ(StatusCode::OK_200, res->status);
  10080. EXPECT_EQ("world", body);
  10081. }
  10082. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10083. Server svr;
  10084. svr.Get("/search", [&](const Request &req, Response &res) {
  10085. auto q = req.get_param_value("q");
  10086. res.set_content(q, "text/plain");
  10087. });
  10088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10089. auto se = detail::scope_exit([&] {
  10090. svr.stop();
  10091. listen_thread.join();
  10092. ASSERT_FALSE(svr.is_running());
  10093. });
  10094. svr.wait_until_ready();
  10095. Client cli("localhost", PORT);
  10096. // Verify that Get(path, params) works without requiring Headers argument
  10097. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10099. EXPECT_EQ(StatusCode::OK_200, res->status);
  10100. EXPECT_EQ("cpp-httplib", res->body);
  10101. }
  10102. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10103. auto host = "httpbingo.org";
  10104. auto path = std::string{"/range/32"};
  10105. #ifdef CPPHTTPLIB_SSL_ENABLED
  10106. SSLClient cli(host);
  10107. #else
  10108. Client cli(host);
  10109. #endif
  10110. cli.set_default_headers({make_range_header({{1, 10}})});
  10111. cli.set_connection_timeout(5);
  10112. {
  10113. auto res = cli.Get(path);
  10114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10115. EXPECT_EQ("bcdefghijk", res->body);
  10116. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10117. }
  10118. {
  10119. auto res = cli.Get(path);
  10120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10121. EXPECT_EQ("bcdefghijk", res->body);
  10122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10123. }
  10124. }
  10125. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10126. Server svr;
  10127. svr.set_default_headers({{"Hello", "World"}});
  10128. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10129. res.set_content("ok", "text/plain");
  10130. });
  10131. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10132. auto se = detail::scope_exit([&] {
  10133. svr.stop();
  10134. listen_thread.join();
  10135. ASSERT_FALSE(svr.is_running());
  10136. });
  10137. svr.wait_until_ready();
  10138. Client cli("localhost", PORT);
  10139. auto res = cli.Get("/");
  10140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10141. EXPECT_EQ(StatusCode::OK_200, res->status);
  10142. EXPECT_EQ("ok", res->body);
  10143. EXPECT_EQ("World", res->get_header_value("Hello"));
  10144. }
  10145. #ifdef CPPHTTPLIB_SSL_ENABLED
  10146. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10148. ASSERT_TRUE(svr.is_valid());
  10149. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10150. std::this_thread::sleep_for(std::chrono::seconds(2));
  10151. res.set_content("a", "text/plain");
  10152. });
  10153. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10154. res.set_content("b", "text/plain");
  10155. });
  10156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. listen_thread.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. SSLClient cli("localhost", PORT);
  10164. cli.enable_server_certificate_verification(false);
  10165. cli.set_keep_alive(true);
  10166. cli.set_read_timeout(std::chrono::seconds(1));
  10167. auto resa = cli.Get("/a");
  10168. ASSERT_TRUE(!resa);
  10169. EXPECT_EQ(Error::Read, resa.error());
  10170. auto resb = cli.Get("/b");
  10171. ASSERT_TRUE(resb);
  10172. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10173. EXPECT_EQ("b", resb->body);
  10174. }
  10175. // Closing an idle keep-alive connection sends close_notify and returns. The
  10176. // server must not wait for the client's close_notify: an idle client never
  10177. // sends one, so the worker would be held until the read timeout expires, and
  10178. // stop() would wait for it.
  10179. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10181. ASSERT_TRUE(svr.is_valid());
  10182. svr.set_keep_alive_timeout(1);
  10183. svr.set_read_timeout(10, 0);
  10184. svr.Get("/", [](const Request &, Response &res) {
  10185. res.set_content("ok", "text/plain");
  10186. });
  10187. auto port = svr.bind_to_any_port(HOST);
  10188. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10189. auto se = detail::scope_exit([&] {
  10190. if (listen_thread.joinable()) {
  10191. svr.stop();
  10192. listen_thread.join();
  10193. }
  10194. });
  10195. svr.wait_until_ready();
  10196. SSLClient cli(HOST, port);
  10197. cli.enable_server_certificate_verification(false);
  10198. cli.set_keep_alive(true);
  10199. auto res = cli.Get("/");
  10200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10201. EXPECT_EQ(StatusCode::OK_200, res->status);
  10202. // Stay idle past the keep-alive timeout so the server closes the connection.
  10203. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10204. auto start = std::chrono::steady_clock::now();
  10205. svr.stop();
  10206. listen_thread.join();
  10207. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10208. std::chrono::steady_clock::now() - start)
  10209. .count();
  10210. EXPECT_LT(elapsed, 3000);
  10211. }
  10212. #endif
  10213. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10214. protected:
  10215. ServerTestWithAI_PASSIVE()
  10216. : cli_(HOST, PORT)
  10217. #ifdef CPPHTTPLIB_SSL_ENABLED
  10218. ,
  10219. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10220. #endif
  10221. {
  10222. #ifdef CPPHTTPLIB_SSL_ENABLED
  10223. cli_.enable_server_certificate_verification(false);
  10224. #endif
  10225. }
  10226. virtual void SetUp() {
  10227. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10228. res.set_content("Hello World!", "text/plain");
  10229. });
  10230. t_ = thread(
  10231. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10232. svr_.wait_until_ready();
  10233. }
  10234. virtual void TearDown() {
  10235. svr_.stop();
  10236. t_.join();
  10237. }
  10238. #ifdef CPPHTTPLIB_SSL_ENABLED
  10239. SSLClient cli_;
  10240. SSLServer svr_;
  10241. #else
  10242. Client cli_;
  10243. Server svr_;
  10244. #endif
  10245. thread t_;
  10246. };
  10247. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10248. auto res = cli_.Get("/hi");
  10249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10250. EXPECT_EQ(StatusCode::OK_200, res->status);
  10251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10252. EXPECT_EQ("Hello World!", res->body);
  10253. }
  10254. class ServerUpDownTest : public ::testing::Test {
  10255. protected:
  10256. ServerUpDownTest() : cli_(HOST, PORT) {}
  10257. virtual void SetUp() {
  10258. t_ = thread([&]() {
  10259. svr_.bind_to_any_port(HOST);
  10260. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10261. ASSERT_TRUE(svr_.listen_after_bind());
  10262. });
  10263. svr_.wait_until_ready();
  10264. }
  10265. virtual void TearDown() {
  10266. svr_.stop();
  10267. t_.join();
  10268. }
  10269. Client cli_;
  10270. Server svr_;
  10271. thread t_;
  10272. };
  10273. TEST_F(ServerUpDownTest, QuickStartStop) {
  10274. // Should not crash, especially when run with
  10275. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10276. }
  10277. class PayloadMaxLengthTest : public ::testing::Test {
  10278. protected:
  10279. PayloadMaxLengthTest()
  10280. : cli_(HOST, PORT)
  10281. #ifdef CPPHTTPLIB_SSL_ENABLED
  10282. ,
  10283. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10284. #endif
  10285. {
  10286. #ifdef CPPHTTPLIB_SSL_ENABLED
  10287. cli_.enable_server_certificate_verification(false);
  10288. #endif
  10289. }
  10290. virtual void SetUp() {
  10291. svr_.set_payload_max_length(8);
  10292. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10293. res.set_content("test", "text/plain");
  10294. });
  10295. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10296. svr_.wait_until_ready();
  10297. }
  10298. virtual void TearDown() {
  10299. svr_.stop();
  10300. t_.join();
  10301. }
  10302. #ifdef CPPHTTPLIB_SSL_ENABLED
  10303. SSLClient cli_;
  10304. SSLServer svr_;
  10305. #else
  10306. Client cli_;
  10307. Server svr_;
  10308. #endif
  10309. thread t_;
  10310. };
  10311. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10312. auto res = cli_.Post("/test", "123456789", "text/plain");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10315. res = cli_.Post("/test", "12345678", "text/plain");
  10316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. }
  10319. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10320. // Test chunked encoding with payload exceeding the 8-byte limit
  10321. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10322. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10324. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10325. }
  10326. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10327. // Test chunked encoding with payload within the 8-byte limit
  10328. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10329. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. EXPECT_EQ(StatusCode::OK_200, res->status);
  10332. }
  10333. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10334. // Test using send_request to send chunked data exceeding payload limit
  10335. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10336. "Host: " +
  10337. std::string(HOST) + ":" + std::to_string(PORT) +
  10338. "\r\n"
  10339. "Transfer-Encoding: chunked\r\n"
  10340. "Connection: close\r\n"
  10341. "\r\n"
  10342. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10343. "0123456789\r\n"
  10344. "0\r\n" // End chunk
  10345. "\r\n";
  10346. std::string response;
  10347. bool result = send_request(1, chunked_request, &response);
  10348. if (!result) {
  10349. // If send_request fails, it might be because the server closed the
  10350. // connection due to payload limit enforcement, which is acceptable
  10351. SUCCEED()
  10352. << "Server rejected oversized chunked request (connection closed)";
  10353. } else {
  10354. // If we got a response, check if it's an error response or connection was
  10355. // closed early Short response length indicates connection was closed due to
  10356. // payload limit
  10357. if (response.length() <= 10) {
  10358. SUCCEED() << "Server closed connection for oversized chunked request";
  10359. } else {
  10360. // Check for error status codes
  10361. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10362. response.find("Payload Too Large") != std::string::npos ||
  10363. response.find("400") != std::string::npos);
  10364. }
  10365. }
  10366. }
  10367. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10368. // Test request without Content-Length header exceeding payload limit
  10369. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10370. "Host: " +
  10371. std::string(HOST) + ":" +
  10372. std::to_string(PORT) +
  10373. "\r\n"
  10374. "Connection: close\r\n"
  10375. "\r\n";
  10376. // Add payload exceeding the 8-byte limit
  10377. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10378. request_without_content_length += large_payload;
  10379. std::string response;
  10380. bool result = send_request(1, request_without_content_length, &response);
  10381. if (!result) {
  10382. // If send_request fails, server likely closed connection due to payload
  10383. // limit
  10384. SUCCEED() << "Server rejected oversized request without Content-Length "
  10385. "(connection closed)";
  10386. } else {
  10387. // Check if server responded with error or closed connection early
  10388. if (response.length() <= 10) {
  10389. SUCCEED() << "Server closed connection for oversized request without "
  10390. "Content-Length";
  10391. } else {
  10392. // Check for error status codes
  10393. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10394. response.find("Payload Too Large") != std::string::npos ||
  10395. response.find("400") != std::string::npos);
  10396. }
  10397. }
  10398. }
  10399. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10400. // Test request without Content-Length header within payload limit
  10401. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10402. "Host: " +
  10403. std::string(HOST) + ":" +
  10404. std::to_string(PORT) +
  10405. "\r\n"
  10406. "Connection: close\r\n"
  10407. "\r\n";
  10408. // Add payload within the 8-byte limit
  10409. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10410. request_without_content_length += small_payload;
  10411. std::string response;
  10412. bool result = send_request(1, request_without_content_length, &response);
  10413. // For requests without Content-Length, the server may have different behavior
  10414. // The key is that it should not reject due to payload limit for small
  10415. // payloads
  10416. if (result) {
  10417. // Check for any HTTP response (success or error, but not connection closed)
  10418. if (response.length() > 10) {
  10419. SUCCEED()
  10420. << "Server processed request without Content-Length within limit";
  10421. } else {
  10422. // Short response might indicate connection closed, which is acceptable
  10423. SUCCEED() << "Server closed connection for request without "
  10424. "Content-Length (acceptable behavior)";
  10425. }
  10426. } else {
  10427. // Connection failure might be due to protocol requirements
  10428. SUCCEED() << "Connection issue with request without Content-Length "
  10429. "(environment-specific)";
  10430. }
  10431. }
  10432. class LargePayloadMaxLengthTest : public ::testing::Test {
  10433. protected:
  10434. LargePayloadMaxLengthTest()
  10435. : cli_(HOST, PORT)
  10436. #ifdef CPPHTTPLIB_SSL_ENABLED
  10437. ,
  10438. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10439. #endif
  10440. {
  10441. #ifdef CPPHTTPLIB_SSL_ENABLED
  10442. cli_.enable_server_certificate_verification(false);
  10443. #endif
  10444. }
  10445. virtual void SetUp() {
  10446. // Set 10MB payload limit
  10447. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10448. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10449. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10450. res.set_content("Large payload test", "text/plain");
  10451. });
  10452. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10453. svr_.wait_until_ready();
  10454. }
  10455. virtual void TearDown() {
  10456. svr_.stop();
  10457. t_.join();
  10458. }
  10459. #ifdef CPPHTTPLIB_SSL_ENABLED
  10460. SSLClient cli_;
  10461. SSLServer svr_;
  10462. #else
  10463. Client cli_;
  10464. Server svr_;
  10465. #endif
  10466. thread t_;
  10467. };
  10468. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10469. // Test chunked encoding with payload within 10MB limit
  10470. std::string medium_payload(5 * 1024 * 1024,
  10471. 'A'); // 5MB payload, within 10MB limit
  10472. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::OK_200, res->status);
  10475. }
  10476. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10477. // Test chunked encoding with payload exceeding 10MB limit
  10478. std::string large_payload(12 * 1024 * 1024,
  10479. 'B'); // 12MB payload, exceeds 10MB limit
  10480. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10481. // Server may either return 413 or close the connection
  10482. if (res) {
  10483. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10484. } else {
  10485. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10486. }
  10487. }
  10488. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10489. // Test request without Content-Length header within 10MB limit
  10490. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10491. "Host: " +
  10492. std::string(HOST) + ":" +
  10493. std::to_string(PORT) +
  10494. "\r\n"
  10495. "Connection: close\r\n"
  10496. "\r\n";
  10497. // Add 1MB payload (within 10MB limit)
  10498. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10499. request_without_content_length += medium_payload;
  10500. std::string response;
  10501. bool result = send_request(5, request_without_content_length, &response);
  10502. if (result) {
  10503. // Should get a proper HTTP response for payloads within limit
  10504. if (response.length() > 10) {
  10505. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10506. "10MB limit";
  10507. } else {
  10508. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10509. "Content-Length)";
  10510. }
  10511. } else {
  10512. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10513. }
  10514. }
  10515. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10516. // Test request without Content-Length header exceeding 10MB limit
  10517. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10518. "Host: " +
  10519. std::string(HOST) + ":" +
  10520. std::to_string(PORT) +
  10521. "\r\n"
  10522. "Connection: close\r\n"
  10523. "\r\n";
  10524. // Add 12MB payload (exceeds 10MB limit)
  10525. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10526. request_without_content_length += large_payload;
  10527. std::string response;
  10528. bool result = send_request(10, request_without_content_length, &response);
  10529. if (!result) {
  10530. // Server should close connection due to payload limit
  10531. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10532. "(connection closed)";
  10533. } else {
  10534. // Check for error response
  10535. if (response.length() <= 10) {
  10536. SUCCEED()
  10537. << "Server closed connection for 12MB request exceeding 10MB limit";
  10538. } else {
  10539. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10540. response.find("Payload Too Large") != std::string::npos ||
  10541. response.find("400") != std::string::npos);
  10542. }
  10543. }
  10544. }
  10545. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10546. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10547. // path.
  10548. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10549. Server svr;
  10550. const size_t LIMIT = 64 * 1024; // 64KB
  10551. svr.set_payload_max_length(LIMIT);
  10552. size_t total = 0;
  10553. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10554. const ContentReader &content_reader) {
  10555. content_reader([&](const char * /*data*/, size_t len) {
  10556. total += len;
  10557. return true;
  10558. });
  10559. res.status = 200;
  10560. res.set_content("stream_ok", "text/plain");
  10561. });
  10562. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. thread.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. // Prepare 256KB raw data and gzip-compress it
  10570. std::string raw(256 * 1024, 'A');
  10571. std::string gz;
  10572. {
  10573. z_stream zs{};
  10574. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10575. Z_DEFAULT_STRATEGY);
  10576. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10577. zs.avail_in = static_cast<uInt>(raw.size());
  10578. char outbuf[4096];
  10579. int ret;
  10580. do {
  10581. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10582. zs.avail_out = sizeof(outbuf);
  10583. ret = deflate(&zs, Z_FINISH);
  10584. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10585. } while (ret != Z_STREAM_END);
  10586. deflateEnd(&zs);
  10587. }
  10588. Client cli(HOST, PORT);
  10589. cli.set_connection_timeout(std::chrono::seconds(5));
  10590. Headers headers = {{"Content-Encoding", "gzip"}};
  10591. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10592. "application/octet-stream");
  10593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10594. // Server must reject oversized decompressed payloads with 413.
  10595. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10596. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10597. EXPECT_LE(total, LIMIT);
  10598. }
  10599. #ifndef CPPHTTPLIB_SSL_ENABLED
  10600. // For a request with neither Content-Length nor Transfer-Encoding, the
  10601. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10602. // compressed wire bytes straight to the ContentReader without ever routing
  10603. // them through the decompressor, so payload_max_length_ only bounded the
  10604. // compressed size on the wire, not the decompressed size.
  10605. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10606. Server svr;
  10607. const size_t LIMIT = 64 * 1024; // 64KB
  10608. svr.set_payload_max_length(LIMIT);
  10609. size_t total = 0;
  10610. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10611. const ContentReader &content_reader) {
  10612. content_reader([&](const char * /*data*/, size_t len) {
  10613. total += len;
  10614. return true;
  10615. });
  10616. res.status = 200;
  10617. res.set_content("stream_ok", "text/plain");
  10618. });
  10619. auto port = svr.bind_to_any_port(HOST);
  10620. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10621. auto se = detail::scope_exit([&] {
  10622. svr.stop();
  10623. thread.join();
  10624. ASSERT_FALSE(svr.is_running());
  10625. });
  10626. svr.wait_until_ready();
  10627. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10628. // StreamingGzipDecompression test above.
  10629. std::string raw(256 * 1024, 'A');
  10630. std::string gz;
  10631. {
  10632. httplib::detail::gzip_compressor compressor;
  10633. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10634. [&](const char *chunk, size_t len) {
  10635. gz.append(chunk, len);
  10636. return true;
  10637. });
  10638. ASSERT_TRUE(result);
  10639. }
  10640. // Send the gzip body over raw TCP with neither Content-Length nor
  10641. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10642. // kicks in.
  10643. std::string req = "POST /stream HTTP/1.1\r\n"
  10644. "Host: " +
  10645. std::string(HOST) + ":" + std::to_string(port) +
  10646. "\r\n"
  10647. "Content-Encoding: gzip\r\n"
  10648. "Connection: close\r\n"
  10649. "\r\n" +
  10650. gz;
  10651. std::string response;
  10652. ASSERT_TRUE(send_request(5, req, &response, port));
  10653. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10654. EXPECT_LE(total, LIMIT);
  10655. }
  10656. #endif
  10657. #endif
  10658. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10659. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10660. // the payload must be passed through untouched instead of being rejected.
  10661. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10662. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10663. Server svr;
  10664. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10665. res.set_content(body, "image/jpeg");
  10666. res.set_header("Content-Encoding", "UTF-8");
  10667. });
  10668. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10669. res.set_content(body, "image/jpeg");
  10670. res.set_header("Content-Encoding", "identity");
  10671. });
  10672. svr.Post("/echo", [](const Request &req, Response &res) {
  10673. res.set_content(req.body, "image/jpeg");
  10674. });
  10675. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli(HOST, PORT);
  10683. {
  10684. auto res = cli.Get("/image");
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::OK_200, res->status);
  10687. EXPECT_EQ(body, res->body);
  10688. }
  10689. {
  10690. auto res = cli.Get("/identity");
  10691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10692. EXPECT_EQ(StatusCode::OK_200, res->status);
  10693. EXPECT_EQ(body, res->body);
  10694. }
  10695. {
  10696. // The same applies to a request body reaching the server.
  10697. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10698. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10700. EXPECT_EQ(StatusCode::OK_200, res->status);
  10701. EXPECT_EQ(body, res->body);
  10702. }
  10703. }
  10704. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10705. // gzip-encoded response even when the build has no zlib support.
  10706. static const char GZIPPED_HELLO_WORLD[] = {
  10707. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10708. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10709. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10710. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10711. // A content coding is a whole token, not something the field value merely
  10712. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10713. // as "fibre" look like Brotli, and turned a multi-coding value like
  10714. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10715. // it was never meant to see.
  10716. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10717. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10718. Server svr;
  10719. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10720. res.set_content(body, "image/jpeg");
  10721. res.set_header("Content-Encoding", "fibre");
  10722. });
  10723. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10724. res.set_content(body, "image/jpeg");
  10725. res.set_header("Content-Encoding", "gzip, br");
  10726. });
  10727. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10728. res.set_content(body, "image/jpeg");
  10729. res.set_header("Content-Encoding", "x-zstd-ish");
  10730. });
  10731. auto port = svr.bind_to_any_port(HOST);
  10732. thread t = thread([&]() { svr.listen_after_bind(); });
  10733. auto se = detail::scope_exit([&] {
  10734. svr.stop();
  10735. t.join();
  10736. ASSERT_FALSE(svr.is_running());
  10737. });
  10738. svr.wait_until_ready();
  10739. Client cli(HOST, port);
  10740. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10741. auto res = cli.Get(path);
  10742. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10743. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10744. // Not a coding we recognize, so the payload comes back untouched
  10745. EXPECT_EQ(body, res->body) << path;
  10746. }
  10747. }
  10748. // A content coding cpp-httplib recognizes but was not built with must be
  10749. // reported as such. Handing the still-compressed payload back to the caller
  10750. // would silently corrupt it.
  10751. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10752. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10753. Server svr;
  10754. // "image/jpeg" keeps the server from applying a content coding of its own,
  10755. // so the hand-crafted Content-Encoding below survives.
  10756. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10757. res.set_content(gzipped, "image/jpeg");
  10758. res.set_header("Content-Encoding", "gzip");
  10759. });
  10760. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10761. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10762. res.set_content(gzipped, "image/jpeg");
  10763. res.set_header("Content-Encoding", "GZIP");
  10764. });
  10765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10766. auto se = detail::scope_exit([&] {
  10767. svr.stop();
  10768. t.join();
  10769. ASSERT_FALSE(svr.is_running());
  10770. });
  10771. svr.wait_until_ready();
  10772. Client cli(HOST, PORT);
  10773. {
  10774. auto res = cli.Get("/gzipped");
  10775. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10777. EXPECT_EQ("Hello World!", res->body);
  10778. #else
  10779. ASSERT_FALSE(res);
  10780. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10781. #endif
  10782. }
  10783. {
  10784. // open_stream() must behave the same way.
  10785. auto handle = cli.open_stream("GET", "/gzipped");
  10786. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10787. ASSERT_TRUE(handle.is_valid());
  10788. std::string received;
  10789. char buf[256];
  10790. ssize_t n;
  10791. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10792. received.append(buf, static_cast<size_t>(n));
  10793. }
  10794. EXPECT_EQ("Hello World!", received);
  10795. #else
  10796. EXPECT_FALSE(handle.is_valid());
  10797. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10798. #endif
  10799. }
  10800. {
  10801. // A differently-cased coding must not be mistaken for an unknown one, or
  10802. // the body would be handed back still compressed.
  10803. auto res = cli.Get("/gzipped-uppercase");
  10804. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10806. EXPECT_EQ("Hello World!", res->body);
  10807. #else
  10808. ASSERT_FALSE(res);
  10809. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10810. #endif
  10811. }
  10812. }
  10813. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10814. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10815. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10816. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10817. // body a second time and appending a second Content-Encoding field line, so
  10818. // clients that decode one coding per listed value handed back raw gzip bytes.
  10819. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10820. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10821. Server svr;
  10822. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10823. // keeps the server from applying a coding of its own.
  10824. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10825. res.set_content(gzipped, "text/plain");
  10826. res.set_header("Content-Encoding", "gzip");
  10827. });
  10828. auto port = svr.bind_to_any_port(HOST);
  10829. thread t = thread([&]() { svr.listen_after_bind(); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. t.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. Client cli(HOST, port);
  10837. Headers headers = {{"Accept-Encoding", "gzip"}};
  10838. auto res = cli.Get("/pre-gzipped", headers);
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. EXPECT_EQ(StatusCode::OK_200, res->status);
  10841. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10842. EXPECT_EQ("Hello World!", res->body);
  10843. }
  10844. // A chunked provider settles its coding where the headers are written and
  10845. // reuses it at write time. Both ends of that have to hold: a handler's own
  10846. // Content-Encoding suppresses the coding, and a response without one is still
  10847. // compressed as it always was.
  10848. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10849. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10850. const std::string plain = "Hello World! Hello World! Hello World!";
  10851. Server svr;
  10852. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10853. res.set_header("Content-Encoding", "gzip");
  10854. res.set_chunked_content_provider(
  10855. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10856. sink.write(gzipped.data(), gzipped.size());
  10857. sink.done();
  10858. return true;
  10859. });
  10860. });
  10861. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10862. res.set_chunked_content_provider(
  10863. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10864. sink.write(plain.data(), plain.size());
  10865. sink.done();
  10866. return true;
  10867. });
  10868. });
  10869. auto port = svr.bind_to_any_port(HOST);
  10870. thread t = thread([&]() { svr.listen_after_bind(); });
  10871. auto se = detail::scope_exit([&] {
  10872. svr.stop();
  10873. t.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. svr.wait_until_ready();
  10877. Client cli(HOST, port);
  10878. Headers headers = {{"Accept-Encoding", "gzip"}};
  10879. {
  10880. auto res = cli.Get("/pre-gzipped", headers);
  10881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10882. EXPECT_EQ(StatusCode::OK_200, res->status);
  10883. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10884. EXPECT_EQ("Hello World!", res->body);
  10885. }
  10886. {
  10887. auto res = cli.Get("/negotiated", headers);
  10888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10889. EXPECT_EQ(StatusCode::OK_200, res->status);
  10890. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10891. EXPECT_EQ(plain, res->body);
  10892. }
  10893. }
  10894. #endif
  10895. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10896. // the same message as the comma-joined one, so both have to be read the same
  10897. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10898. // single gzip coding, and a body the sender says was encoded twice was handed
  10899. // back after one pass, still compressed but presented as decoded.
  10900. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10901. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10902. Server svr;
  10903. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10904. res.set_content(body, "image/jpeg");
  10905. res.headers.emplace("Content-Encoding", "gzip");
  10906. res.headers.emplace("Content-Encoding", "gzip");
  10907. });
  10908. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10909. res.set_content(body, "image/jpeg");
  10910. res.set_header("Content-Encoding", "gzip, gzip");
  10911. });
  10912. auto port = svr.bind_to_any_port(HOST);
  10913. thread t = thread([&]() { svr.listen_after_bind(); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. t.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. });
  10919. svr.wait_until_ready();
  10920. Client cli(HOST, port);
  10921. // Two codings is not something cpp-httplib decodes, so both representations
  10922. // take the pass-through path rather than one of them being gunzipped once.
  10923. for (const char *path : {"/split", "/joined"}) {
  10924. auto res = cli.Get(path);
  10925. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10926. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10927. EXPECT_EQ(body, res->body) << path;
  10928. }
  10929. }
  10930. // Regression test for DoS vulnerability: a malicious server sending a response
  10931. // without Content-Length header must not cause unbounded memory consumption on
  10932. // the client side. The client should stop reading after a reasonable limit,
  10933. // similar to the server-side set_payload_max_length protection.
  10934. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10935. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10936. #ifndef _WIN32
  10937. signal(SIGPIPE, SIG_IGN);
  10938. #endif
  10939. auto server_thread = std::thread([] {
  10940. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10941. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10942. default_socket_options(srv);
  10943. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10944. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10945. sockaddr_in addr{};
  10946. addr.sin_family = AF_INET;
  10947. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10948. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10949. int opt = 1;
  10950. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10951. #ifdef _WIN32
  10952. reinterpret_cast<const char *>(&opt),
  10953. #else
  10954. &opt,
  10955. #endif
  10956. sizeof(opt));
  10957. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10958. ::listen(srv, 1);
  10959. sockaddr_in cli_addr{};
  10960. socklen_t cli_len = sizeof(cli_addr);
  10961. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10962. if (cli != INVALID_SOCKET) {
  10963. char buf[4096];
  10964. ::recv(cli, buf, sizeof(buf), 0);
  10965. // Malicious response: no Content-Length, no chunked encoding
  10966. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10967. "Connection: close\r\n"
  10968. "\r\n";
  10969. ::send(cli,
  10970. #ifdef _WIN32
  10971. static_cast<const char *>(response_header.c_str()),
  10972. static_cast<int>(response_header.size()),
  10973. #else
  10974. response_header.c_str(), response_header.size(),
  10975. #endif
  10976. 0);
  10977. // Send 10MB of data
  10978. std::string chunk(64 * 1024, 'A');
  10979. size_t total_sent = 0;
  10980. while (total_sent < MALICIOUS_DATA_SIZE) {
  10981. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10982. auto sent = ::send(cli,
  10983. #ifdef _WIN32
  10984. static_cast<const char *>(chunk.c_str()),
  10985. static_cast<int>(to_send),
  10986. #else
  10987. chunk.c_str(), to_send,
  10988. #endif
  10989. 0);
  10990. if (sent <= 0) break;
  10991. total_sent += static_cast<size_t>(sent);
  10992. }
  10993. detail::close_socket(cli);
  10994. }
  10995. detail::close_socket(srv);
  10996. });
  10997. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10998. size_t total_read = 0;
  10999. {
  11000. Client cli("127.0.0.1", PORT + 2);
  11001. cli.set_read_timeout(5, 0);
  11002. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11003. auto stream = cli.open_stream("GET", "/malicious");
  11004. ASSERT_TRUE(stream.is_valid());
  11005. char buffer[64 * 1024];
  11006. ssize_t n;
  11007. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11008. total_read += static_cast<size_t>(n);
  11009. }
  11010. } // StreamHandle and Client destroyed here, closing the socket
  11011. server_thread.join();
  11012. // With set_payload_max_length, the client must stop reading before consuming
  11013. // all 10MB. The read loop should be cut off at or near the configured limit.
  11014. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11015. << "Client read " << total_read << " bytes, exceeding the configured "
  11016. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11017. }
  11018. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11019. // the entire response body without truncation.
  11020. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11021. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11022. #ifndef _WIN32
  11023. signal(SIGPIPE, SIG_IGN);
  11024. #endif
  11025. auto server_thread = std::thread([] {
  11026. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11027. default_socket_options(srv);
  11028. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11029. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11030. sockaddr_in addr{};
  11031. addr.sin_family = AF_INET;
  11032. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11033. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11034. int opt = 1;
  11035. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11036. #ifdef _WIN32
  11037. reinterpret_cast<const char *>(&opt),
  11038. #else
  11039. &opt,
  11040. #endif
  11041. sizeof(opt));
  11042. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11043. ::listen(srv, 1);
  11044. sockaddr_in cli_addr{};
  11045. socklen_t cli_len = sizeof(cli_addr);
  11046. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11047. if (cli != INVALID_SOCKET) {
  11048. char buf[4096];
  11049. ::recv(cli, buf, sizeof(buf), 0);
  11050. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11051. "Connection: close\r\n"
  11052. "\r\n";
  11053. ::send(cli,
  11054. #ifdef _WIN32
  11055. static_cast<const char *>(response_header.c_str()),
  11056. static_cast<int>(response_header.size()),
  11057. #else
  11058. response_header.c_str(), response_header.size(),
  11059. #endif
  11060. 0);
  11061. std::string chunk(64 * 1024, 'A');
  11062. size_t total_sent = 0;
  11063. while (total_sent < DATA_SIZE) {
  11064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11065. auto sent = ::send(cli,
  11066. #ifdef _WIN32
  11067. static_cast<const char *>(chunk.c_str()),
  11068. static_cast<int>(to_send),
  11069. #else
  11070. chunk.c_str(), to_send,
  11071. #endif
  11072. 0);
  11073. if (sent <= 0) break;
  11074. total_sent += static_cast<size_t>(sent);
  11075. }
  11076. #ifdef _WIN32
  11077. ::shutdown(cli, SD_SEND);
  11078. #else
  11079. ::shutdown(cli, SHUT_WR);
  11080. #endif
  11081. // Drain until the client closes its end, ensuring all data is delivered
  11082. char drain[1024];
  11083. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11084. detail::close_socket(cli);
  11085. }
  11086. detail::close_socket(srv);
  11087. });
  11088. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11089. size_t total_read = 0;
  11090. {
  11091. Client cli("127.0.0.1", PORT + 2);
  11092. cli.set_read_timeout(5, 0);
  11093. cli.set_payload_max_length(0); // 0 means no limit
  11094. auto stream = cli.open_stream("GET", "/data");
  11095. ASSERT_TRUE(stream.is_valid());
  11096. char buffer[64 * 1024];
  11097. ssize_t n;
  11098. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11099. total_read += static_cast<size_t>(n);
  11100. }
  11101. }
  11102. server_thread.join();
  11103. EXPECT_EQ(total_read, DATA_SIZE)
  11104. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11105. << " bytes without truncation, but only read " << total_read << " bytes.";
  11106. }
  11107. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11108. // enormous Content-Length must not cause the client to pre-allocate a huge
  11109. // response body buffer. The reservation is capped at payload_max_length_, and
  11110. // the read itself fails when the body exceeds the limit.
  11111. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11112. #ifndef _WIN32
  11113. signal(SIGPIPE, SIG_IGN);
  11114. #endif
  11115. auto server_thread = std::thread([] {
  11116. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11117. default_socket_options(srv);
  11118. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11119. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11120. sockaddr_in addr{};
  11121. addr.sin_family = AF_INET;
  11122. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11123. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11124. int opt = 1;
  11125. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11126. #ifdef _WIN32
  11127. reinterpret_cast<const char *>(&opt),
  11128. #else
  11129. &opt,
  11130. #endif
  11131. sizeof(opt));
  11132. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11133. ::listen(srv, 1);
  11134. sockaddr_in cli_addr{};
  11135. socklen_t cli_len = sizeof(cli_addr);
  11136. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11137. if (cli != INVALID_SOCKET) {
  11138. char buf[4096];
  11139. ::recv(cli, buf, sizeof(buf), 0);
  11140. // Malicious response: claim a 20GB body but send only a tiny payload.
  11141. std::string response = "HTTP/1.1 200 OK\r\n"
  11142. "Content-Length: 20000000000\r\n"
  11143. "\r\n"
  11144. "abc";
  11145. ::send(cli,
  11146. #ifdef _WIN32
  11147. static_cast<const char *>(response.c_str()),
  11148. static_cast<int>(response.size()),
  11149. #else
  11150. response.c_str(), response.size(),
  11151. #endif
  11152. 0);
  11153. detail::close_socket(cli);
  11154. }
  11155. detail::close_socket(srv);
  11156. });
  11157. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11158. {
  11159. Client cli("127.0.0.1", PORT + 2);
  11160. cli.set_read_timeout(5, 0);
  11161. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11162. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11163. // (server claims more bytes than payload_max_length permits), but it must
  11164. // not exhaust memory before getting there.
  11165. auto res = cli.Get("/malicious");
  11166. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11167. }
  11168. server_thread.join();
  11169. }
  11170. // Verify that content_receiver bypasses the default payload_max_length,
  11171. // allowing streaming downloads larger than 100MB without requiring an explicit
  11172. // set_payload_max_length call.
  11173. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11174. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11175. #ifndef _WIN32
  11176. signal(SIGPIPE, SIG_IGN);
  11177. #endif
  11178. auto server_thread = std::thread([] {
  11179. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11180. default_socket_options(srv);
  11181. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11182. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11183. sockaddr_in addr{};
  11184. addr.sin_family = AF_INET;
  11185. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11186. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11187. int opt = 1;
  11188. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11189. #ifdef _WIN32
  11190. reinterpret_cast<const char *>(&opt),
  11191. #else
  11192. &opt,
  11193. #endif
  11194. sizeof(opt));
  11195. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11196. ::listen(srv, 1);
  11197. sockaddr_in cli_addr{};
  11198. socklen_t cli_len = sizeof(cli_addr);
  11199. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11200. if (cli != INVALID_SOCKET) {
  11201. char buf[4096];
  11202. ::recv(cli, buf, sizeof(buf), 0);
  11203. // Response with Content-Length larger than default 100MB limit
  11204. auto content_length = std::to_string(DATA_SIZE);
  11205. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11206. "Content-Length: " +
  11207. content_length +
  11208. "\r\n"
  11209. "Connection: close\r\n"
  11210. "\r\n";
  11211. ::send(cli,
  11212. #ifdef _WIN32
  11213. static_cast<const char *>(response_header.c_str()),
  11214. static_cast<int>(response_header.size()),
  11215. #else
  11216. response_header.c_str(), response_header.size(),
  11217. #endif
  11218. 0);
  11219. std::string chunk(64 * 1024, 'A');
  11220. size_t total_sent = 0;
  11221. while (total_sent < DATA_SIZE) {
  11222. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11223. auto sent = ::send(cli,
  11224. #ifdef _WIN32
  11225. static_cast<const char *>(chunk.c_str()),
  11226. static_cast<int>(to_send),
  11227. #else
  11228. chunk.c_str(), to_send,
  11229. #endif
  11230. 0);
  11231. if (sent <= 0) break;
  11232. total_sent += static_cast<size_t>(sent);
  11233. }
  11234. detail::close_socket(cli);
  11235. }
  11236. detail::close_socket(srv);
  11237. });
  11238. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11239. size_t total_received = 0;
  11240. {
  11241. Client cli("127.0.0.1", PORT + 2);
  11242. cli.set_read_timeout(10, 0);
  11243. // Do NOT call set_payload_max_length — use the default 100MB limit
  11244. auto res =
  11245. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11246. total_received += data_length;
  11247. return true;
  11248. });
  11249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11250. EXPECT_EQ(StatusCode::OK_200, res->status);
  11251. }
  11252. server_thread.join();
  11253. EXPECT_EQ(total_received, DATA_SIZE)
  11254. << "With content_receiver, the client should read all " << DATA_SIZE
  11255. << " bytes despite the default 100MB payload_max_length, but only read "
  11256. << total_received << " bytes.";
  11257. }
  11258. // Verify that an explicit set_payload_max_length smaller than the response is
  11259. // enforced even when a content_receiver is used.
  11260. TEST(ClientVulnerabilityTest,
  11261. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11262. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11263. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11264. #ifndef _WIN32
  11265. signal(SIGPIPE, SIG_IGN);
  11266. #endif
  11267. auto server_thread = std::thread([] {
  11268. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11269. default_socket_options(srv);
  11270. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11271. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11272. sockaddr_in addr{};
  11273. addr.sin_family = AF_INET;
  11274. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11275. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11276. int opt = 1;
  11277. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11278. #ifdef _WIN32
  11279. reinterpret_cast<const char *>(&opt),
  11280. #else
  11281. &opt,
  11282. #endif
  11283. sizeof(opt));
  11284. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11285. ::listen(srv, 1);
  11286. sockaddr_in cli_addr{};
  11287. socklen_t cli_len = sizeof(cli_addr);
  11288. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11289. if (cli != INVALID_SOCKET) {
  11290. char buf[4096];
  11291. ::recv(cli, buf, sizeof(buf), 0);
  11292. auto content_length = std::to_string(DATA_SIZE);
  11293. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11294. "Content-Length: " +
  11295. content_length +
  11296. "\r\n"
  11297. "Connection: close\r\n"
  11298. "\r\n";
  11299. ::send(cli,
  11300. #ifdef _WIN32
  11301. static_cast<const char *>(response_header.c_str()),
  11302. static_cast<int>(response_header.size()),
  11303. #else
  11304. response_header.c_str(), response_header.size(),
  11305. #endif
  11306. 0);
  11307. std::string chunk(64 * 1024, 'A');
  11308. size_t total_sent = 0;
  11309. while (total_sent < DATA_SIZE) {
  11310. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11311. auto sent = ::send(cli,
  11312. #ifdef _WIN32
  11313. static_cast<const char *>(chunk.c_str()),
  11314. static_cast<int>(to_send),
  11315. #else
  11316. chunk.c_str(), to_send,
  11317. #endif
  11318. 0);
  11319. if (sent <= 0) break;
  11320. total_sent += static_cast<size_t>(sent);
  11321. }
  11322. detail::close_socket(cli);
  11323. }
  11324. detail::close_socket(srv);
  11325. });
  11326. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11327. size_t total_received = 0;
  11328. {
  11329. Client cli("127.0.0.1", PORT + 2);
  11330. cli.set_read_timeout(10, 0);
  11331. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11332. auto res =
  11333. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11334. total_received += data_length;
  11335. return true;
  11336. });
  11337. // Should fail because 200MB exceeds the explicit 150MB limit
  11338. EXPECT_FALSE(res);
  11339. }
  11340. server_thread.join();
  11341. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11342. << "Client with content_receiver should respect the explicit "
  11343. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11344. << total_received << " bytes.";
  11345. }
  11346. // Verify that an explicit set_payload_max_length larger than the response
  11347. // allows the content_receiver to read all data successfully.
  11348. TEST(ClientVulnerabilityTest,
  11349. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11350. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11351. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11352. #ifndef _WIN32
  11353. signal(SIGPIPE, SIG_IGN);
  11354. #endif
  11355. auto server_thread = std::thread([] {
  11356. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11357. default_socket_options(srv);
  11358. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11359. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11360. sockaddr_in addr{};
  11361. addr.sin_family = AF_INET;
  11362. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11363. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11364. int opt = 1;
  11365. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11366. #ifdef _WIN32
  11367. reinterpret_cast<const char *>(&opt),
  11368. #else
  11369. &opt,
  11370. #endif
  11371. sizeof(opt));
  11372. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11373. ::listen(srv, 1);
  11374. sockaddr_in cli_addr{};
  11375. socklen_t cli_len = sizeof(cli_addr);
  11376. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11377. if (cli != INVALID_SOCKET) {
  11378. char buf[4096];
  11379. ::recv(cli, buf, sizeof(buf), 0);
  11380. auto content_length = std::to_string(DATA_SIZE);
  11381. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11382. "Content-Length: " +
  11383. content_length +
  11384. "\r\n"
  11385. "Connection: close\r\n"
  11386. "\r\n";
  11387. ::send(cli,
  11388. #ifdef _WIN32
  11389. static_cast<const char *>(response_header.c_str()),
  11390. static_cast<int>(response_header.size()),
  11391. #else
  11392. response_header.c_str(), response_header.size(),
  11393. #endif
  11394. 0);
  11395. std::string chunk(64 * 1024, 'A');
  11396. size_t total_sent = 0;
  11397. while (total_sent < DATA_SIZE) {
  11398. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11399. auto sent = ::send(cli,
  11400. #ifdef _WIN32
  11401. static_cast<const char *>(chunk.c_str()),
  11402. static_cast<int>(to_send),
  11403. #else
  11404. chunk.c_str(), to_send,
  11405. #endif
  11406. 0);
  11407. if (sent <= 0) break;
  11408. total_sent += static_cast<size_t>(sent);
  11409. }
  11410. #ifdef _WIN32
  11411. ::shutdown(cli, SD_SEND);
  11412. #else
  11413. ::shutdown(cli, SHUT_WR);
  11414. #endif
  11415. char drain[1024];
  11416. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11417. detail::close_socket(cli);
  11418. }
  11419. detail::close_socket(srv);
  11420. });
  11421. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11422. size_t total_received = 0;
  11423. {
  11424. Client cli("127.0.0.1", PORT + 2);
  11425. cli.set_read_timeout(10, 0);
  11426. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11427. auto res =
  11428. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11429. total_received += data_length;
  11430. return true;
  11431. });
  11432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11433. EXPECT_EQ(StatusCode::OK_200, res->status);
  11434. }
  11435. server_thread.join();
  11436. EXPECT_EQ(total_received, DATA_SIZE)
  11437. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11438. << " bytes (larger than " << DATA_SIZE
  11439. << " bytes response), content_receiver should read all data, but only "
  11440. "read "
  11441. << total_received << " bytes.";
  11442. }
  11443. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11444. // Regression test for "zip bomb" attack on the client side: a malicious server
  11445. // sends a small gzip-compressed response that decompresses to a huge payload.
  11446. // The client must enforce payload_max_length on the decompressed size.
  11447. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11448. constexpr size_t DECOMPRESSED_SIZE =
  11449. 10 * 1024 * 1024; // 10MB after decompression
  11450. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11451. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11452. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11453. std::string compressed;
  11454. {
  11455. httplib::detail::gzip_compressor compressor;
  11456. bool ok =
  11457. compressor.compress(uncompressed.data(), uncompressed.size(),
  11458. /*last=*/true, [&](const char *buf, size_t len) {
  11459. compressed.append(buf, len);
  11460. return true;
  11461. });
  11462. ASSERT_TRUE(ok);
  11463. }
  11464. // Sanity: compressed data should be much smaller than the decompressed size
  11465. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11466. #ifndef _WIN32
  11467. signal(SIGPIPE, SIG_IGN);
  11468. #endif
  11469. // Set up the listening socket in the main thread so the server is guaranteed
  11470. // to be ready before the client connects (eliminates race condition).
  11471. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11472. default_socket_options(srv);
  11473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11474. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11475. sockaddr_in addr{};
  11476. addr.sin_family = AF_INET;
  11477. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11478. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11479. int opt = 1;
  11480. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11481. #ifdef _WIN32
  11482. reinterpret_cast<const char *>(&opt),
  11483. #else
  11484. &opt,
  11485. #endif
  11486. sizeof(opt));
  11487. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11488. ASSERT_EQ(0, ::listen(srv, 1));
  11489. auto server_thread = std::thread([&compressed, srv] {
  11490. sockaddr_in cli_addr{};
  11491. socklen_t cli_len = sizeof(cli_addr);
  11492. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11493. if (cli != INVALID_SOCKET) {
  11494. // Read the full HTTP request (until \r\n\r\n)
  11495. char buf[4096];
  11496. size_t total = 0;
  11497. while (total < sizeof(buf)) {
  11498. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11499. if (n <= 0) break;
  11500. total += static_cast<size_t>(n);
  11501. // Check for end of headers
  11502. if (total >= 4) {
  11503. std::string req(buf, total);
  11504. if (req.find("\r\n\r\n") != std::string::npos) break;
  11505. }
  11506. }
  11507. // Malicious response: gzip-compressed body, no Content-Length
  11508. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11509. "Content-Encoding: gzip\r\n"
  11510. "Connection: close\r\n"
  11511. "\r\n";
  11512. ::send(cli,
  11513. #ifdef _WIN32
  11514. static_cast<const char *>(response_header.c_str()),
  11515. static_cast<int>(response_header.size()),
  11516. #else
  11517. response_header.c_str(), response_header.size(),
  11518. #endif
  11519. 0);
  11520. // Send the compressed payload (small on the wire, huge when decompressed)
  11521. size_t total_sent = 0;
  11522. while (total_sent < compressed.size()) {
  11523. auto to_send = std::min(compressed.size() - total_sent,
  11524. static_cast<size_t>(64 * 1024));
  11525. auto sent =
  11526. ::send(cli,
  11527. #ifdef _WIN32
  11528. static_cast<const char *>(compressed.c_str() + total_sent),
  11529. static_cast<int>(to_send),
  11530. #else
  11531. compressed.c_str() + total_sent, to_send,
  11532. #endif
  11533. 0);
  11534. if (sent <= 0) break;
  11535. total_sent += static_cast<size_t>(sent);
  11536. }
  11537. detail::close_socket(cli);
  11538. }
  11539. });
  11540. auto se = detail::scope_exit([&] {
  11541. detail::close_socket(srv);
  11542. server_thread.join();
  11543. });
  11544. size_t total_decompressed = 0;
  11545. {
  11546. Client cli("127.0.0.1", PORT + 3);
  11547. cli.set_read_timeout(5, 0);
  11548. cli.set_decompress(true);
  11549. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11550. auto stream = cli.open_stream("GET", "/zipbomb");
  11551. ASSERT_TRUE(stream.is_valid());
  11552. char buffer[64 * 1024];
  11553. ssize_t n;
  11554. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11555. total_decompressed += static_cast<size_t>(n);
  11556. }
  11557. }
  11558. // The decompressed size must be capped by payload_max_length. Without
  11559. // protection, the client would decompress the full 10MB from a tiny
  11560. // compressed payload, enabling a zip bomb DoS attack.
  11561. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11562. << "Client decompressed " << total_decompressed
  11563. << " bytes from a gzip response. The decompressed size should be "
  11564. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11565. }
  11566. #endif
  11567. TEST(HostAndPortPropertiesTest, NoSSL) {
  11568. httplib::Client cli("www.google.com", 1234);
  11569. ASSERT_EQ("www.google.com", cli.host());
  11570. ASSERT_EQ(1234, cli.port());
  11571. }
  11572. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11573. httplib::Client cli("www.google.com:1234");
  11574. ASSERT_EQ("www.google.com", cli.host());
  11575. ASSERT_EQ(1234, cli.port());
  11576. }
  11577. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11578. // Port number that overflows int — should not crash, client becomes invalid
  11579. httplib::Client cli("http://www.google.com:99999999999999999999");
  11580. ASSERT_FALSE(cli.is_valid());
  11581. }
  11582. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11583. // Port 99999 exceeds valid range (1-65535) — should not crash
  11584. httplib::Client cli("http://www.google.com:99999");
  11585. ASSERT_FALSE(cli.is_valid());
  11586. }
  11587. #ifdef CPPHTTPLIB_SSL_ENABLED
  11588. TEST(HostAndPortPropertiesTest, SSL) {
  11589. httplib::SSLClient cli("www.google.com");
  11590. ASSERT_EQ("www.google.com", cli.host());
  11591. ASSERT_EQ(443, cli.port());
  11592. }
  11593. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11594. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11595. std::string cert;
  11596. read_file(CA_CERT_FILE, cert);
  11597. httplib::SSLClient httplib_client("www.google.com");
  11598. // Load CA store first time
  11599. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11600. // Load CA store second time (update)
  11601. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11602. // Verify client is still valid and can make connections
  11603. httplib_client.enable_server_certificate_verification(true);
  11604. auto res = httplib_client.Get("/");
  11605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11606. // Google may return 200 or 301 depending on various factors
  11607. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11608. res->status == StatusCode::MovedPermanently_301);
  11609. }
  11610. TEST(SSLClientTest, ServerNameIndication_Online) {
  11611. auto host = "httpbingo.org";
  11612. auto path = std::string{"/get"};
  11613. SSLClient cli(host, 443);
  11614. auto res = cli.Get(path);
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. ASSERT_EQ(StatusCode::OK_200, res->status);
  11617. }
  11618. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11619. // Use a site that will cause SSL verification failure due to self-signed cert
  11620. SSLClient cli("self-signed.badssl.com", 443);
  11621. cli.enable_server_certificate_verification(true);
  11622. auto res = cli.Get("/");
  11623. ASSERT_TRUE(!res);
  11624. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11625. // Verify backend error is captured for SSLServerVerification
  11626. // This occurs when certificate verification fails
  11627. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11628. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11629. EXPECT_NE(0UL, res.ssl_backend_error());
  11630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11631. // For OpenSSL, ssl_error is 0 for verification errors
  11632. EXPECT_EQ(0, res.ssl_error());
  11633. #if !defined(_WIN32) || \
  11634. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11635. // On non-Windows or when Windows Schannel is disabled, the error comes
  11636. // from OpenSSL's verification
  11637. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11638. res.ssl_backend_error());
  11639. #endif
  11640. #endif
  11641. }
  11642. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11643. // Use a site where hostname doesn't match the certificate
  11644. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11645. SSLClient cli("wrong.host.badssl.com", 443);
  11646. cli.enable_server_certificate_verification(true);
  11647. cli.enable_server_hostname_verification(true);
  11648. auto res = cli.Get("/");
  11649. ASSERT_TRUE(!res);
  11650. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11651. // Verify backend error is captured for hostname verification failure
  11652. EXPECT_NE(0UL, res.ssl_backend_error());
  11653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11654. // For OpenSSL, ssl_error is 0 for verification errors
  11655. EXPECT_EQ(0, res.ssl_error());
  11656. #if !defined(_WIN32) || \
  11657. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11658. // On non-Windows or when Windows Schannel is disabled, the error comes
  11659. // from OpenSSL's hostname verification
  11660. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11661. res.ssl_backend_error());
  11662. #endif
  11663. #endif
  11664. }
  11665. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11666. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11667. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11668. SSLClient cli("www.google.com", 443);
  11669. cli.enable_server_certificate_verification(true);
  11670. auto res = cli.Get("/");
  11671. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11672. }
  11673. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11674. SSLClient cli("www.google.com", 443);
  11675. cli.enable_server_certificate_verification(true);
  11676. cli.enable_windows_certificate_verification(false);
  11677. auto res = cli.Get("/");
  11678. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11679. }
  11680. #endif
  11681. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11682. Client cli("https://google.com");
  11683. auto res = cli.Get("/");
  11684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11685. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11686. }
  11687. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11688. SSLClient cli("google.com");
  11689. cli.set_ca_cert_path(CA_CERT_FILE);
  11690. auto res = cli.Get("/");
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11693. }
  11694. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11695. SSLClient cli("google.com");
  11696. cli.enable_server_certificate_verification(true);
  11697. cli.set_ca_cert_path("hello");
  11698. auto res = cli.Get("/");
  11699. ASSERT_TRUE(!res);
  11700. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11701. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11702. // should be set
  11703. EXPECT_EQ(0, res.ssl_error());
  11704. // Verify backend error is captured for SSLLoadingCerts
  11705. // This error occurs when loading CA certificates fails
  11706. EXPECT_NE(0UL, res.ssl_backend_error());
  11707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11708. // OpenSSL specific error codes:
  11709. // > openssl errstr 0x80000002
  11710. // error:80000002:system library::No such file or directory
  11711. // > openssl errstr 0xA000126
  11712. // error:0A000126:SSL routines::unexpected eof while reading
  11713. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11714. res.ssl_backend_error() == 0xA000126);
  11715. #endif
  11716. }
  11717. TEST(SSLClientTest, ServerCertificateVerification4) {
  11718. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11719. ASSERT_TRUE(svr.is_valid());
  11720. svr.Get("/test", [&](const Request &, Response &res) {
  11721. res.set_content("test", "text/plain");
  11722. svr.stop();
  11723. ASSERT_TRUE(true);
  11724. });
  11725. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11726. auto se = detail::scope_exit([&] {
  11727. t.join();
  11728. ASSERT_FALSE(svr.is_running());
  11729. });
  11730. svr.wait_until_ready();
  11731. SSLClient cli("127.0.0.1", PORT);
  11732. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11733. cli.enable_server_certificate_verification(true);
  11734. cli.set_connection_timeout(30);
  11735. auto res = cli.Get("/test");
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. ASSERT_EQ(StatusCode::OK_200, res->status);
  11738. }
  11739. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11740. std::string cert;
  11741. read_file(CA_CERT_FILE, cert);
  11742. SSLClient cli("google.com");
  11743. cli.load_ca_cert_store(cert.data(), cert.size());
  11744. const auto res = cli.Get("/");
  11745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11747. }
  11748. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11749. // clang-format off
  11750. static constexpr char cert[] =
  11751. "GlobalSign Root CA\n"
  11752. "==================\n"
  11753. "-----BEGIN CERTIFICATE-----\n"
  11754. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11755. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11756. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11757. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11758. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11759. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11760. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11761. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11762. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11763. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11764. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11765. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11766. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11767. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11768. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11769. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11770. "-----END CERTIFICATE-----\n";
  11771. // clang-format on
  11772. SSLClient cli("google.com");
  11773. cli.load_ca_cert_store(cert, sizeof(cert));
  11774. const auto res = cli.Get("/");
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11777. }
  11778. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11779. SSLClient cli("www.youtube.com");
  11780. cli.set_ca_cert_path(CA_CERT_FILE);
  11781. cli.enable_server_certificate_verification(true);
  11782. cli.set_follow_location(true);
  11783. auto res = cli.Get("/");
  11784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11785. ASSERT_EQ(StatusCode::OK_200, res->status);
  11786. }
  11787. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11788. SSLClient cli("wWw.YouTube.Com");
  11789. cli.set_ca_cert_path(CA_CERT_FILE);
  11790. cli.enable_server_certificate_verification(true);
  11791. cli.enable_server_hostname_verification(true);
  11792. cli.set_follow_location(true);
  11793. auto res = cli.Get("/");
  11794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11795. ASSERT_EQ(StatusCode::OK_200, res->status);
  11796. }
  11797. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11798. SSLClient cli("gOoGlE.COm");
  11799. cli.enable_server_certificate_verification(true);
  11800. cli.enable_server_hostname_verification(true);
  11801. cli.set_follow_location(true);
  11802. auto res = cli.Get("/");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. ASSERT_EQ(StatusCode::OK_200, res->status);
  11805. }
  11806. TEST(SSLClientTest, Issue2004_Online) {
  11807. Client client("https://google.com");
  11808. client.set_follow_location(true);
  11809. auto res = client.Get("/");
  11810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11811. ASSERT_EQ(StatusCode::OK_200, res->status);
  11812. auto body = res->body;
  11813. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11814. }
  11815. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11816. // Create SSLClient with invalid cert/key to make is_valid() return false
  11817. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11818. "nonexistent_key.pem");
  11819. // is_valid() should be false due to cert loading failure
  11820. ASSERT_FALSE(cli.is_valid());
  11821. auto res = cli.Get("/");
  11822. ASSERT_FALSE(res);
  11823. EXPECT_EQ(Error::SSLConnection, res.error());
  11824. }
  11825. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11826. // Test for Issue #2251: SSL error not properly reported when client cert
  11827. // and key paths are swapped or mismatched
  11828. // This simulates the scenario where user accidentally swaps the cert and key
  11829. // files
  11830. // Using client cert file as private key and vice versa (completely wrong)
  11831. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11832. // Should fail validation due to cert/key mismatch
  11833. ASSERT_FALSE(cli.is_valid());
  11834. // Attempt to make a request should fail with proper error
  11835. auto res = cli.Get("/");
  11836. ASSERT_FALSE(res);
  11837. EXPECT_EQ(Error::SSLConnection, res.error());
  11838. // SSL error should be recorded in the Result object (this is the key fix for
  11839. // Issue #2251)
  11840. auto backend_error = res.ssl_backend_error();
  11841. EXPECT_NE(0u, backend_error);
  11842. }
  11843. // Tests cert/key mismatch detection at the TLS context level
  11844. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11845. // Test that using mismatched cert/key causes connection failure.
  11846. // We verify this at the SSLClient level rather than through internal
  11847. // TLS API functions.
  11848. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11849. cli.enable_server_certificate_verification(false);
  11850. cli.set_connection_timeout(2);
  11851. // The mismatch should cause a connection or handshake error
  11852. auto res = cli.Get("/test");
  11853. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11854. // Either way, the request should fail
  11855. EXPECT_FALSE(res);
  11856. }
  11857. #endif
  11858. #if 0
  11859. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11860. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11861. ASSERT_TRUE(cli != nullptr);
  11862. cli->set_address_family(AF_INET6);
  11863. cli->set_interface("en0");
  11864. auto res = cli->Get("/get");
  11865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11866. ASSERT_EQ(StatusCode::OK_200, res->status);
  11867. }
  11868. #endif
  11869. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11870. #ifdef CPPHTTPLIB_SSL_ENABLED
  11871. void ClientCertPresent(
  11872. const std::string &client_cert_file,
  11873. const std::string &client_private_key_file,
  11874. const std::string &client_encrypted_private_key_pass = std::string()) {
  11875. using namespace httplib::tls;
  11876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11877. CLIENT_CA_CERT_DIR);
  11878. ASSERT_TRUE(svr.is_valid());
  11879. svr.Get("/test", [&](const Request &req, Response &res) {
  11880. res.set_content("test", "text/plain");
  11881. auto cert = req.peer_cert();
  11882. ASSERT_TRUE(static_cast<bool>(cert));
  11883. std::string common_name = cert.subject_cn();
  11884. EXPECT_EQ("Common Name", common_name);
  11885. });
  11886. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11887. auto se = detail::scope_exit([&] {
  11888. svr.stop();
  11889. t.join();
  11890. ASSERT_FALSE(svr.is_running());
  11891. });
  11892. svr.wait_until_ready();
  11893. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11894. client_encrypted_private_key_pass);
  11895. cli.enable_server_certificate_verification(false);
  11896. cli.set_connection_timeout(30);
  11897. auto res = cli.Get("/test");
  11898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11899. ASSERT_EQ(StatusCode::OK_200, res->status);
  11900. }
  11901. TEST(SSLClientServerTest, ClientCertPresent) {
  11902. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11903. }
  11904. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11905. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11906. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11907. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11908. }
  11909. // PEM memory-based constructor tests (works with all TLS backends)
  11910. void PemMemoryClientCertPresent(
  11911. const std::string &client_cert_file,
  11912. const std::string &client_private_key_file,
  11913. const std::string &client_encrypted_private_key_pass = std::string()) {
  11914. // Read PEM files into memory
  11915. std::string server_cert_pem, server_key_pem;
  11916. std::string client_ca_pem;
  11917. std::string client_cert_pem, client_key_pem;
  11918. read_file(SERVER_CERT_FILE, server_cert_pem);
  11919. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11920. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11921. read_file(client_cert_file, client_cert_pem);
  11922. read_file(client_private_key_file, client_key_pem);
  11923. // Create server with PEM memory
  11924. SSLServer::PemMemory server_pem = {
  11925. server_cert_pem.c_str(),
  11926. server_cert_pem.size(),
  11927. server_key_pem.c_str(),
  11928. server_key_pem.size(),
  11929. client_ca_pem.c_str(),
  11930. client_ca_pem.size(),
  11931. nullptr // no password for server key
  11932. };
  11933. SSLServer svr(server_pem);
  11934. ASSERT_TRUE(svr.is_valid());
  11935. svr.Get("/test", [&](const Request &, Response &res) {
  11936. res.set_content("test", "text/plain");
  11937. });
  11938. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11939. auto se = detail::scope_exit([&] {
  11940. svr.stop();
  11941. t.join();
  11942. ASSERT_FALSE(svr.is_running());
  11943. });
  11944. svr.wait_until_ready();
  11945. // Create client with PEM memory
  11946. const char *password = client_encrypted_private_key_pass.empty()
  11947. ? nullptr
  11948. : client_encrypted_private_key_pass.c_str();
  11949. SSLClient::PemMemory client_pem = {
  11950. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11951. client_key_pem.size(), password};
  11952. SSLClient cli(HOST, PORT, client_pem);
  11953. cli.enable_server_certificate_verification(false);
  11954. cli.set_connection_timeout(30);
  11955. auto res = cli.Get("/test");
  11956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11957. ASSERT_EQ(StatusCode::OK_200, res->status);
  11958. }
  11959. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11960. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11961. }
  11962. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11963. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11964. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11965. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11966. }
  11967. TEST(SSLClientServerTest, ClientCertMissing) {
  11968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11969. CLIENT_CA_CERT_DIR);
  11970. ASSERT_TRUE(svr.is_valid());
  11971. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11972. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11973. auto se = detail::scope_exit([&] {
  11974. svr.stop();
  11975. t.join();
  11976. ASSERT_FALSE(svr.is_running());
  11977. });
  11978. svr.wait_until_ready();
  11979. SSLClient cli(HOST, PORT);
  11980. cli.set_connection_timeout(30);
  11981. auto res = cli.Get("/test");
  11982. ASSERT_TRUE(!res);
  11983. // When client cert is missing and server requires it, connection fails
  11984. // Error type depends on backend implementation
  11985. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11986. res.error() == Error::SSLConnection);
  11987. // Verify backend error is captured
  11988. // Note: This test may have different error codes depending on the exact
  11989. // verification failure
  11990. EXPECT_NE(0UL, res.ssl_backend_error());
  11991. }
  11992. TEST(SSLClientServerTest, TrustDirOptional) {
  11993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11994. ASSERT_TRUE(svr.is_valid());
  11995. svr.Get("/test", [&](const Request &, Response &res) {
  11996. res.set_content("test", "text/plain");
  11997. });
  11998. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11999. auto se = detail::scope_exit([&] {
  12000. svr.stop();
  12001. t.join();
  12002. ASSERT_FALSE(svr.is_running());
  12003. });
  12004. svr.wait_until_ready();
  12005. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12006. cli.enable_server_certificate_verification(false);
  12007. cli.set_connection_timeout(30);
  12008. auto res = cli.Get("/test");
  12009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12010. ASSERT_EQ(StatusCode::OK_200, res->status);
  12011. }
  12012. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12013. class NoListenSSLServer : public SSLServer {
  12014. public:
  12015. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12016. const char *client_ca_cert_file_path,
  12017. const char *client_ca_cert_dir_path = nullptr)
  12018. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12019. client_ca_cert_dir_path),
  12020. stop_(false) {}
  12021. std::atomic_bool stop_;
  12022. private:
  12023. bool process_and_close_socket(socket_t /*sock*/) override {
  12024. // Don't create SSL context
  12025. while (!stop_.load()) {
  12026. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12027. }
  12028. return true;
  12029. }
  12030. };
  12031. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12032. CLIENT_CA_CERT_FILE);
  12033. ASSERT_TRUE(svr.is_valid());
  12034. svr.Get("/test", [&](const Request &, Response &res) {
  12035. res.set_content("test", "text/plain");
  12036. });
  12037. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12038. auto se = detail::scope_exit([&] {
  12039. svr.stop_ = true;
  12040. svr.stop();
  12041. t.join();
  12042. ASSERT_FALSE(svr.is_running());
  12043. });
  12044. svr.wait_until_ready();
  12045. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12046. cli.enable_server_certificate_verification(false);
  12047. cli.set_connection_timeout(1);
  12048. auto res = cli.Get("/test");
  12049. ASSERT_TRUE(!res);
  12050. EXPECT_EQ(Error::SSLConnection, res.error());
  12051. // Timeout results in WantRead error code (maps to backend-specific value)
  12052. EXPECT_NE(0, res.ssl_error());
  12053. }
  12054. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12055. // Test SSLServer with client certificate verification using the standard
  12056. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12058. CLIENT_CA_CERT_DIR);
  12059. ASSERT_TRUE(svr.is_valid());
  12060. svr.Get("/test", [&](const Request &req, Response &res) {
  12061. res.set_content("test", "text/plain");
  12062. auto cert = req.peer_cert();
  12063. ASSERT_TRUE(static_cast<bool>(cert));
  12064. auto common_name = cert.subject_cn();
  12065. EXPECT_EQ("Common Name", common_name);
  12066. });
  12067. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12068. auto se = detail::scope_exit([&] {
  12069. svr.stop();
  12070. t.join();
  12071. ASSERT_FALSE(svr.is_running());
  12072. });
  12073. svr.wait_until_ready();
  12074. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12075. cli.enable_server_certificate_verification(false);
  12076. cli.set_connection_timeout(30);
  12077. auto res = cli.Get("/test");
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. ASSERT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12082. // Verifies that wildcard matching and exact matching work consistently
  12083. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12084. using namespace httplib::tls;
  12085. // We need a running server to test against
  12086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12087. ASSERT_TRUE(svr.is_valid());
  12088. svr.Get("/test", [](const Request &, Response &res) {
  12089. res.set_content("ok", "text/plain");
  12090. });
  12091. thread t([&]() { svr.listen(HOST, PORT); });
  12092. auto se = detail::scope_exit([&] {
  12093. svr.stop();
  12094. t.join();
  12095. });
  12096. svr.wait_until_ready();
  12097. bool verify_callback_called = false;
  12098. bool verify_result_wrong = false;
  12099. SSLClient cli(HOST, PORT);
  12100. cli.enable_server_certificate_verification(true);
  12101. cli.set_ca_cert_path(CA_CERT_FILE);
  12102. cli.set_connection_timeout(5);
  12103. // Note: Test certificate has CN="Common Name", not "localhost"
  12104. bool verify_result_cn = false;
  12105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12106. verify_callback_called = true;
  12107. if (!ctx.cert) return false;
  12108. // Test 1: "Common Name" should match (our test server cert CN)
  12109. verify_result_cn = ctx.check_hostname("Common Name");
  12110. // Test 2: wrong hostname should not match
  12111. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12112. return true; // Accept for the purpose of this test
  12113. });
  12114. auto res = cli.Get("/test");
  12115. // The request may succeed or fail depending on cert configuration
  12116. // but the callback should have been called
  12117. ASSERT_TRUE(verify_callback_called)
  12118. << "Verify callback should have been called";
  12119. // CN="Common Name" should match our test certificate
  12120. //
  12121. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12122. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12123. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12124. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12125. // <openssl/base.h>, which is included transitively when
  12126. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12127. #if defined(OPENSSL_IS_BORINGSSL)
  12128. EXPECT_FALSE(verify_result_cn)
  12129. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12130. #else
  12131. EXPECT_TRUE(verify_result_cn)
  12132. << "verify_hostname should match 'Common Name' (certificate CN)";
  12133. #endif
  12134. // Wrong hostname should not match
  12135. EXPECT_FALSE(verify_result_wrong)
  12136. << "verify_hostname should not match 'wronghost.example.com'";
  12137. }
  12138. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12139. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12140. // X509_check_ip behavior and must hold for every backend.
  12141. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12142. using namespace httplib::tls;
  12143. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12144. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12145. ASSERT_TRUE(svr.is_valid());
  12146. svr.Get("/test", [](const Request &, Response &res) {
  12147. res.set_content("ok", "text/plain");
  12148. });
  12149. thread t([&]() { svr.listen(HOST, PORT); });
  12150. auto se = detail::scope_exit([&] {
  12151. svr.stop();
  12152. t.join();
  12153. });
  12154. svr.wait_until_ready();
  12155. bool verify_callback_called = false;
  12156. bool ip_matched_via_cn = true;
  12157. SSLClient cli(HOST, PORT);
  12158. cli.enable_server_certificate_verification(true);
  12159. cli.set_ca_cert_path(CA_CERT_FILE);
  12160. cli.set_connection_timeout(5);
  12161. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12162. verify_callback_called = true;
  12163. if (!ctx.cert) return false;
  12164. // The IP appears only in the CN, so it must NOT be accepted.
  12165. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12166. return true; // Accept for the purpose of this test
  12167. });
  12168. cli.Get("/test");
  12169. ASSERT_TRUE(verify_callback_called)
  12170. << "Verify callback should have been called";
  12171. EXPECT_FALSE(ip_matched_via_cn)
  12172. << "An IP host must not be authenticated via the certificate CN";
  12173. }
  12174. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12175. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12176. using namespace httplib::tls;
  12177. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12178. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12179. ASSERT_TRUE(svr.is_valid());
  12180. svr.Get("/test", [](const Request &, Response &res) {
  12181. res.set_content("ok", "text/plain");
  12182. });
  12183. thread t([&]() { svr.listen(HOST, PORT); });
  12184. auto se = detail::scope_exit([&] {
  12185. svr.stop();
  12186. t.join();
  12187. });
  12188. svr.wait_until_ready();
  12189. bool verify_callback_called = false;
  12190. bool san_matched = false;
  12191. bool wrong_ipv6_matched = true;
  12192. bool cn_ipv6_matched = true;
  12193. SSLClient cli(HOST, PORT);
  12194. cli.enable_server_certificate_verification(true);
  12195. cli.set_ca_cert_path(CA_CERT_FILE);
  12196. cli.set_connection_timeout(5);
  12197. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12198. verify_callback_called = true;
  12199. if (!ctx.cert) return false;
  12200. // Matches the IPv6 iPAddress SAN.
  12201. san_matched = ctx.check_hostname("2001:db8::1");
  12202. // A different IPv6 address must not match.
  12203. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12204. // "::1" lives only in the CN, so it must not be accepted.
  12205. cn_ipv6_matched = ctx.check_hostname("::1");
  12206. return true; // Accept for the purpose of this test
  12207. });
  12208. cli.Get("/test");
  12209. ASSERT_TRUE(verify_callback_called)
  12210. << "Verify callback should have been called";
  12211. EXPECT_TRUE(san_matched)
  12212. << "verify_hostname should match an IPv6 iPAddress SAN";
  12213. EXPECT_FALSE(wrong_ipv6_matched)
  12214. << "verify_hostname should not match a non-matching IPv6 address";
  12215. EXPECT_FALSE(cn_ipv6_matched)
  12216. << "An IPv6 host must not be authenticated via the certificate CN";
  12217. }
  12218. #endif
  12219. // mbedTLS-specific callback constructor test
  12220. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12221. #ifdef CPPHTTPLIB_SSL_ENABLED
  12222. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12224. ASSERT_TRUE(svr.is_valid());
  12225. // Set up a handler to verify client certificate is present
  12226. bool client_cert_verified = false;
  12227. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12228. // Verify that client certificate was provided
  12229. client_cert_verified = true;
  12230. res.set_content("success", "text/plain");
  12231. });
  12232. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12233. auto se = detail::scope_exit([&] {
  12234. svr.stop();
  12235. t.join();
  12236. ASSERT_FALSE(svr.is_running());
  12237. });
  12238. svr.wait_until_ready();
  12239. // Client with certificate
  12240. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12241. cli.enable_server_certificate_verification(false);
  12242. cli.set_connection_timeout(30);
  12243. auto res = cli.Get("/test");
  12244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12245. ASSERT_EQ(StatusCode::OK_200, res->status);
  12246. ASSERT_TRUE(client_cert_verified);
  12247. EXPECT_EQ("success", res->body);
  12248. }
  12249. #endif
  12250. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12251. // backends
  12252. #ifdef CPPHTTPLIB_SSL_ENABLED
  12253. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12254. using namespace httplib::tls;
  12255. // Test that when client CA cert file is provided,
  12256. // the server properly requests and validates client certificates
  12257. // Create a server with client authentication
  12258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12259. ASSERT_TRUE(svr.is_valid());
  12260. bool handler_called = false;
  12261. svr.Get("/test", [&](const Request &req, Response &res) {
  12262. handler_called = true;
  12263. // Verify that a client certificate was provided
  12264. auto cert = req.peer_cert();
  12265. ASSERT_TRUE(static_cast<bool>(cert));
  12266. // Get the issuer name
  12267. std::string issuer_str = cert.issuer_name();
  12268. ASSERT_FALSE(issuer_str.empty());
  12269. // The client certificate should be issued by our test CA
  12270. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12271. res.set_content("authenticated", "text/plain");
  12272. });
  12273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. t.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. // Connect with a client certificate issued by the CA
  12281. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12282. cli.enable_server_certificate_verification(false);
  12283. cli.set_connection_timeout(30);
  12284. auto res = cli.Get("/test");
  12285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12286. ASSERT_EQ(StatusCode::OK_200, res->status);
  12287. ASSERT_TRUE(handler_called);
  12288. EXPECT_EQ("authenticated", res->body);
  12289. }
  12290. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12291. using namespace httplib::tls;
  12292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12293. ASSERT_TRUE(svr.is_valid());
  12294. svr.Get("/test", [](const Request &, Response &res) {
  12295. res.set_content("ok", "text/plain");
  12296. });
  12297. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. t.join();
  12301. });
  12302. svr.wait_until_ready();
  12303. SSLClient cli(HOST, PORT);
  12304. cli.enable_server_certificate_verification(false);
  12305. cli.set_connection_timeout(30);
  12306. bool cert_checked = false;
  12307. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12308. if (ctx.cert) {
  12309. auto sans = ctx.sans();
  12310. // Test certificate may or may not have SANs - just verify the API
  12311. // works If SANs exist, verify the types are valid
  12312. for (const auto &san : sans) {
  12313. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12314. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12315. san.type == SanType::OTHER);
  12316. EXPECT_FALSE(san.value.empty());
  12317. }
  12318. cert_checked = true;
  12319. }
  12320. return true;
  12321. });
  12322. auto res = cli.Get("/test");
  12323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12324. EXPECT_TRUE(cert_checked);
  12325. }
  12326. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12327. using namespace httplib::tls;
  12328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12329. ASSERT_TRUE(svr.is_valid());
  12330. svr.Get("/test", [](const Request &, Response &res) {
  12331. res.set_content("ok", "text/plain");
  12332. });
  12333. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. t.join();
  12337. });
  12338. svr.wait_until_ready();
  12339. SSLClient cli(HOST, PORT);
  12340. cli.enable_server_certificate_verification(false);
  12341. cli.set_connection_timeout(30);
  12342. bool validity_checked = false;
  12343. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12344. if (ctx.cert) {
  12345. time_t not_before = 0, not_after = 0;
  12346. bool result = ctx.validity(not_before, not_after);
  12347. EXPECT_TRUE(result);
  12348. // Verify that not_before < now < not_after for a valid cert
  12349. time_t now = time(nullptr);
  12350. EXPECT_LT(not_before, now);
  12351. EXPECT_GT(not_after, now);
  12352. validity_checked = true;
  12353. }
  12354. return true;
  12355. });
  12356. auto res = cli.Get("/test");
  12357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12358. EXPECT_TRUE(validity_checked);
  12359. }
  12360. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12361. using namespace httplib::tls;
  12362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12363. ASSERT_TRUE(svr.is_valid());
  12364. svr.Get("/test", [](const Request &, Response &res) {
  12365. res.set_content("ok", "text/plain");
  12366. });
  12367. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12368. auto se = detail::scope_exit([&] {
  12369. svr.stop();
  12370. t.join();
  12371. });
  12372. svr.wait_until_ready();
  12373. SSLClient cli(HOST, PORT);
  12374. cli.enable_server_certificate_verification(false);
  12375. cli.set_connection_timeout(30);
  12376. bool serial_checked = false;
  12377. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12378. if (ctx.cert) {
  12379. std::string serial = ctx.serial();
  12380. EXPECT_FALSE(serial.empty());
  12381. // Serial should be a hex string
  12382. for (char c : serial) {
  12383. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12384. (c >= 'a' && c <= 'f'));
  12385. }
  12386. serial_checked = true;
  12387. }
  12388. return true;
  12389. });
  12390. auto res = cli.Get("/test");
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. EXPECT_TRUE(serial_checked);
  12393. }
  12394. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12395. // Test 1: Valid CA file - no error should be recorded
  12396. {
  12397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12398. CLIENT_CA_CERT_FILE);
  12399. ASSERT_TRUE(svr.is_valid());
  12400. // With valid setup, last_ssl_error should be 0
  12401. EXPECT_EQ(0, svr.ssl_last_error());
  12402. }
  12403. // Test 2: Invalid CA file content
  12404. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12405. {
  12406. // Create a temporary file with completely invalid content
  12407. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12408. {
  12409. std::ofstream ofs(temp_invalid_ca);
  12410. ofs << "This is not a certificate file at all\n";
  12411. ofs << "Just plain text content\n";
  12412. }
  12413. // Create server with invalid CA file
  12414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12415. // Clean up temporary file
  12416. std::remove(temp_invalid_ca);
  12417. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12418. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12419. // Note: SSL_CTX_load_verify_locations typically fails first,
  12420. // but our error handling code path is still exercised
  12421. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12422. }
  12423. }
  12424. TEST(VerifyCallbackTest, VerifyContextFields) {
  12425. using namespace httplib::tls;
  12426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12427. ASSERT_TRUE(svr.is_valid());
  12428. svr.Get("/test", [](const Request &, Response &res) {
  12429. res.set_content("ok", "text/plain");
  12430. });
  12431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12432. auto se = detail::scope_exit([&] {
  12433. svr.stop();
  12434. t.join();
  12435. });
  12436. svr.wait_until_ready();
  12437. SSLClient cli(HOST, PORT);
  12438. cli.enable_server_certificate_verification(false);
  12439. cli.set_connection_timeout(30);
  12440. int callback_count = 0;
  12441. bool saw_leaf_cert = false;
  12442. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12443. if (ctx.cert) {
  12444. callback_count++;
  12445. // We should see at least one certificate (the leaf)
  12446. std::string cn = ctx.subject_cn();
  12447. if (!cn.empty()) { saw_leaf_cert = true; }
  12448. // Verify context fields are populated
  12449. EXPECT_NE(ctx.session, nullptr);
  12450. EXPECT_GE(ctx.depth, 0);
  12451. }
  12452. return true;
  12453. });
  12454. auto res = cli.Get("/test");
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12456. EXPECT_GT(callback_count, 0);
  12457. EXPECT_TRUE(saw_leaf_cert);
  12458. }
  12459. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12460. using httplib::tls::TlsError;
  12461. // Test that verify_error_to_string returns empty for success
  12462. std::string success_str = TlsError::verify_error_to_string(0);
  12463. EXPECT_TRUE(success_str.empty());
  12464. // Test that verify_error_to_string returns non-empty for error codes
  12465. // Using a common error code (certificate expired)
  12466. std::string error_str =
  12467. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12468. EXPECT_FALSE(error_str.empty());
  12469. }
  12470. TEST(SessionVerifierTest, CertificateAccepted) {
  12471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12472. ASSERT_TRUE(svr.is_valid());
  12473. svr.Get("/test", [](const Request &, Response &res) {
  12474. res.set_content("ok", "text/plain");
  12475. });
  12476. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12477. auto se = detail::scope_exit([&] {
  12478. svr.stop();
  12479. t.join();
  12480. });
  12481. svr.wait_until_ready();
  12482. SSLClient cli(HOST, PORT);
  12483. cli.enable_server_certificate_verification(false);
  12484. cli.set_connection_timeout(30);
  12485. bool callback_called = false;
  12486. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12487. EXPECT_NE(session, nullptr);
  12488. callback_called = true;
  12489. return SSLVerifierResponse::CertificateAccepted;
  12490. });
  12491. auto res = cli.Get("/test");
  12492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12493. EXPECT_EQ(200, res->status);
  12494. EXPECT_TRUE(callback_called);
  12495. }
  12496. TEST(SessionVerifierTest, CertificateRejected) {
  12497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12498. ASSERT_TRUE(svr.is_valid());
  12499. svr.Get("/test", [](const Request &, Response &res) {
  12500. res.set_content("ok", "text/plain");
  12501. });
  12502. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12503. auto se = detail::scope_exit([&] {
  12504. svr.stop();
  12505. t.join();
  12506. });
  12507. svr.wait_until_ready();
  12508. SSLClient cli(HOST, PORT);
  12509. cli.enable_server_certificate_verification(false);
  12510. cli.set_connection_timeout(30);
  12511. bool callback_called = false;
  12512. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12513. EXPECT_NE(session, nullptr);
  12514. callback_called = true;
  12515. return SSLVerifierResponse::CertificateRejected;
  12516. });
  12517. auto res = cli.Get("/test");
  12518. EXPECT_FALSE(res);
  12519. EXPECT_TRUE(callback_called);
  12520. }
  12521. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12523. ASSERT_TRUE(svr.is_valid());
  12524. svr.Get("/test", [](const Request &, Response &res) {
  12525. res.set_content("ok", "text/plain");
  12526. });
  12527. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12528. auto se = detail::scope_exit([&] {
  12529. svr.stop();
  12530. t.join();
  12531. });
  12532. svr.wait_until_ready();
  12533. // NoDecisionMade with verification disabled should succeed (no default check)
  12534. SSLClient cli(HOST, PORT);
  12535. cli.enable_server_certificate_verification(false);
  12536. cli.set_connection_timeout(30);
  12537. bool callback_called = false;
  12538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12539. EXPECT_NE(session, nullptr);
  12540. callback_called = true;
  12541. return SSLVerifierResponse::NoDecisionMade;
  12542. });
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_EQ(200, res->status);
  12546. EXPECT_TRUE(callback_called);
  12547. }
  12548. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12550. ASSERT_TRUE(svr.is_valid());
  12551. svr.Get("/test", [](const Request &, Response &res) {
  12552. res.set_content("ok", "text/plain");
  12553. });
  12554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. });
  12559. svr.wait_until_ready();
  12560. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12561. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12562. // so we only check that the request fails, not whether the callback was
  12563. // called.
  12564. SSLClient cli(HOST, PORT);
  12565. cli.enable_server_certificate_verification(true);
  12566. cli.set_connection_timeout(30);
  12567. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12568. EXPECT_NE(session, nullptr);
  12569. return SSLVerifierResponse::NoDecisionMade;
  12570. });
  12571. auto res = cli.Get("/test");
  12572. EXPECT_FALSE(res);
  12573. }
  12574. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12575. // Test SSL server using PemMemory constructor with client CA certificates
  12576. // Read PEM files
  12577. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12578. read_file(SERVER_CERT_FILE, server_cert_pem);
  12579. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12580. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12581. // Create SSLServer with PemMemory constructor including client CA
  12582. SSLServer::PemMemory server_pem = {
  12583. server_cert_pem.c_str(),
  12584. server_cert_pem.size(),
  12585. server_key_pem.c_str(),
  12586. server_key_pem.size(),
  12587. client_ca_pem.c_str(),
  12588. client_ca_pem.size(),
  12589. nullptr // no password for server key
  12590. };
  12591. SSLServer svr(server_pem);
  12592. ASSERT_TRUE(svr.is_valid());
  12593. // No SSL error should be recorded for valid setup
  12594. EXPECT_EQ(0, svr.ssl_last_error());
  12595. // Set up server endpoints
  12596. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12597. res.set_content("ok", "text/plain");
  12598. });
  12599. // Start server in a thread
  12600. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12601. svr.wait_until_ready();
  12602. // Connect with client certificate (using constructor with paths)
  12603. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12604. cli.enable_server_certificate_verification(false);
  12605. auto res = cli.Get("/test-pem-ca");
  12606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12607. EXPECT_EQ(200, res->status);
  12608. EXPECT_EQ("ok", res->body);
  12609. svr.stop();
  12610. server_thread.join();
  12611. }
  12612. #endif
  12613. #ifdef _WIN32
  12614. TEST(CleanupTest, WSACleanup) {
  12615. int ret = WSACleanup();
  12616. ASSERT_EQ(0, ret);
  12617. }
  12618. #endif
  12619. #ifndef CPPHTTPLIB_SSL_ENABLED
  12620. TEST(NoSSLSupport, SimpleInterface) {
  12621. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12622. }
  12623. #endif
  12624. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12625. TEST(InvalidScheme, SimpleInterface) {
  12626. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12627. }
  12628. #endif
  12629. TEST(NoScheme, SimpleInterface) {
  12630. Client cli("yahoo.com:80");
  12631. ASSERT_TRUE(cli.is_valid());
  12632. }
  12633. TEST(SendAPI, SimpleInterface_Online) {
  12634. Client cli("http://yahoo.com");
  12635. Request req;
  12636. req.method = "GET";
  12637. req.path = "/";
  12638. auto res = cli.send(req);
  12639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12640. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12641. }
  12642. TEST(SendAPI, WithParamsInRequest) {
  12643. Server svr;
  12644. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12645. EXPECT_TRUE(req.has_param("test"));
  12646. EXPECT_EQ("test_value", req.get_param_value("test"));
  12647. });
  12648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12649. auto se = detail::scope_exit([&] {
  12650. svr.stop();
  12651. t.join();
  12652. ASSERT_FALSE(svr.is_running());
  12653. });
  12654. svr.wait_until_ready();
  12655. Client cli(HOST, PORT);
  12656. {
  12657. Request req;
  12658. req.method = "GET";
  12659. req.path = "/";
  12660. req.params.emplace("test", "test_value");
  12661. auto res = cli.send(req);
  12662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12663. }
  12664. {
  12665. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12667. }
  12668. }
  12669. TEST(ClientImplMethods, GetSocketTest) {
  12670. httplib::Server svr;
  12671. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12672. res.status = StatusCode::OK_200;
  12673. });
  12674. auto port = svr.bind_to_any_port("127.0.0.1");
  12675. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12676. auto se = detail::scope_exit([&] {
  12677. svr.stop();
  12678. thread.join();
  12679. ASSERT_FALSE(svr.is_running());
  12680. });
  12681. svr.wait_until_ready();
  12682. {
  12683. httplib::Client cli("127.0.0.1", port);
  12684. cli.set_keep_alive(true);
  12685. // Use the behavior of cpp-httplib of opening the connection
  12686. // only when the first request happens. If that changes,
  12687. // this test would be obsolete.
  12688. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12689. // This also implicitly tests the server. But other tests would fail much
  12690. // earlier than this one to be considered.
  12691. auto res = cli.Get("/");
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. EXPECT_EQ(StatusCode::OK_200, res->status);
  12694. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12695. }
  12696. }
  12697. #ifdef CPPHTTPLIB_SSL_ENABLED
  12698. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12699. Client cli("http://yahoo.com");
  12700. auto res = cli.Get("/");
  12701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12703. cli.set_follow_location(true);
  12704. res = cli.Get("/");
  12705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12706. EXPECT_EQ(StatusCode::OK_200, res->status);
  12707. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12708. }
  12709. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12710. Client cli("https://yahoo.com");
  12711. auto res = cli.Get("/");
  12712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12713. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12714. cli.set_follow_location(true);
  12715. res = cli.Get("/");
  12716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12717. EXPECT_EQ(StatusCode::OK_200, res->status);
  12718. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12719. }
  12720. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12721. Client cli("https://yahoo.com");
  12722. auto res = cli.Get("/");
  12723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12724. ASSERT_FALSE(!res);
  12725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12726. ASSERT_FALSE(res == nullptr);
  12727. ASSERT_TRUE(res != nullptr);
  12728. EXPECT_EQ(Error::Success, res.error());
  12729. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12730. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12731. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12732. cli.set_follow_location(true);
  12733. res = cli.Get("/");
  12734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12735. EXPECT_EQ(Error::Success, res.error());
  12736. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12737. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12738. EXPECT_EQ(StatusCode::OK_200, res->status);
  12739. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12740. }
  12741. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12742. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12743. Client cli("https://cdnjs.cloudflare.com");
  12744. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12745. Headers{{"Accept-Encoding", "br"}});
  12746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12747. EXPECT_EQ(StatusCode::OK_200, res->status);
  12748. EXPECT_EQ(287630U, res->body.size());
  12749. EXPECT_EQ("application/javascript; charset=utf-8",
  12750. res->get_header_value("Content-Type"));
  12751. }
  12752. #endif
  12753. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12754. #undef REDIR_HOST // Silence compiler warning
  12755. #define REDIR_HOST "https://httpbingo.org"
  12756. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12757. Client cli(REDIR_HOST);
  12758. cli.set_follow_location(true);
  12759. auto res =
  12760. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12762. EXPECT_EQ(StatusCode::OK_200, res->status);
  12763. }
  12764. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12765. Client cli(REDIR_HOST);
  12766. cli.set_follow_location(true);
  12767. Params params;
  12768. params.emplace("url", "http://example.com");
  12769. params.emplace("status_code", "302");
  12770. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12772. EXPECT_EQ(StatusCode::OK_200, res->status);
  12773. }
  12774. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12775. Client cli(REDIR_HOST);
  12776. cli.set_follow_location(true);
  12777. Params params;
  12778. params.emplace("url", "http://example.com");
  12779. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12781. EXPECT_EQ(StatusCode::OK_200, res->status);
  12782. }
  12783. TEST(HttpToHttpsRedirectTest, CertFile) {
  12784. auto ssl_port = PORT + 1;
  12785. Server svr;
  12786. ASSERT_TRUE(svr.is_valid());
  12787. svr.Get("/index", [&](const Request &, Response &res) {
  12788. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12789. "/index");
  12790. svr.stop();
  12791. });
  12792. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12793. ASSERT_TRUE(ssl_svr.is_valid());
  12794. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12795. res.set_content("test", "text/plain");
  12796. ssl_svr.stop();
  12797. });
  12798. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12799. thread t2 =
  12800. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12801. auto se = detail::scope_exit([&] {
  12802. t2.join();
  12803. t.join();
  12804. ASSERT_FALSE(svr.is_running());
  12805. });
  12806. svr.wait_until_ready();
  12807. ssl_svr.wait_until_ready();
  12808. Client cli("127.0.0.1", PORT);
  12809. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12810. cli.enable_server_certificate_verification(true);
  12811. cli.set_follow_location(true);
  12812. cli.set_connection_timeout(30);
  12813. auto res = cli.Get("/index");
  12814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12815. ASSERT_EQ(StatusCode::OK_200, res->status);
  12816. }
  12817. TEST(SSLClientRedirectTest, CertFile) {
  12818. auto ssl_port = PORT + 1;
  12819. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12820. ASSERT_TRUE(ssl_svr1.is_valid());
  12821. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12822. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12823. "/index");
  12824. ssl_svr1.stop();
  12825. });
  12826. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12827. ASSERT_TRUE(ssl_svr2.is_valid());
  12828. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12829. res.set_content("test", "text/plain");
  12830. ssl_svr2.stop();
  12831. });
  12832. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12833. thread t2 =
  12834. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12835. auto se = detail::scope_exit([&] {
  12836. t2.join();
  12837. t.join();
  12838. ASSERT_FALSE(ssl_svr1.is_running());
  12839. });
  12840. ssl_svr1.wait_until_ready();
  12841. ssl_svr2.wait_until_ready();
  12842. SSLClient cli("127.0.0.1", PORT);
  12843. std::string cert;
  12844. read_file(SERVER_CERT2_FILE, cert);
  12845. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12846. cli.enable_server_certificate_verification(true);
  12847. cli.set_follow_location(true);
  12848. cli.set_connection_timeout(30);
  12849. auto res = cli.Get("/index");
  12850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12851. ASSERT_EQ(StatusCode::OK_200, res->status);
  12852. }
  12853. #endif
  12854. #ifdef CPPHTTPLIB_SSL_ENABLED
  12855. // Test that set_ca_cert_store() skips system certs (consistent with
  12856. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12857. // should be trusted - system certs should NOT be loaded.
  12858. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12859. // Load a specific cert that is NOT a system CA cert
  12860. std::string cert;
  12861. read_file(SERVER_CERT2_FILE, cert);
  12862. SSLClient cli("google.com");
  12863. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12864. cli.enable_server_certificate_verification(true);
  12865. // This should FAIL because:
  12866. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12867. // 2. System certs should NOT be loaded when custom store is set
  12868. // If system certs WERE loaded, this would succeed
  12869. auto res = cli.Get("/");
  12870. ASSERT_FALSE(res);
  12871. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12872. }
  12873. // Same as above, but through the native store handle path. Regression test:
  12874. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12875. // merged system certs into the user-provided store.
  12876. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12877. std::string cert;
  12878. read_file(SERVER_CERT2_FILE, cert);
  12879. SSLClient cli("google.com");
  12880. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12881. cli.enable_server_certificate_verification(true);
  12882. auto res = cli.Get("/");
  12883. ASSERT_FALSE(res);
  12884. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12885. }
  12886. // A custom store set via the native handle must still verify a server whose
  12887. // cert it does contain.
  12888. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12889. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12890. ASSERT_TRUE(svr.is_valid());
  12891. svr.Get("/test", [&](const Request &, Response &res) {
  12892. res.set_content("test", "text/plain");
  12893. });
  12894. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12895. auto se = detail::scope_exit([&] {
  12896. svr.stop();
  12897. t.join();
  12898. ASSERT_FALSE(svr.is_running());
  12899. });
  12900. svr.wait_until_ready();
  12901. SSLClient cli("127.0.0.1", PORT);
  12902. std::string cert;
  12903. read_file(SERVER_CERT2_FILE, cert);
  12904. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12905. cli.enable_server_certificate_verification(true);
  12906. cli.set_connection_timeout(30);
  12907. auto res = cli.Get("/test");
  12908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12909. ASSERT_EQ(StatusCode::OK_200, res->status);
  12910. }
  12911. // CA certs loaded through the universal Client must be transferred to the
  12912. // client created internally for following an HTTPS redirect. Regression test:
  12913. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12914. // the CA data for redirect transfer.
  12915. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12916. auto ssl_port = PORT + 1;
  12917. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12918. ASSERT_TRUE(ssl_svr1.is_valid());
  12919. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12920. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12921. "/index");
  12922. });
  12923. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12924. ASSERT_TRUE(ssl_svr2.is_valid());
  12925. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12926. res.set_content("test", "text/plain");
  12927. });
  12928. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12929. thread t2 =
  12930. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12931. auto se = detail::scope_exit([&] {
  12932. ssl_svr2.stop();
  12933. ssl_svr1.stop();
  12934. t2.join();
  12935. t.join();
  12936. ASSERT_FALSE(ssl_svr1.is_running());
  12937. });
  12938. ssl_svr1.wait_until_ready();
  12939. ssl_svr2.wait_until_ready();
  12940. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12941. std::string cert;
  12942. read_file(SERVER_CERT2_FILE, cert);
  12943. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12944. cli.enable_server_certificate_verification(true);
  12945. cli.set_follow_location(true);
  12946. cli.set_connection_timeout(30);
  12947. auto res = cli.Get("/index");
  12948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12949. ASSERT_EQ(StatusCode::OK_200, res->status);
  12950. }
  12951. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12952. // so a host signed by a system CA verifies even though a custom CA is set
  12953. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12954. std::string cert;
  12955. read_file(SERVER_CERT2_FILE, cert);
  12956. SSLClient cli("google.com");
  12957. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12958. cli.enable_system_ca(true);
  12959. cli.enable_server_certificate_verification(true);
  12960. auto res = cli.Get("/");
  12961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12962. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12963. }
  12964. // The custom CA remains effective when combined with the system CA
  12965. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12966. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12967. ASSERT_TRUE(svr.is_valid());
  12968. svr.Get("/test", [&](const Request &, Response &res) {
  12969. res.set_content("test", "text/plain");
  12970. });
  12971. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12972. auto se = detail::scope_exit([&] {
  12973. svr.stop();
  12974. t.join();
  12975. ASSERT_FALSE(svr.is_running());
  12976. });
  12977. svr.wait_until_ready();
  12978. SSLClient cli("127.0.0.1", PORT);
  12979. std::string cert;
  12980. read_file(SERVER_CERT2_FILE, cert);
  12981. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12982. cli.enable_system_ca(true);
  12983. cli.enable_server_certificate_verification(true);
  12984. cli.set_connection_timeout(30);
  12985. auto res = cli.Get("/test");
  12986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12987. ASSERT_EQ(StatusCode::OK_200, res->status);
  12988. }
  12989. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12990. // skip chain verification entirely (only the certificate identity was
  12991. // checked), so a server presenting an untrusted certificate with a matching
  12992. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12993. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12994. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12995. ASSERT_TRUE(svr.is_valid());
  12996. svr.Get("/test", [&](const Request &, Response &res) {
  12997. res.set_content("test", "text/plain");
  12998. });
  12999. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13000. auto se = detail::scope_exit([&] {
  13001. svr.stop();
  13002. t.join();
  13003. ASSERT_FALSE(svr.is_running());
  13004. });
  13005. svr.wait_until_ready();
  13006. SSLClient cli("127.0.0.1", PORT);
  13007. std::string cert;
  13008. // A trusted CA that did not sign the server certificate. The server cert
  13009. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13010. // this connection.
  13011. read_file(CLIENT_CA_CERT_FILE, cert);
  13012. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13013. cli.enable_server_certificate_verification(true);
  13014. cli.set_connection_timeout(30);
  13015. auto res = cli.Get("/test");
  13016. ASSERT_FALSE(res);
  13017. }
  13018. // enable_system_ca(false) prevents system CA loading entirely
  13019. TEST(SSLClientTest, DisableSystemCa_Online) {
  13020. SSLClient cli("google.com");
  13021. cli.enable_system_ca(false);
  13022. cli.enable_server_certificate_verification(true);
  13023. auto res = cli.Get("/");
  13024. ASSERT_FALSE(res);
  13025. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13026. // itself when the CA chain is empty
  13027. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13028. res.error() == Error::SSLConnection);
  13029. }
  13030. // The universal Client forwards enable_system_ca()
  13031. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13032. std::string cert;
  13033. read_file(SERVER_CERT2_FILE, cert);
  13034. Client cli("https://google.com");
  13035. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13036. cli.enable_system_ca(true);
  13037. cli.enable_server_certificate_verification(true);
  13038. auto res = cli.Get("/");
  13039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13040. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13041. }
  13042. // The system CA policy must carry over to the client created internally for
  13043. // following a cross-host HTTPS redirect
  13044. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13045. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13046. ASSERT_TRUE(svr.is_valid());
  13047. svr.Get("/index", [&](const Request &, Response &res) {
  13048. res.set_redirect("https://www.google.com/");
  13049. });
  13050. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13051. auto se = detail::scope_exit([&] {
  13052. svr.stop();
  13053. t.join();
  13054. ASSERT_FALSE(svr.is_running());
  13055. });
  13056. svr.wait_until_ready();
  13057. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13058. std::string cert;
  13059. read_file(SERVER_CERT2_FILE, cert);
  13060. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13061. cli.enable_system_ca(true);
  13062. cli.enable_server_certificate_verification(true);
  13063. cli.set_follow_location(true);
  13064. cli.set_connection_timeout(30);
  13065. // Receiving any response proves the redirect client completed the TLS
  13066. // handshake with a system-CA-signed host
  13067. auto res = cli.Get("/index");
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. }
  13070. TEST(MultipartFormDataTest, LargeData) {
  13071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13072. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13073. const ContentReader &content_reader) {
  13074. if (req.is_multipart_form_data()) {
  13075. std::vector<FormData> items;
  13076. content_reader(
  13077. [&](const FormData &file) {
  13078. items.push_back(file);
  13079. return true;
  13080. },
  13081. [&](const char *data, size_t data_length) {
  13082. items.back().content.append(data, data_length);
  13083. return true;
  13084. });
  13085. EXPECT_TRUE(std::string(items[0].name) == "document");
  13086. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13087. EXPECT_TRUE(items[0].filename == "2MB_data");
  13088. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13089. EXPECT_TRUE(items[1].name == "hello");
  13090. EXPECT_TRUE(items[1].content == "world");
  13091. EXPECT_TRUE(items[1].filename == "");
  13092. EXPECT_TRUE(items[1].content_type == "");
  13093. } else {
  13094. std::string body;
  13095. content_reader([&](const char *data, size_t data_length) {
  13096. body.append(data, data_length);
  13097. return true;
  13098. });
  13099. }
  13100. });
  13101. auto port = svr.bind_to_any_port(HOST);
  13102. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. {
  13110. std::string data(1024 * 1024 * 2, '.');
  13111. std::stringstream buffer;
  13112. buffer << data;
  13113. SSLClient cli(HOST, port);
  13114. cli.enable_server_certificate_verification(false);
  13115. UploadFormDataItems items{
  13116. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13117. {"hello", "world", "", ""},
  13118. };
  13119. auto res = cli.Post("/post", items);
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. ASSERT_EQ(StatusCode::OK_200, res->status);
  13122. }
  13123. }
  13124. TEST(MultipartFormDataTest, DataProviderItems) {
  13125. std::random_device seed_gen;
  13126. std::mt19937 random(seed_gen());
  13127. std::string rand1;
  13128. rand1.resize(1000);
  13129. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13130. std::string rand2;
  13131. rand2.resize(3000);
  13132. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13134. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13135. const ContentReader &content_reader) {
  13136. ASSERT_FALSE(req.is_multipart_form_data());
  13137. std::string body;
  13138. content_reader([&](const char *data, size_t data_length) {
  13139. body.append(data, data_length);
  13140. return true;
  13141. });
  13142. EXPECT_EQ(body, "");
  13143. });
  13144. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13145. const ContentReader &content_reader) {
  13146. ASSERT_TRUE(req.is_multipart_form_data());
  13147. std::vector<FormData> items;
  13148. content_reader(
  13149. [&](const FormData &file) {
  13150. items.push_back(file);
  13151. return true;
  13152. },
  13153. [&](const char *data, size_t data_length) {
  13154. items.back().content.append(data, data_length);
  13155. return true;
  13156. });
  13157. ASSERT_TRUE(items.size() == 2);
  13158. EXPECT_EQ(std::string(items[0].name), "name1");
  13159. EXPECT_EQ(items[0].content, "Testing123");
  13160. EXPECT_EQ(items[0].filename, "filename1");
  13161. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13162. EXPECT_EQ(items[1].name, "name2");
  13163. EXPECT_EQ(items[1].content, "Testing456");
  13164. EXPECT_EQ(items[1].filename, "");
  13165. EXPECT_EQ(items[1].content_type, "");
  13166. });
  13167. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13168. const ContentReader &content_reader) {
  13169. ASSERT_TRUE(req.is_multipart_form_data());
  13170. std::vector<FormData> items;
  13171. content_reader(
  13172. [&](const FormData &file) {
  13173. items.push_back(file);
  13174. return true;
  13175. },
  13176. [&](const char *data, size_t data_length) {
  13177. items.back().content.append(data, data_length);
  13178. return true;
  13179. });
  13180. ASSERT_TRUE(items.size() == 2);
  13181. EXPECT_EQ(items[0].name, "name3");
  13182. EXPECT_EQ(items[0].content, rand1);
  13183. EXPECT_EQ(items[0].filename, "filename3");
  13184. EXPECT_EQ(items[0].content_type, "");
  13185. EXPECT_EQ(items[1].name, "name4");
  13186. EXPECT_EQ(items[1].content, rand2);
  13187. EXPECT_EQ(items[1].filename, "filename4");
  13188. EXPECT_EQ(items[1].content_type, "");
  13189. });
  13190. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13191. const ContentReader &content_reader) {
  13192. ASSERT_TRUE(req.is_multipart_form_data());
  13193. std::vector<FormData> items;
  13194. content_reader(
  13195. [&](const FormData &file) {
  13196. items.push_back(file);
  13197. return true;
  13198. },
  13199. [&](const char *data, size_t data_length) {
  13200. items.back().content.append(data, data_length);
  13201. return true;
  13202. });
  13203. ASSERT_TRUE(items.size() == 4);
  13204. EXPECT_EQ(std::string(items[0].name), "name1");
  13205. EXPECT_EQ(items[0].content, "Testing123");
  13206. EXPECT_EQ(items[0].filename, "filename1");
  13207. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13208. EXPECT_EQ(items[1].name, "name2");
  13209. EXPECT_EQ(items[1].content, "Testing456");
  13210. EXPECT_EQ(items[1].filename, "");
  13211. EXPECT_EQ(items[1].content_type, "");
  13212. EXPECT_EQ(items[2].name, "name3");
  13213. EXPECT_EQ(items[2].content, rand1);
  13214. EXPECT_EQ(items[2].filename, "filename3");
  13215. EXPECT_EQ(items[2].content_type, "");
  13216. EXPECT_EQ(items[3].name, "name4");
  13217. EXPECT_EQ(items[3].content, rand2);
  13218. EXPECT_EQ(items[3].filename, "filename4");
  13219. EXPECT_EQ(items[3].content_type, "");
  13220. });
  13221. auto port = svr.bind_to_any_port("localhost");
  13222. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. t.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. {
  13230. SSLClient cli("localhost", port);
  13231. cli.enable_server_certificate_verification(false);
  13232. UploadFormDataItems items{
  13233. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13234. {"name2", "Testing456", "", ""}, // not a file
  13235. };
  13236. {
  13237. auto res = cli.Post("/post-none", {}, {}, {});
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. ASSERT_EQ(StatusCode::OK_200, res->status);
  13240. }
  13241. FormDataProviderItems providers;
  13242. {
  13243. auto res =
  13244. cli.Post("/post-items", {}, items, providers); // empty providers
  13245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13246. ASSERT_EQ(StatusCode::OK_200, res->status);
  13247. }
  13248. providers.push_back({"name3",
  13249. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13250. // test the offset is given correctly at each step
  13251. if (!offset)
  13252. sink.os.write(rand1.data(), 30);
  13253. else if (offset == 30)
  13254. sink.os.write(rand1.data() + 30, 300);
  13255. else if (offset == 330)
  13256. sink.os.write(rand1.data() + 330, 670);
  13257. else if (offset == rand1.size())
  13258. sink.done();
  13259. return true;
  13260. },
  13261. "filename3",
  13262. {}});
  13263. providers.push_back({"name4",
  13264. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13265. // test the offset is given correctly at each step
  13266. if (!offset)
  13267. sink.os.write(rand2.data(), 2000);
  13268. else if (offset == 2000)
  13269. sink.os.write(rand2.data() + 2000, 1);
  13270. else if (offset == 2001)
  13271. sink.os.write(rand2.data() + 2001, 999);
  13272. else if (offset == rand2.size())
  13273. sink.done();
  13274. return true;
  13275. },
  13276. "filename4",
  13277. {}});
  13278. {
  13279. auto res = cli.Post("/post-providers", {}, {}, providers);
  13280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13281. ASSERT_EQ(StatusCode::OK_200, res->status);
  13282. }
  13283. {
  13284. auto res = cli.Post("/post-both", {}, items, providers);
  13285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13286. ASSERT_EQ(StatusCode::OK_200, res->status);
  13287. }
  13288. }
  13289. }
  13290. TEST(MultipartFormDataTest, BadHeader) {
  13291. Server svr;
  13292. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13293. res.set_content("ok", "text/plain");
  13294. });
  13295. thread t = thread([&] { svr.listen(HOST, PORT); });
  13296. auto se = detail::scope_exit([&] {
  13297. svr.stop();
  13298. t.join();
  13299. ASSERT_FALSE(svr.is_running());
  13300. });
  13301. svr.wait_until_ready();
  13302. const std::string body =
  13303. "This is the preamble. It is to be ignored, though it\r\n"
  13304. "is a handy place for composition agents to include an\r\n"
  13305. "explanatory note to non-MIME conformant readers.\r\n"
  13306. "\r\n"
  13307. "\r\n"
  13308. "--simple boundary\r\n"
  13309. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13310. ": BAD...\r\n"
  13311. "\r\n"
  13312. "value1\r\n"
  13313. "--simple boundary\r\n"
  13314. "Content-Disposition: form-data; name=\"field2\"; "
  13315. "filename=\"example.txt\"\r\n"
  13316. "\r\n"
  13317. "value2\r\n"
  13318. "--simple boundary--\r\n"
  13319. "This is the epilogue. It is also to be ignored.\r\n";
  13320. std::string content_type =
  13321. R"(multipart/form-data; boundary="simple boundary")";
  13322. Client cli(HOST, PORT);
  13323. auto res = cli.Post("/post", body, content_type.c_str());
  13324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13325. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13326. }
  13327. TEST(MultipartFormDataTest, WithPreamble) {
  13328. Server svr;
  13329. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13330. res.set_content("ok", "text/plain");
  13331. });
  13332. thread t = thread([&] { svr.listen(HOST, PORT); });
  13333. auto se = detail::scope_exit([&] {
  13334. svr.stop();
  13335. t.join();
  13336. ASSERT_FALSE(svr.is_running());
  13337. });
  13338. svr.wait_until_ready();
  13339. const std::string body =
  13340. "This is the preamble. It is to be ignored, though it\r\n"
  13341. "is a handy place for composition agents to include an\r\n"
  13342. "explanatory note to non-MIME conformant readers.\r\n"
  13343. "\r\n"
  13344. "\r\n"
  13345. "--simple boundary\r\n"
  13346. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13347. "\r\n"
  13348. "value1\r\n"
  13349. "--simple boundary\r\n"
  13350. "Content-Disposition: form-data; name=\"field2\"; "
  13351. "filename=\"example.txt\"\r\n"
  13352. "\r\n"
  13353. "value2\r\n"
  13354. "--simple boundary--\r\n"
  13355. "This is the epilogue. It is also to be ignored.\r\n";
  13356. std::string content_type =
  13357. R"(multipart/form-data; boundary="simple boundary")";
  13358. Client cli(HOST, PORT);
  13359. auto res = cli.Post("/post", body, content_type.c_str());
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. EXPECT_EQ(StatusCode::OK_200, res->status);
  13362. }
  13363. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13365. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13366. const ContentReader &content_reader) {
  13367. if (req.is_multipart_form_data()) {
  13368. std::vector<FormData> items;
  13369. content_reader(
  13370. [&](const FormData &file) {
  13371. items.push_back(file);
  13372. return true;
  13373. },
  13374. [&](const char *data, size_t data_length) {
  13375. items.back().content.append(data, data_length);
  13376. return true;
  13377. });
  13378. EXPECT_TRUE(std::string(items[0].name) == "document");
  13379. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13380. EXPECT_TRUE(items[0].filename == "2MB_data");
  13381. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13382. EXPECT_TRUE(items[1].name == "hello");
  13383. EXPECT_TRUE(items[1].content == "world");
  13384. EXPECT_TRUE(items[1].filename == "");
  13385. EXPECT_TRUE(items[1].content_type == "");
  13386. } else {
  13387. std::string body;
  13388. content_reader([&](const char *data, size_t data_length) {
  13389. body.append(data, data_length);
  13390. return true;
  13391. });
  13392. }
  13393. });
  13394. auto port = svr.bind_to_any_port("localhost");
  13395. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13396. auto se = detail::scope_exit([&] {
  13397. svr.stop();
  13398. t.join();
  13399. ASSERT_FALSE(svr.is_running());
  13400. });
  13401. svr.wait_until_ready();
  13402. {
  13403. std::string data(1024 * 1024 * 2, '.');
  13404. std::stringstream buffer;
  13405. buffer << data;
  13406. SSLClient cli("localhost", port);
  13407. cli.enable_server_certificate_verification(false);
  13408. UploadFormDataItems items{
  13409. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13410. {"hello", "world", "", ""},
  13411. };
  13412. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13414. ASSERT_EQ(StatusCode::OK_200, res->status);
  13415. }
  13416. }
  13417. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13418. std::string data(1024 * 1024 * 2, '&');
  13419. std::stringstream buffer;
  13420. buffer << data;
  13421. Client cli("https://localhost:8080");
  13422. UploadFormDataItems items{
  13423. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13424. {"hello", "world", "", ""},
  13425. };
  13426. for (const char &c : " \t\r\n") {
  13427. auto res =
  13428. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13429. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13430. ASSERT_FALSE(res);
  13431. }
  13432. }
  13433. TEST(MultipartFormDataTest, PutFormData) {
  13434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13435. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13436. const ContentReader &content_reader) {
  13437. if (req.is_multipart_form_data()) {
  13438. std::vector<FormData> items;
  13439. content_reader(
  13440. [&](const FormData &file) {
  13441. items.push_back(file);
  13442. return true;
  13443. },
  13444. [&](const char *data, size_t data_length) {
  13445. items.back().content.append(data, data_length);
  13446. return true;
  13447. });
  13448. EXPECT_TRUE(std::string(items[0].name) == "document");
  13449. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13450. EXPECT_TRUE(items[0].filename == "2MB_data");
  13451. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13452. EXPECT_TRUE(items[1].name == "hello");
  13453. EXPECT_TRUE(items[1].content == "world");
  13454. EXPECT_TRUE(items[1].filename == "");
  13455. EXPECT_TRUE(items[1].content_type == "");
  13456. } else {
  13457. std::string body;
  13458. content_reader([&](const char *data, size_t data_length) {
  13459. body.append(data, data_length);
  13460. return true;
  13461. });
  13462. }
  13463. });
  13464. auto port = svr.bind_to_any_port("localhost");
  13465. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13466. auto se = detail::scope_exit([&] {
  13467. svr.stop();
  13468. t.join();
  13469. ASSERT_FALSE(svr.is_running());
  13470. });
  13471. svr.wait_until_ready();
  13472. {
  13473. std::string data(1024 * 1024 * 2, '&');
  13474. std::stringstream buffer;
  13475. buffer << data;
  13476. SSLClient cli("localhost", port);
  13477. cli.enable_server_certificate_verification(false);
  13478. UploadFormDataItems items{
  13479. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13480. {"hello", "world", "", ""},
  13481. };
  13482. auto res = cli.Put("/put", items);
  13483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13484. ASSERT_EQ(StatusCode::OK_200, res->status);
  13485. }
  13486. }
  13487. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13489. svr.Put("/put_customboundary",
  13490. [&](const Request &req, const Response & /*res*/,
  13491. const ContentReader &content_reader) {
  13492. if (req.is_multipart_form_data()) {
  13493. std::vector<FormData> items;
  13494. content_reader(
  13495. [&](const FormData &file) {
  13496. items.push_back(file);
  13497. return true;
  13498. },
  13499. [&](const char *data, size_t data_length) {
  13500. items.back().content.append(data, data_length);
  13501. return true;
  13502. });
  13503. EXPECT_TRUE(std::string(items[0].name) == "document");
  13504. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13505. EXPECT_TRUE(items[0].filename == "2MB_data");
  13506. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13507. EXPECT_TRUE(items[1].name == "hello");
  13508. EXPECT_TRUE(items[1].content == "world");
  13509. EXPECT_TRUE(items[1].filename == "");
  13510. EXPECT_TRUE(items[1].content_type == "");
  13511. } else {
  13512. std::string body;
  13513. content_reader([&](const char *data, size_t data_length) {
  13514. body.append(data, data_length);
  13515. return true;
  13516. });
  13517. }
  13518. });
  13519. auto port = svr.bind_to_any_port("localhost");
  13520. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13521. auto se = detail::scope_exit([&] {
  13522. svr.stop();
  13523. t.join();
  13524. ASSERT_FALSE(svr.is_running());
  13525. });
  13526. svr.wait_until_ready();
  13527. {
  13528. std::string data(1024 * 1024 * 2, '&');
  13529. std::stringstream buffer;
  13530. buffer << data;
  13531. SSLClient cli("localhost", port);
  13532. cli.enable_server_certificate_verification(false);
  13533. UploadFormDataItems items{
  13534. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13535. {"hello", "world", "", ""},
  13536. };
  13537. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13539. ASSERT_EQ(StatusCode::OK_200, res->status);
  13540. }
  13541. }
  13542. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13543. std::string data(1024 * 1024 * 2, '&');
  13544. std::stringstream buffer;
  13545. buffer << data;
  13546. Client cli("https://localhost:8080");
  13547. cli.enable_server_certificate_verification(false);
  13548. UploadFormDataItems items{
  13549. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13550. {"hello", "world", "", ""},
  13551. };
  13552. for (const char &c : " \t\r\n") {
  13553. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13554. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13555. ASSERT_FALSE(res);
  13556. }
  13557. }
  13558. TEST(MultipartFormDataTest, AlternateFilename) {
  13559. auto handled = false;
  13560. Server svr;
  13561. svr.Post("/test", [&](const Request &req, Response &res) {
  13562. ASSERT_EQ(2u, req.form.files.size());
  13563. ASSERT_EQ(1u, req.form.fields.size());
  13564. // Test files
  13565. const auto &file1 = req.form.get_file("file1");
  13566. ASSERT_EQ("file1", file1.name);
  13567. ASSERT_EQ("A.txt", file1.filename);
  13568. ASSERT_EQ("text/plain", file1.content_type);
  13569. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13570. const auto &file2 = req.form.get_file("file2");
  13571. ASSERT_EQ("file2", file2.name);
  13572. ASSERT_EQ("a.html", file2.filename);
  13573. ASSERT_EQ("text/html", file2.content_type);
  13574. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13575. file2.content);
  13576. // Test text field
  13577. const auto &text = req.form.get_field("text");
  13578. ASSERT_EQ("text default", text);
  13579. res.set_content("ok", "text/plain");
  13580. handled = true;
  13581. });
  13582. thread t = thread([&] { svr.listen(HOST, PORT); });
  13583. auto se = detail::scope_exit([&] {
  13584. svr.stop();
  13585. t.join();
  13586. ASSERT_FALSE(svr.is_running());
  13587. ASSERT_TRUE(handled);
  13588. });
  13589. svr.wait_until_ready();
  13590. auto req = "POST /test HTTP/1.1\r\n"
  13591. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13592. "Content-Length: 399\r\n"
  13593. "\r\n"
  13594. "----------\r\n"
  13595. "Content-Disposition: form-data; name=\"text\"\r\n"
  13596. "\r\n"
  13597. "text default\r\n"
  13598. "----------\r\n"
  13599. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13600. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13601. "Content-Type: text/plain\r\n"
  13602. "\r\n"
  13603. "Content of a.txt.\r\n"
  13604. "\r\n"
  13605. "----------\r\n"
  13606. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13607. "\"a.html\"\r\n"
  13608. "Content-Type: text/html\r\n"
  13609. "\r\n"
  13610. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13611. "\r\n"
  13612. "------------\r\n";
  13613. ASSERT_TRUE(send_request(1, req));
  13614. }
  13615. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13616. auto handled = false;
  13617. Server svr;
  13618. svr.Post("/test", [&](const Request &req, Response &res) {
  13619. // Case-insensitive "utf-8''" prefix with a long value
  13620. const auto &file = req.form.get_file("file1");
  13621. ASSERT_EQ("file1", file.name);
  13622. // 8000 chars exercises both the Content-Disposition parser and the
  13623. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13624. // Prior to the fix, std::regex_match on this header would cause O(N)
  13625. // stack recursion in libstdc++, leading to SIGSEGV.
  13626. std::string expected_filename(8000, 'A');
  13627. ASSERT_EQ(expected_filename, file.filename);
  13628. res.set_content("ok", "text/plain");
  13629. handled = true;
  13630. });
  13631. thread t = thread([&] { svr.listen(HOST, PORT); });
  13632. auto se = detail::scope_exit([&] {
  13633. svr.stop();
  13634. t.join();
  13635. ASSERT_FALSE(svr.is_running());
  13636. ASSERT_TRUE(handled);
  13637. });
  13638. svr.wait_until_ready();
  13639. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13640. // Regression test for GHSA-qq6v-r583-3h69
  13641. std::string long_filename(8000, 'A');
  13642. std::string body = "----------\r\n"
  13643. "Content-Disposition: form-data; name=\"file1\"; "
  13644. "filename*=\"Utf-8''" +
  13645. long_filename +
  13646. "\"\r\n"
  13647. "\r\n"
  13648. "hello\r\n"
  13649. "------------\r\n";
  13650. auto req = "POST /test HTTP/1.1\r\n"
  13651. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13652. "Content-Length: " +
  13653. std::to_string(body.size()) + "\r\n\r\n" + body;
  13654. ASSERT_TRUE(send_request(1, req));
  13655. }
  13656. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13657. auto handled = false;
  13658. Server svr;
  13659. svr.Post("/test", [&](const Request &req, Response &) {
  13660. ASSERT_EQ(2u, req.form.fields.size());
  13661. const auto &text1 = req.form.get_field("text1");
  13662. ASSERT_EQ("text1", text1);
  13663. const auto &text2 = req.form.get_field("text2");
  13664. ASSERT_EQ("text2", text2);
  13665. handled = true;
  13666. });
  13667. thread t = thread([&] { svr.listen(HOST, PORT); });
  13668. auto se = detail::scope_exit([&] {
  13669. svr.stop();
  13670. t.join();
  13671. ASSERT_FALSE(svr.is_running());
  13672. ASSERT_TRUE(handled);
  13673. });
  13674. svr.wait_until_ready();
  13675. auto req = "POST /test HTTP/1.1\r\n"
  13676. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13677. "Content-Length: 146\r\n"
  13678. "\r\n----------\r\n"
  13679. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13680. "\r\n"
  13681. "text1"
  13682. "\r\n----------\r\n"
  13683. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13684. "\r\n"
  13685. "text2"
  13686. "\r\n------------";
  13687. std::string response;
  13688. ASSERT_TRUE(send_request(1, req, &response));
  13689. ASSERT_EQ("200", response.substr(9, 3));
  13690. }
  13691. TEST(MultipartFormDataTest, ContentLength) {
  13692. auto handled = false;
  13693. Server svr;
  13694. svr.Post("/test", [&](const Request &req, Response &) {
  13695. ASSERT_EQ(2u, req.form.fields.size());
  13696. const auto &text1 = req.form.get_field("text1");
  13697. ASSERT_EQ("text1", text1);
  13698. const auto &text2 = req.form.get_field("text2");
  13699. ASSERT_EQ("text2", text2);
  13700. handled = true;
  13701. });
  13702. thread t = thread([&] { svr.listen(HOST, PORT); });
  13703. auto se = detail::scope_exit([&] {
  13704. svr.stop();
  13705. t.join();
  13706. ASSERT_FALSE(svr.is_running());
  13707. ASSERT_TRUE(handled);
  13708. });
  13709. svr.wait_until_ready();
  13710. auto req = "POST /test HTTP/1.1\r\n"
  13711. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13712. "Content-Length: 167\r\n"
  13713. "\r\n----------\r\n"
  13714. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13715. "Content-Length: 5\r\n"
  13716. "\r\n"
  13717. "text1"
  13718. "\r\n----------\r\n"
  13719. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13720. "\r\n"
  13721. "text2"
  13722. "\r\n------------\r\n";
  13723. std::string response;
  13724. ASSERT_TRUE(send_request(1, req, &response));
  13725. ASSERT_EQ("200", response.substr(9, 3));
  13726. }
  13727. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13728. auto handled = false;
  13729. Server svr;
  13730. svr.Post("/test", [&](const Request &req, Response &) {
  13731. ASSERT_EQ(2u, req.form.fields.size());
  13732. const auto &text1 = req.form.get_field("text1");
  13733. ASSERT_EQ("text1", text1);
  13734. // TODO: Add header access for text fields if needed
  13735. const auto &text2 = req.form.get_field("text2");
  13736. ASSERT_EQ("text2", text2);
  13737. // TODO: Header access for text fields needs to be implemented
  13738. // auto &headers = it->second.headers;
  13739. // ASSERT_EQ(3U, headers.size());
  13740. // auto custom_header = headers.find("x-whatever");
  13741. // ASSERT_TRUE(custom_header != headers.end());
  13742. // ASSERT_NE("customvalue", custom_header->second);
  13743. // ASSERT_EQ("CustomValue", custom_header->second);
  13744. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13745. handled = true;
  13746. });
  13747. thread t = thread([&] { svr.listen(HOST, PORT); });
  13748. auto se = detail::scope_exit([&] {
  13749. svr.stop();
  13750. t.join();
  13751. ASSERT_FALSE(svr.is_running());
  13752. ASSERT_TRUE(handled);
  13753. });
  13754. svr.wait_until_ready();
  13755. auto req = "POST /test HTTP/1.1\r\n"
  13756. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13757. "Content-Length: 232\r\n"
  13758. "\r\n----------\r\n"
  13759. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13760. "Content-Length: 5\r\n"
  13761. "X-Test: 1\r\n"
  13762. "\r\n"
  13763. "text1"
  13764. "\r\n----------\r\n"
  13765. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13766. "Content-Type: text/plain\r\n"
  13767. "X-Whatever: CustomValue\r\n"
  13768. "\r\n"
  13769. "text2"
  13770. "\r\n------------\r\n"
  13771. "That should be disregarded. Not even read";
  13772. std::string response;
  13773. ASSERT_TRUE(send_request(1, req, &response));
  13774. ASSERT_EQ("200", response.substr(9, 3));
  13775. }
  13776. TEST(MultipartFormDataTest, LargeHeader) {
  13777. auto handled = false;
  13778. Server svr;
  13779. svr.Post("/test", [&](const Request &req, Response &) {
  13780. ASSERT_EQ(1u, req.form.fields.size());
  13781. const auto &text = req.form.get_field("name1");
  13782. ASSERT_EQ("text1", text);
  13783. handled = true;
  13784. });
  13785. thread t = thread([&] { svr.listen(HOST, PORT); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. ASSERT_TRUE(handled);
  13791. });
  13792. svr.wait_until_ready();
  13793. auto boundary = std::string("cpp-httplib-multipart-data");
  13794. std::string content = "--" + boundary +
  13795. "\r\n"
  13796. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13797. "\r\n"
  13798. "text1\r\n"
  13799. "--" +
  13800. boundary + "--\r\n";
  13801. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13802. "Content-Type: multipart/form-data;boundary=" +
  13803. boundary +
  13804. "\r\n"
  13805. "Content-Length: " +
  13806. std::to_string(content.size()) +
  13807. "\r\n"
  13808. "Dummy-Header: ";
  13809. std::string header_suffix = "\r\n"
  13810. "\r\n";
  13811. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13812. size_t header_dummy_size =
  13813. read_buff_size -
  13814. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13815. auto header_dummy = std::string(header_dummy_size, '@');
  13816. auto req = header_prefix + header_dummy + header_suffix + content;
  13817. std::string response;
  13818. ASSERT_TRUE(send_request(1, req, &response));
  13819. ASSERT_EQ("200", response.substr(9, 3));
  13820. }
  13821. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13822. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13823. // (not chunked Transfer-Encoding) after the streaming refactor.
  13824. auto handled = false;
  13825. Server svr;
  13826. svr.Post("/upload", [&](const Request &req, Response &res) {
  13827. auto cl_it = req.headers.find("Content-Length");
  13828. EXPECT_TRUE(cl_it != req.headers.end());
  13829. auto te_it = req.headers.find("Transfer-Encoding");
  13830. EXPECT_TRUE(te_it == req.headers.end());
  13831. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13832. res.set_content("ok", "text/plain");
  13833. handled = true;
  13834. });
  13835. auto port = svr.bind_to_any_port(HOST);
  13836. auto t = thread([&] { svr.listen_after_bind(); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. ASSERT_TRUE(handled);
  13842. });
  13843. svr.wait_until_ready();
  13844. UploadFormDataItems items = {
  13845. {"field1", "hello", "", "text/plain"},
  13846. {"file1", "world", "test.txt", "application/octet-stream"},
  13847. };
  13848. Client cli(HOST, port);
  13849. auto res = cli.Post("/upload", {}, items);
  13850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13851. EXPECT_EQ(StatusCode::OK_200, res->status);
  13852. }
  13853. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13854. // Verify that make_multipart_content_provider coalesces many small segments
  13855. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13856. constexpr size_t kItemCount = 1000;
  13857. UploadFormDataItems items;
  13858. items.reserve(kItemCount);
  13859. for (size_t i = 0; i < kItemCount; i++) {
  13860. items.push_back(
  13861. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13862. }
  13863. const std::string boundary = "----test-boundary";
  13864. auto content_length = detail::get_multipart_content_length(items, boundary);
  13865. auto provider = detail::make_multipart_content_provider(items, boundary);
  13866. // Drive the provider the same way write_content_with_progress does
  13867. size_t write_count = 0;
  13868. size_t total_bytes = 0;
  13869. DataSink sink;
  13870. size_t offset = 0;
  13871. sink.write = [&](const char *d, size_t l) -> bool {
  13872. (void)d;
  13873. write_count++;
  13874. total_bytes += l;
  13875. offset += l;
  13876. return true;
  13877. };
  13878. sink.is_writable = []() -> bool { return true; };
  13879. while (offset < content_length) {
  13880. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13881. }
  13882. EXPECT_EQ(content_length, total_bytes);
  13883. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13884. // With buffering into 64KB blocks, write_count should be much smaller.
  13885. auto segment_count = 3 * kItemCount + 1;
  13886. EXPECT_LT(write_count, segment_count / 10);
  13887. }
  13888. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13889. // Integration test: send many UploadFormDataItems and verify the server
  13890. // receives all of them correctly (#2410).
  13891. constexpr size_t kItemCount = 500;
  13892. auto handled = false;
  13893. Server svr;
  13894. svr.Post("/upload", [&](const Request &req, Response &res) {
  13895. EXPECT_EQ(kItemCount, req.form.fields.size());
  13896. for (size_t i = 0; i < kItemCount; i++) {
  13897. auto key = "field" + std::to_string(i);
  13898. auto val = "value" + std::to_string(i);
  13899. auto it = req.form.fields.find(key);
  13900. if (it != req.form.fields.end()) {
  13901. EXPECT_EQ(val, it->second.content);
  13902. } else {
  13903. ADD_FAILURE() << "Missing field: " << key;
  13904. }
  13905. }
  13906. res.set_content("ok", "text/plain");
  13907. handled = true;
  13908. });
  13909. auto port = svr.bind_to_any_port(HOST);
  13910. auto t = thread([&] { svr.listen_after_bind(); });
  13911. auto se = detail::scope_exit([&] {
  13912. svr.stop();
  13913. t.join();
  13914. ASSERT_FALSE(svr.is_running());
  13915. ASSERT_TRUE(handled);
  13916. });
  13917. svr.wait_until_ready();
  13918. UploadFormDataItems items;
  13919. items.reserve(kItemCount);
  13920. for (size_t i = 0; i < kItemCount; i++) {
  13921. items.push_back(
  13922. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13923. }
  13924. Client cli(HOST, port);
  13925. auto res = cli.Post("/upload", items);
  13926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13927. EXPECT_EQ(StatusCode::OK_200, res->status);
  13928. }
  13929. TEST(MultipartFormDataTest, MakeFileProvider) {
  13930. // Verify make_file_provider sends a file's contents correctly.
  13931. const std::string file_content(4096, 'Z');
  13932. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13933. {
  13934. std::ofstream ofs(tmp_path, std::ios::binary);
  13935. ofs.write(file_content.data(),
  13936. static_cast<std::streamsize>(file_content.size()));
  13937. }
  13938. auto handled = false;
  13939. Server svr;
  13940. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13941. const ContentReader &content_reader) {
  13942. ASSERT_TRUE(req.is_multipart_form_data());
  13943. std::vector<FormData> items;
  13944. content_reader(
  13945. [&](const FormData &file) {
  13946. items.push_back(file);
  13947. return true;
  13948. },
  13949. [&](const char *data, size_t data_length) {
  13950. items.back().content.append(data, data_length);
  13951. return true;
  13952. });
  13953. ASSERT_EQ(1u, items.size());
  13954. EXPECT_EQ("myfile", items[0].name);
  13955. EXPECT_EQ("data.bin", items[0].filename);
  13956. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13957. EXPECT_EQ(file_content, items[0].content);
  13958. handled = true;
  13959. });
  13960. auto port = svr.bind_to_any_port(HOST);
  13961. auto t = thread([&] { svr.listen_after_bind(); });
  13962. auto se = detail::scope_exit([&] {
  13963. svr.stop();
  13964. t.join();
  13965. ASSERT_FALSE(svr.is_running());
  13966. ASSERT_TRUE(handled);
  13967. std::remove(tmp_path.c_str());
  13968. });
  13969. svr.wait_until_ready();
  13970. FormDataProviderItems providers;
  13971. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13972. "application/octet-stream"));
  13973. Client cli(HOST, port);
  13974. auto res = cli.Post("/upload", {}, {}, providers);
  13975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13976. EXPECT_EQ(StatusCode::OK_200, res->status);
  13977. }
  13978. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13979. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13980. // (100) headers is rejected with a 400 Bad Request response.
  13981. Server svr;
  13982. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13983. res.set_content("ok", "text/plain");
  13984. });
  13985. thread t = thread([&] { svr.listen(HOST, PORT); });
  13986. auto se = detail::scope_exit([&] {
  13987. svr.stop();
  13988. t.join();
  13989. ASSERT_FALSE(svr.is_running());
  13990. });
  13991. svr.wait_until_ready();
  13992. // Build a multipart part with 101 custom headers (exceeding
  13993. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13994. std::stringstream body;
  13995. body << "--simpleboundary\r\n"
  13996. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13997. for (int i = 0; i < 101; i++) {
  13998. body << "X-Custom-Header-" << i << ": value\r\n";
  13999. }
  14000. body << "\r\n"
  14001. << "value1\r\n"
  14002. << "--simpleboundary--\r\n";
  14003. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14004. Client cli(HOST, PORT);
  14005. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14007. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14008. }
  14009. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14010. // A body that never contains the declared boundary must not be accumulated
  14011. // while the parser waits for it. Buffering it would also make every read
  14012. // rescan everything seen so far, which is quadratic in the body size.
  14013. Server svr;
  14014. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14015. res.set_content("ok", "text/plain");
  14016. });
  14017. auto port = svr.bind_to_any_port(HOST);
  14018. thread t = thread([&] { svr.listen_after_bind(); });
  14019. auto se = detail::scope_exit([&] {
  14020. svr.stop();
  14021. t.join();
  14022. ASSERT_FALSE(svr.is_running());
  14023. });
  14024. svr.wait_until_ready();
  14025. Client cli(HOST, port);
  14026. cli.set_read_timeout(60, 0);
  14027. cli.set_write_timeout(60, 0);
  14028. // '-' is the worst case: it matches the first character of the boundary, so
  14029. // every position has to be checked against it.
  14030. auto post_dashes = [&](size_t size) {
  14031. const std::string body(size, '-');
  14032. auto start = std::chrono::steady_clock::now();
  14033. auto res =
  14034. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14035. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14036. std::chrono::steady_clock::now() - start)
  14037. .count();
  14038. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14039. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14040. return ms;
  14041. };
  14042. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14043. // Windows.
  14044. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14045. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14046. // Comparing the two sizes rather than checking an absolute duration keeps
  14047. // this meaningful across build types and CI load, both of which move the
  14048. // absolute numbers by more than an order of magnitude. Four times the bytes
  14049. // costs about four times the time when parsing is linear, and about sixteen
  14050. // times when the body is buffered and rescanned.
  14051. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14052. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14053. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14054. << "ms, which suggests the body is being buffered and rescanned";
  14055. }
  14056. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14057. // A boundary can only be followed by CRLF or by "--", so anything else is
  14058. // malformed no matter what comes next. The parser must say so right away
  14059. // instead of buffering the rest of the declared body.
  14060. Server svr;
  14061. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14062. res.set_content("ok", "text/plain");
  14063. });
  14064. auto port = svr.bind_to_any_port(HOST);
  14065. thread t = thread([&] { svr.listen_after_bind(); });
  14066. auto se = detail::scope_exit([&] {
  14067. svr.stop();
  14068. t.join();
  14069. ASSERT_FALSE(svr.is_running());
  14070. });
  14071. svr.wait_until_ready();
  14072. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14073. // buffers instead of failing would still be waiting for the remaining bytes.
  14074. const std::string body = "--zzzz\r\n"
  14075. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14076. "\r\n"
  14077. "text1"
  14078. "\r\n--zzzzXX";
  14079. const std::string req = "POST /post HTTP/1.1\r\n"
  14080. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14081. "Content-Length: 1048576\r\n"
  14082. "\r\n" +
  14083. body;
  14084. std::string response;
  14085. ASSERT_TRUE(send_request(3, req, &response, port));
  14086. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14087. EXPECT_EQ("400", response.substr(9, 3));
  14088. }
  14089. // Posts a multipart body split into two writes, so that the server sees the
  14090. // split at whatever offset the caller chose, and expects the single "text1"
  14091. // field to come through.
  14092. static void expect_split_multipart_ok(const std::string &body1,
  14093. const std::string &body2) {
  14094. auto handled = false;
  14095. Server svr;
  14096. svr.Post("/post", [&](const Request &req, Response &) {
  14097. EXPECT_EQ(1u, req.form.fields.size());
  14098. EXPECT_EQ("text1", req.form.get_field("text1"));
  14099. handled = true;
  14100. });
  14101. auto port = svr.bind_to_any_port(HOST);
  14102. thread t = thread([&] { svr.listen_after_bind(); });
  14103. auto se = detail::scope_exit([&] {
  14104. svr.stop();
  14105. t.join();
  14106. ASSERT_FALSE(svr.is_running());
  14107. ASSERT_TRUE(handled);
  14108. });
  14109. svr.wait_until_ready();
  14110. // "Connection: close" makes the server close once it has answered, so the
  14111. // response drain ends immediately instead of idling until the read timeout.
  14112. const std::string head =
  14113. "POST /post HTTP/1.1\r\n"
  14114. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14115. "Connection: close\r\n"
  14116. "Content-Length: " +
  14117. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14118. std::string response;
  14119. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14120. ASSERT_GE(response.size(), 12u) << "no response";
  14121. EXPECT_EQ("200", response.substr(9, 3));
  14122. }
  14123. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14124. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14125. // ignored, including when it does not arrive in the same read as the
  14126. // close-delimiter itself.
  14127. expect_split_multipart_ok("--zzzz\r\n"
  14128. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14129. "\r\n"
  14130. "text1"
  14131. "\r\n--zzzz--",
  14132. "\r\nthis epilogue must be ignored\r\n");
  14133. }
  14134. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14135. // The initial boundary may be preceded by a preamble of any length and may
  14136. // straddle a read boundary. Discarding data while waiting for it must not
  14137. // throw away a partial boundary sitting at the end of the buffer.
  14138. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14139. "zz\r\n"
  14140. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14141. "\r\n"
  14142. "text1"
  14143. "\r\n--zzzz--\r\n");
  14144. }
  14145. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14146. // The received boundary was only checked for being non-empty, so it could be
  14147. // as long as a header is allowed to be. The parser scans the body for
  14148. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14149. // costs a nearly full comparison at nearly every position, making the
  14150. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14151. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14152. Server svr;
  14153. svr.Post("/post", [](const Request &req, Response &res) {
  14154. EXPECT_EQ(1u, req.form.fields.size());
  14155. EXPECT_EQ("text1", req.form.get_field("text1"));
  14156. res.set_content("ok", "text/plain");
  14157. });
  14158. auto port = svr.bind_to_any_port(HOST);
  14159. thread t = thread([&] { svr.listen_after_bind(); });
  14160. auto se = detail::scope_exit([&] {
  14161. svr.stop();
  14162. t.join();
  14163. ASSERT_FALSE(svr.is_running());
  14164. });
  14165. svr.wait_until_ready();
  14166. Client cli(HOST, port);
  14167. auto post_with_boundary_of_length = [&](size_t len) {
  14168. const std::string boundary(len, 'a');
  14169. const std::string body =
  14170. "--" + boundary +
  14171. "\r\n"
  14172. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14173. "\r\n"
  14174. "text1"
  14175. "\r\n--" +
  14176. boundary + "--\r\n";
  14177. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14178. };
  14179. auto res = post_with_boundary_of_length(70);
  14180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14181. EXPECT_EQ(StatusCode::OK_200, res->status);
  14182. res = post_with_boundary_of_length(71);
  14183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14184. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14185. }
  14186. TEST(MakeFileBodyTest, Basic) {
  14187. const std::string file_content(4096, 'Z');
  14188. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14189. {
  14190. std::ofstream ofs(tmp_path, std::ios::binary);
  14191. ofs.write(file_content.data(),
  14192. static_cast<std::streamsize>(file_content.size()));
  14193. }
  14194. auto handled = false;
  14195. Server svr;
  14196. svr.Post("/upload", [&](const Request &req, Response &res) {
  14197. EXPECT_EQ(file_content, req.body);
  14198. handled = true;
  14199. res.status = StatusCode::OK_200;
  14200. });
  14201. auto port = svr.bind_to_any_port(HOST);
  14202. auto t = thread([&] { svr.listen_after_bind(); });
  14203. auto se = detail::scope_exit([&] {
  14204. svr.stop();
  14205. t.join();
  14206. ASSERT_FALSE(svr.is_running());
  14207. ASSERT_TRUE(handled);
  14208. std::remove(tmp_path.c_str());
  14209. });
  14210. svr.wait_until_ready();
  14211. auto fb = make_file_body(tmp_path);
  14212. ASSERT_GT(fb.first, 0u);
  14213. Client cli(HOST, port);
  14214. auto res =
  14215. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14217. EXPECT_EQ(StatusCode::OK_200, res->status);
  14218. }
  14219. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14220. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14221. {
  14222. std::ofstream ofs(path, std::ios::binary);
  14223. const std::string content(100, 'A');
  14224. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14225. }
  14226. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14227. auto body = make_file_body(path);
  14228. ASSERT_EQ(100u, body.first);
  14229. ASSERT_TRUE(static_cast<bool>(body.second));
  14230. // Rewritten shorter after its length was measured - and, on a server, after
  14231. // that length has already gone out as Content-Length.
  14232. {
  14233. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14234. const std::string content(10, 'A');
  14235. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14236. }
  14237. std::string written;
  14238. DataSink sink;
  14239. sink.write = [&](const char *d, size_t l) {
  14240. written.append(d, l);
  14241. return true;
  14242. };
  14243. // The provider has to report failure. write_content_with_progress() advances
  14244. // its offset only by what was written, so a provider that returns true
  14245. // without completing the length it promised is called again straight away,
  14246. // and again.
  14247. EXPECT_FALSE(body.second(0, body.first, sink));
  14248. EXPECT_EQ(std::string(10, 'A'), written);
  14249. }
  14250. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14251. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14252. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14253. {
  14254. std::ofstream ofs(path, std::ios::binary);
  14255. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14256. }
  14257. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14258. auto body = make_file_body(path);
  14259. ASSERT_EQ(content.size(), body.first);
  14260. ASSERT_TRUE(static_cast<bool>(body.second));
  14261. std::string written;
  14262. DataSink sink;
  14263. sink.write = [&](const char *d, size_t l) {
  14264. written.append(d, l);
  14265. return true;
  14266. };
  14267. EXPECT_TRUE(body.second(0, body.first, sink));
  14268. EXPECT_EQ(content, written);
  14269. }
  14270. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14271. static constexpr unsigned int number_of_tasks{1000000};
  14272. std::atomic_uint count{0};
  14273. std::unique_ptr<TaskQueue> task_queue{
  14274. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14275. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14276. auto queued = task_queue->enqueue(
  14277. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14278. EXPECT_TRUE(queued);
  14279. }
  14280. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14281. task_queue->shutdown();
  14282. #else
  14283. EXPECT_NO_THROW(task_queue->shutdown());
  14284. #endif
  14285. EXPECT_EQ(number_of_tasks, count.load());
  14286. }
  14287. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14288. static constexpr unsigned int number_of_tasks{1000000};
  14289. static constexpr unsigned int qlimit{2};
  14290. unsigned int queued_count{0};
  14291. std::atomic_uint count{0};
  14292. std::unique_ptr<TaskQueue> task_queue{
  14293. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14294. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14295. if (task_queue->enqueue(
  14296. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14297. queued_count++;
  14298. }
  14299. }
  14300. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14301. task_queue->shutdown();
  14302. #else
  14303. EXPECT_NO_THROW(task_queue->shutdown());
  14304. #endif
  14305. EXPECT_EQ(queued_count, count.load());
  14306. EXPECT_TRUE(queued_count <= number_of_tasks);
  14307. EXPECT_TRUE(queued_count >= qlimit);
  14308. }
  14309. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14310. // Use a short idle timeout so a dynamic thread spawns, times out and
  14311. // exits during the test, and the pool keeps working afterwards.
  14312. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14313. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14314. /*idle_timeout_sec=*/1}};
  14315. std::atomic_uint count{0};
  14316. std::condition_variable cv;
  14317. std::mutex mtx;
  14318. bool release = false;
  14319. // Block the base thread so the second task spawns a dynamic thread.
  14320. EXPECT_TRUE(task_queue->enqueue([&] {
  14321. std::unique_lock<std::mutex> lock(mtx);
  14322. while (!release) {
  14323. cv.wait(lock);
  14324. }
  14325. count++;
  14326. }));
  14327. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14328. // Let the dynamic thread finish its task and exceed the idle timeout.
  14329. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14330. {
  14331. std::unique_lock<std::mutex> lock(mtx);
  14332. release = true;
  14333. }
  14334. cv.notify_all();
  14335. // The pool must still accept and run tasks after the dynamic thread exited.
  14336. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14337. task_queue->shutdown();
  14338. EXPECT_EQ(3u, count.load());
  14339. }
  14340. TEST(TaskQueueTest, MaxQueuedRequests) {
  14341. static constexpr unsigned int qlimit{3};
  14342. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14343. std::condition_variable sem_cv;
  14344. std::mutex sem_mtx;
  14345. int credits = 0;
  14346. bool queued;
  14347. /* Fill up the queue with tasks that will block until we give them credits to
  14348. * complete. */
  14349. for (unsigned int n = 0; n <= qlimit;) {
  14350. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14351. std::unique_lock<std::mutex> lock(sem_mtx);
  14352. while (credits <= 0) {
  14353. sem_cv.wait(lock);
  14354. }
  14355. /* Consume the credit and signal the test code if they are all gone. */
  14356. if (--credits == 0) { sem_cv.notify_one(); }
  14357. });
  14358. if (n < qlimit) {
  14359. /* The first qlimit enqueues must succeed. */
  14360. EXPECT_TRUE(queued);
  14361. } else {
  14362. /* The last one will succeed only when the worker thread
  14363. * starts and dequeues the first blocking task. Although
  14364. * not necessary for the correctness of this test, we sleep for
  14365. * a short while to avoid busy waiting. */
  14366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14367. }
  14368. if (queued) { n++; }
  14369. }
  14370. /* Further enqueues must fail since the queue is full. */
  14371. for (auto i = 0; i < 4; i++) {
  14372. queued = task_queue->enqueue([] {});
  14373. EXPECT_FALSE(queued);
  14374. }
  14375. /* Give the credits to allow the previous tasks to complete. */
  14376. {
  14377. std::unique_lock<std::mutex> lock(sem_mtx);
  14378. credits += qlimit + 1;
  14379. }
  14380. sem_cv.notify_all();
  14381. /* Wait for all the credits to be consumed. */
  14382. {
  14383. std::unique_lock<std::mutex> lock(sem_mtx);
  14384. while (credits > 0) {
  14385. sem_cv.wait(lock);
  14386. }
  14387. }
  14388. /* Check that we are able again to enqueue at least qlimit tasks. */
  14389. for (unsigned int i = 0; i < qlimit; i++) {
  14390. queued = task_queue->enqueue([] {});
  14391. EXPECT_TRUE(queued);
  14392. }
  14393. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14394. task_queue->shutdown();
  14395. #else
  14396. EXPECT_NO_THROW(task_queue->shutdown());
  14397. #endif
  14398. }
  14399. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14400. Server svr;
  14401. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14402. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14403. });
  14404. svr.Get("/hello", [](const Request &req, Response &res) {
  14405. res.set_content(req.get_param_value("key"), "text/plain");
  14406. });
  14407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14408. auto se = detail::scope_exit([&] {
  14409. svr.stop();
  14410. thread.join();
  14411. ASSERT_FALSE(svr.is_running());
  14412. });
  14413. svr.wait_until_ready();
  14414. {
  14415. Client cli(HOST, PORT);
  14416. cli.set_follow_location(true);
  14417. auto res = cli.Get("/");
  14418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14419. EXPECT_EQ(StatusCode::OK_200, res->status);
  14420. EXPECT_EQ("val&key2=val2", res->body);
  14421. }
  14422. }
  14423. #endif
  14424. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14425. Server svr;
  14426. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14427. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14428. });
  14429. svr.Get("/hello", [](const Request &req, Response &res) {
  14430. res.set_content(req.get_param_value("key"), "text/plain");
  14431. });
  14432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14433. auto se = detail::scope_exit([&] {
  14434. svr.stop();
  14435. thread.join();
  14436. ASSERT_FALSE(svr.is_running());
  14437. });
  14438. svr.wait_until_ready();
  14439. {
  14440. Client cli(HOST, PORT);
  14441. cli.set_follow_location(true);
  14442. auto res = cli.Get("/");
  14443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14444. EXPECT_EQ(StatusCode::OK_200, res->status);
  14445. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14446. }
  14447. }
  14448. TEST(RedirectTest, RedirectWithPlusInPath) {
  14449. Server svr;
  14450. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14451. res.set_redirect("/a+b");
  14452. });
  14453. // Route pattern uses regex; escape + as \\+
  14454. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14455. res.set_content(req.path, "text/plain");
  14456. });
  14457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14458. auto se = detail::scope_exit([&] {
  14459. svr.stop();
  14460. thread.join();
  14461. ASSERT_FALSE(svr.is_running());
  14462. });
  14463. svr.wait_until_ready();
  14464. {
  14465. Client cli(HOST, PORT);
  14466. cli.set_follow_location(true);
  14467. auto res = cli.Get("/");
  14468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14469. EXPECT_EQ(StatusCode::OK_200, res->status);
  14470. EXPECT_EQ("/a+b", res->body);
  14471. }
  14472. }
  14473. TEST(RedirectTest, ResolveRelativeLocation) {
  14474. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14475. const std::vector<std::pair<std::string, std::string>> cases = {
  14476. {"g", "/b/c/g"},
  14477. {"./g", "/b/c/g"},
  14478. {"g/", "/b/c/g/"},
  14479. {"?y", "/b/c/d;p?y"},
  14480. {"g?y", "/b/c/g?y"},
  14481. {"#s", "/b/c/d;p?q#s"},
  14482. {"g#s", "/b/c/g#s"},
  14483. {"g?y#s", "/b/c/g?y#s"},
  14484. {";x", "/b/c/;x"},
  14485. {"g;x", "/b/c/g;x"},
  14486. {".", "/b/c/"},
  14487. {"./", "/b/c/"},
  14488. {"..", "/b/"},
  14489. {"../", "/b/"},
  14490. {"../g", "/b/g"},
  14491. {"../..", "/"},
  14492. {"../../", "/"},
  14493. {"../../g", "/g"},
  14494. {"../../../g", "/g"},
  14495. {"g.", "/b/c/g."},
  14496. {".g", "/b/c/.g"},
  14497. {"g..", "/b/c/g.."},
  14498. {"..g", "/b/c/..g"},
  14499. {"./../g", "/b/g"},
  14500. {"./g/.", "/b/c/g/"},
  14501. {"g/./h", "/b/c/g/h"},
  14502. {"g/../h", "/b/c/h"},
  14503. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14504. {"g;x=1/../y", "/b/c/y"},
  14505. {"g?y/./x", "/b/c/g?y/./x"},
  14506. {"g#s/../x", "/b/c/g#s/../x"},
  14507. // Not relative-path references, so left for parse_url.
  14508. {"/g", "/g"},
  14509. {"//g", "//g"},
  14510. {"http://g/x", "http://g/x"},
  14511. {"g:h", "g:h"},
  14512. };
  14513. for (const auto &c : cases) {
  14514. EXPECT_EQ(c.second,
  14515. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14516. << c.first;
  14517. }
  14518. }
  14519. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14520. Server svr;
  14521. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14522. res.set_redirect(req.get_param_value("to"));
  14523. });
  14524. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14525. res.set_content(req.target, "text/plain");
  14526. });
  14527. svr.Get("/other", [](const Request &req, Response &res) {
  14528. res.set_content(req.target, "text/plain");
  14529. });
  14530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14531. auto se = detail::scope_exit([&] {
  14532. svr.stop();
  14533. thread.join();
  14534. ASSERT_FALSE(svr.is_running());
  14535. });
  14536. svr.wait_until_ready();
  14537. const std::vector<std::pair<std::string, std::string>> cases = {
  14538. {"next", "/dir/next"},
  14539. {"./next?x=1", "/dir/next?x=1"},
  14540. {"../other", "/other"},
  14541. };
  14542. for (const auto &c : cases) {
  14543. Client cli(HOST, PORT);
  14544. cli.set_follow_location(true);
  14545. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14546. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14547. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14548. EXPECT_EQ(c.second, res->body) << c.first;
  14549. }
  14550. }
  14551. #ifdef CPPHTTPLIB_SSL_ENABLED
  14552. TEST(RedirectTest, Issue2185_Online) {
  14553. SSLClient client("github.com");
  14554. client.set_follow_location(true);
  14555. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14556. "Coollab-Windows.zip");
  14557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14558. EXPECT_EQ(StatusCode::OK_200, res->status);
  14559. EXPECT_EQ(9920427U, res->body.size());
  14560. }
  14561. #endif
  14562. TEST(VulnerabilityTest, CRLFInjection) {
  14563. Server svr;
  14564. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14565. res.set_content("Hello 1", "text/plain");
  14566. });
  14567. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14568. res.set_content("Hello 2", "text/plain");
  14569. });
  14570. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14571. res.set_content("Hello 3", "text/plain");
  14572. });
  14573. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14574. res.set_content("Hello 4", "text/plain");
  14575. });
  14576. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14577. for (const auto &x : req.headers) {
  14578. auto key = x.first;
  14579. EXPECT_STRNE("evil", key.c_str());
  14580. }
  14581. });
  14582. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14583. auto se = detail::scope_exit([&] {
  14584. svr.stop();
  14585. thread.join();
  14586. ASSERT_FALSE(svr.is_running());
  14587. });
  14588. svr.wait_until_ready();
  14589. {
  14590. Client cli(HOST, PORT);
  14591. cli.Post("/test1", "A=B",
  14592. "application/x-www-form-urlencoded\r\nevil: hello1");
  14593. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14594. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14595. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14596. }
  14597. }
  14598. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14599. auto server_thread = std::thread([] {
  14600. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14601. default_socket_options(srv);
  14602. sockaddr_in addr{};
  14603. addr.sin_family = AF_INET;
  14604. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14606. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14607. ::listen(srv, 1);
  14608. sockaddr_in cli_addr{};
  14609. socklen_t cli_len = sizeof(cli_addr);
  14610. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14611. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14612. std::string buf_all;
  14613. char buf[2048];
  14614. ssize_t n;
  14615. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14616. buf_all.append(buf, static_cast<size_t>(n));
  14617. size_t pos;
  14618. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14619. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14620. auto e = request_block.find("\r\n");
  14621. if (e != std::string::npos) {
  14622. auto request_line = request_block.substr(0, e);
  14623. std::string msg =
  14624. "CRLF injection detected in request line: '" + request_line + "'";
  14625. EXPECT_FALSE(true) << msg;
  14626. }
  14627. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14628. ::send(cli,
  14629. #ifdef _WIN32
  14630. static_cast<const char *>(resp.c_str()),
  14631. static_cast<int>(resp.size()),
  14632. #else
  14633. resp.c_str(), resp.size(),
  14634. #endif
  14635. 0);
  14636. buf_all.erase(0, pos + 4);
  14637. }
  14638. }
  14639. detail::close_socket(cli);
  14640. detail::close_socket(srv);
  14641. });
  14642. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14643. auto cli = Client("127.0.0.1", PORT + 1);
  14644. auto headers = Headers{
  14645. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14646. {"Connection", "keep-alive"}};
  14647. auto res = cli.Get("/hi", headers);
  14648. EXPECT_FALSE(res);
  14649. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14650. server_thread.join();
  14651. }
  14652. // A request rejected before any byte reaches the socket must fail right away
  14653. // instead of waiting for a response the server will never send.
  14654. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14655. // The kernel completes the TCP handshake from the listen backlog, so the
  14656. // client connects, but nothing ever reads, responds or closes.
  14657. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14658. default_socket_options(srv);
  14659. sockaddr_in addr{};
  14660. addr.sin_family = AF_INET;
  14661. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14662. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14663. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14664. ASSERT_EQ(0, ::listen(srv, 8));
  14665. auto cli = Client("127.0.0.1", PORT + 1);
  14666. cli.set_read_timeout(10, 0);
  14667. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14668. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14669. std::chrono::steady_clock::now() - start)
  14670. .count();
  14671. };
  14672. {
  14673. Request req;
  14674. req.method = "GE T";
  14675. req.path = "/";
  14676. auto start = std::chrono::steady_clock::now();
  14677. auto res = cli.send(req);
  14678. EXPECT_FALSE(res);
  14679. EXPECT_EQ(Error::Write, res.error());
  14680. EXPECT_LT(elapsed_ms(start), 1000);
  14681. }
  14682. {
  14683. auto start = std::chrono::steady_clock::now();
  14684. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14685. EXPECT_FALSE(res);
  14686. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14687. EXPECT_LT(elapsed_ms(start), 1000);
  14688. }
  14689. EXPECT_FALSE(cli.is_socket_open());
  14690. detail::close_socket(srv);
  14691. }
  14692. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14693. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14694. default_socket_options(srv);
  14695. sockaddr_in addr{};
  14696. addr.sin_family = AF_INET;
  14697. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14698. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14699. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14700. ASSERT_EQ(0, ::listen(srv, 1));
  14701. std::string received;
  14702. auto server_thread = std::thread([&] {
  14703. auto sock = ::accept(srv, nullptr, nullptr);
  14704. if (sock == INVALID_SOCKET) { return; }
  14705. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14706. char buf[2048];
  14707. ssize_t n;
  14708. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14709. received.append(buf, static_cast<size_t>(n));
  14710. }
  14711. detail::close_socket(sock);
  14712. });
  14713. {
  14714. auto cli = Client("127.0.0.1", PORT + 1);
  14715. // "Z" sorts after the default headers, so writing straight to the socket
  14716. // would have sent the request line and those headers before the rejection.
  14717. auto handle =
  14718. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14719. EXPECT_FALSE(handle.is_valid());
  14720. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14721. }
  14722. server_thread.join();
  14723. detail::close_socket(srv);
  14724. EXPECT_TRUE(received.empty()) << received;
  14725. }
  14726. TEST(PathParamsTest, StaticMatch) {
  14727. const auto pattern = "/users/all";
  14728. detail::PathParamsMatcher matcher(pattern);
  14729. Request request;
  14730. request.path = "/users/all";
  14731. ASSERT_TRUE(matcher.match(request));
  14732. std::unordered_map<std::string, std::string> expected_params = {};
  14733. EXPECT_EQ(request.path_params, expected_params);
  14734. }
  14735. TEST(PathParamsTest, StaticMismatch) {
  14736. const auto pattern = "/users/all";
  14737. detail::PathParamsMatcher matcher(pattern);
  14738. Request request;
  14739. request.path = "/users/1";
  14740. ASSERT_FALSE(matcher.match(request));
  14741. }
  14742. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14743. const auto pattern = "/users/:id/subscriptions";
  14744. detail::PathParamsMatcher matcher(pattern);
  14745. Request request;
  14746. request.path = "/users/42/subscriptions";
  14747. ASSERT_TRUE(matcher.match(request));
  14748. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14749. EXPECT_EQ(request.path_params, expected_params);
  14750. }
  14751. TEST(PathParamsTest, SingleParamInTheEnd) {
  14752. const auto pattern = "/users/:id";
  14753. detail::PathParamsMatcher matcher(pattern);
  14754. Request request;
  14755. request.path = "/users/24";
  14756. ASSERT_TRUE(matcher.match(request));
  14757. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14758. EXPECT_EQ(request.path_params, expected_params);
  14759. }
  14760. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14761. const auto pattern = "/users/:id/";
  14762. detail::PathParamsMatcher matcher(pattern);
  14763. Request request;
  14764. request.path = "/users/42/";
  14765. ASSERT_TRUE(matcher.match(request));
  14766. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14767. EXPECT_EQ(request.path_params, expected_params);
  14768. }
  14769. TEST(PathParamsTest, EmptyParam) {
  14770. const auto pattern = "/users/:id/";
  14771. detail::PathParamsMatcher matcher(pattern);
  14772. Request request;
  14773. request.path = "/users//";
  14774. ASSERT_TRUE(matcher.match(request));
  14775. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14776. EXPECT_EQ(request.path_params, expected_params);
  14777. }
  14778. TEST(PathParamsTest, FragmentMismatch) {
  14779. const auto pattern = "/users/:id/";
  14780. detail::PathParamsMatcher matcher(pattern);
  14781. Request request;
  14782. request.path = "/admins/24/";
  14783. ASSERT_FALSE(matcher.match(request));
  14784. }
  14785. TEST(PathParamsTest, ExtraFragments) {
  14786. const auto pattern = "/users/:id";
  14787. detail::PathParamsMatcher matcher(pattern);
  14788. Request request;
  14789. request.path = "/users/42/subscriptions";
  14790. ASSERT_FALSE(matcher.match(request));
  14791. }
  14792. TEST(PathParamsTest, MissingTrailingParam) {
  14793. const auto pattern = "/users/:id";
  14794. detail::PathParamsMatcher matcher(pattern);
  14795. Request request;
  14796. request.path = "/users";
  14797. ASSERT_FALSE(matcher.match(request));
  14798. }
  14799. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14800. const auto pattern = "/users/:id/subscriptions";
  14801. detail::PathParamsMatcher matcher(pattern);
  14802. Request request;
  14803. request.path = "/users/subscriptions";
  14804. ASSERT_FALSE(matcher.match(request));
  14805. }
  14806. TEST(PathParamsTest, MultipleParams) {
  14807. const auto pattern = "/users/:userid/subscriptions/:subid";
  14808. detail::PathParamsMatcher matcher(pattern);
  14809. Request request;
  14810. request.path = "/users/42/subscriptions/2";
  14811. ASSERT_TRUE(matcher.match(request));
  14812. std::unordered_map<std::string, std::string> expected_params = {
  14813. {"userid", "42"}, {"subid", "2"}};
  14814. EXPECT_EQ(request.path_params, expected_params);
  14815. }
  14816. TEST(PathParamsTest, SequenceOfParams) {
  14817. const auto pattern = "/values/:x/:y/:z";
  14818. detail::PathParamsMatcher matcher(pattern);
  14819. Request request;
  14820. request.path = "/values/1/2/3";
  14821. ASSERT_TRUE(matcher.match(request));
  14822. std::unordered_map<std::string, std::string> expected_params = {
  14823. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14824. EXPECT_EQ(request.path_params, expected_params);
  14825. }
  14826. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14827. const auto pattern = "/prefix:suffix";
  14828. detail::PathParamsMatcher matcher(pattern);
  14829. Request request;
  14830. request.path = "/prefix:suffix";
  14831. ASSERT_TRUE(matcher.match(request));
  14832. const std::unordered_map<std::string, std::string> expected_params = {};
  14833. EXPECT_EQ(request.path_params, expected_params);
  14834. }
  14835. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14836. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14837. // calling thread's stack on a long enough path for a quantified pattern;
  14838. // RegexMatcher must refuse to run regex matching on paths beyond
  14839. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14840. detail::RegexMatcher matcher("/files/(.*)");
  14841. Request within_limit;
  14842. within_limit.path = "/files/" + std::string(10, 'A');
  14843. EXPECT_TRUE(matcher.match(within_limit));
  14844. Request over_limit;
  14845. over_limit.path =
  14846. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14847. EXPECT_FALSE(matcher.match(over_limit));
  14848. }
  14849. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14850. Server svr;
  14851. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14852. res.set_content("ok", "text/plain");
  14853. });
  14854. auto port = svr.bind_to_any_port(HOST);
  14855. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14856. auto se = detail::scope_exit([&] {
  14857. svr.stop();
  14858. thread.join();
  14859. ASSERT_FALSE(svr.is_running());
  14860. });
  14861. svr.wait_until_ready();
  14862. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14863. // request URI limit; this used to be able to crash the process.
  14864. std::string path =
  14865. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14866. std::string req = "GET " + path +
  14867. " HTTP/1.1\r\n"
  14868. "Host: " +
  14869. std::string(HOST) + ":" + std::to_string(port) +
  14870. "\r\n"
  14871. "Connection: close\r\n"
  14872. "\r\n";
  14873. std::string response;
  14874. ASSERT_TRUE(send_request(5, req, &response, port));
  14875. EXPECT_NE(std::string::npos, response.find("404"));
  14876. }
  14877. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14878. Server svr;
  14879. auto handler = [](const Request & /*req*/, Response &res) {
  14880. res.set_content("hit", "text/plain");
  14881. };
  14882. // No regex metacharacter, so this one is compared literally
  14883. svr.Get("/literal/route", handler);
  14884. // '.' is a regex metacharacter, so this one must keep regex semantics
  14885. svr.Get("/a.c", handler);
  14886. auto port = svr.bind_to_any_port(HOST);
  14887. std::thread t([&]() { svr.listen_after_bind(); });
  14888. auto se = detail::scope_exit([&] {
  14889. svr.stop();
  14890. t.join();
  14891. ASSERT_FALSE(svr.is_running());
  14892. });
  14893. svr.wait_until_ready();
  14894. Client cli(HOST, port);
  14895. struct {
  14896. const char *path;
  14897. int status;
  14898. } cases[] = {
  14899. {"/literal/route", StatusCode::OK_200},
  14900. {"/literal/routes", StatusCode::NotFound_404},
  14901. {"/literal/rout", StatusCode::NotFound_404},
  14902. {"/abc", StatusCode::OK_200},
  14903. {"/a.c", StatusCode::OK_200},
  14904. };
  14905. for (const auto &x : cases) {
  14906. auto res = cli.Get(x.path);
  14907. ASSERT_TRUE(res) << x.path;
  14908. EXPECT_EQ(x.status, res->status) << x.path;
  14909. }
  14910. }
  14911. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14912. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14913. // from exhausting the stack, so it must only constrain routes that actually
  14914. // run a regular expression. A literal route is matched by comparison and
  14915. // stays usable at any length.
  14916. Server svr;
  14917. const std::string pattern =
  14918. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14919. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14920. res.set_content("hit", "text/plain");
  14921. });
  14922. auto port = svr.bind_to_any_port(HOST);
  14923. std::thread t([&]() { svr.listen_after_bind(); });
  14924. auto se = detail::scope_exit([&] {
  14925. svr.stop();
  14926. t.join();
  14927. ASSERT_FALSE(svr.is_running());
  14928. });
  14929. svr.wait_until_ready();
  14930. Client cli(HOST, port);
  14931. auto res = cli.Get(pattern);
  14932. ASSERT_TRUE(res);
  14933. EXPECT_EQ(StatusCode::OK_200, res->status);
  14934. }
  14935. TEST(ParseUrlTest, VariousPatterns) {
  14936. {
  14937. detail::UrlComponents uc;
  14938. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14939. EXPECT_EQ("http", uc.scheme);
  14940. EXPECT_EQ("example.com", uc.host);
  14941. EXPECT_EQ("8080", uc.port);
  14942. EXPECT_EQ("/path", uc.path);
  14943. EXPECT_EQ("?q=1", uc.query);
  14944. }
  14945. {
  14946. detail::UrlComponents uc;
  14947. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14948. EXPECT_EQ("https", uc.scheme);
  14949. EXPECT_EQ("example.com", uc.host);
  14950. EXPECT_TRUE(uc.port.empty());
  14951. EXPECT_EQ("/path", uc.path);
  14952. }
  14953. {
  14954. detail::UrlComponents uc;
  14955. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14956. EXPECT_EQ("::1", uc.host);
  14957. EXPECT_EQ("8080", uc.port);
  14958. EXPECT_EQ("/path", uc.path);
  14959. }
  14960. {
  14961. detail::UrlComponents uc;
  14962. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14963. }
  14964. {
  14965. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14966. // the path while the connection still targets the bracketed host.
  14967. detail::UrlComponents uc;
  14968. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14969. }
  14970. {
  14971. detail::UrlComponents uc;
  14972. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14973. }
  14974. {
  14975. detail::UrlComponents uc;
  14976. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14977. EXPECT_EQ("::1", uc.host);
  14978. EXPECT_TRUE(uc.port.empty());
  14979. EXPECT_EQ("/path", uc.path);
  14980. }
  14981. {
  14982. detail::UrlComponents uc;
  14983. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14984. EXPECT_TRUE(uc.scheme.empty());
  14985. EXPECT_EQ("example.com", uc.host);
  14986. EXPECT_EQ("/path", uc.path);
  14987. EXPECT_EQ("?q=1", uc.query);
  14988. }
  14989. {
  14990. detail::UrlComponents uc;
  14991. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14992. EXPECT_TRUE(uc.host.empty());
  14993. EXPECT_EQ("/path", uc.path);
  14994. EXPECT_EQ("?q=1", uc.query);
  14995. }
  14996. {
  14997. detail::UrlComponents uc;
  14998. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14999. EXPECT_EQ("example.com", uc.host);
  15000. EXPECT_EQ("8080", uc.port);
  15001. }
  15002. {
  15003. // Unix socket path — must not be parsed as host
  15004. detail::UrlComponents uc;
  15005. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15006. EXPECT_TRUE(uc.host.empty());
  15007. }
  15008. {
  15009. detail::UrlComponents uc;
  15010. ASSERT_TRUE(detail::parse_url("", uc));
  15011. EXPECT_TRUE(uc.host.empty());
  15012. EXPECT_TRUE(uc.path.empty());
  15013. }
  15014. {
  15015. detail::UrlComponents uc;
  15016. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15017. }
  15018. {
  15019. detail::UrlComponents uc;
  15020. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15021. }
  15022. {
  15023. // Accepted by parse_url; callers restrict to http/https
  15024. detail::UrlComponents uc;
  15025. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15026. EXPECT_EQ("ftp", uc.scheme);
  15027. }
  15028. {
  15029. detail::UrlComponents uc;
  15030. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15031. }
  15032. {
  15033. detail::UrlComponents uc;
  15034. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15035. }
  15036. }
  15037. TEST(ParseUrlTest, FragmentHandling) {
  15038. {
  15039. detail::UrlComponents uc;
  15040. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15041. EXPECT_EQ("/path", uc.path);
  15042. EXPECT_TRUE(uc.query.empty());
  15043. }
  15044. {
  15045. detail::UrlComponents uc;
  15046. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15047. EXPECT_TRUE(uc.path.empty());
  15048. EXPECT_TRUE(uc.query.empty());
  15049. }
  15050. }
  15051. TEST(ParseUrlTest, UserinfoHandling) {
  15052. // Userinfo with @ but no colon — host includes @
  15053. detail::UrlComponents uc;
  15054. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15055. EXPECT_EQ("user@host.com", uc.host);
  15056. EXPECT_EQ("/path", uc.path);
  15057. }
  15058. TEST(ParseUrlTest, IPv6EdgeCases) {
  15059. {
  15060. detail::UrlComponents uc;
  15061. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15062. EXPECT_TRUE(uc.scheme.empty());
  15063. EXPECT_EQ("::1", uc.host);
  15064. EXPECT_EQ("8080", uc.port);
  15065. }
  15066. {
  15067. // Zone ID '%25' is not in [a-fA-F0-9:]
  15068. detail::UrlComponents uc;
  15069. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15070. }
  15071. }
  15072. TEST(ParseUrlTest, SchemeEdgeCases) {
  15073. {
  15074. detail::UrlComponents uc;
  15075. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15076. }
  15077. {
  15078. detail::UrlComponents uc;
  15079. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15080. }
  15081. {
  15082. detail::UrlComponents uc;
  15083. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15084. }
  15085. }
  15086. TEST(ParseUrlTest, PortEdgeCases) {
  15087. {
  15088. detail::UrlComponents uc;
  15089. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15090. EXPECT_TRUE(uc.port.empty());
  15091. EXPECT_EQ("/path", uc.path);
  15092. }
  15093. {
  15094. // parse_url accepts any port string; validation is done by parse_port
  15095. detail::UrlComponents uc;
  15096. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15097. EXPECT_EQ("abc", uc.port);
  15098. }
  15099. }
  15100. TEST(ParseUrlTest, WebSocketPatterns) {
  15101. {
  15102. detail::UrlComponents uc;
  15103. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15104. EXPECT_EQ("ws", uc.scheme);
  15105. EXPECT_EQ("echo.example.com", uc.host);
  15106. EXPECT_EQ("8080", uc.port);
  15107. EXPECT_EQ("/ws", uc.path);
  15108. }
  15109. {
  15110. detail::UrlComponents uc;
  15111. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15112. EXPECT_EQ("wss", uc.scheme);
  15113. EXPECT_EQ("echo.example.com", uc.host);
  15114. EXPECT_TRUE(uc.port.empty());
  15115. EXPECT_EQ("/ws", uc.path);
  15116. }
  15117. }
  15118. TEST(ParseUrlTest, QueryOnly) {
  15119. detail::UrlComponents uc;
  15120. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15121. EXPECT_TRUE(uc.host.empty());
  15122. EXPECT_TRUE(uc.path.empty());
  15123. EXPECT_EQ("?q=1&r=2", uc.query);
  15124. }
  15125. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15126. detail::UrlComponents uc;
  15127. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15128. EXPECT_TRUE(uc.scheme.empty());
  15129. EXPECT_EQ("example.com", uc.host);
  15130. EXPECT_EQ("443", uc.port);
  15131. EXPECT_EQ("/path", uc.path);
  15132. }
  15133. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15134. // If ipv6 regex working, regex match codepath is taken.
  15135. // else port will default to 80 in Client impl
  15136. int clientImplMagicPort = 80;
  15137. int port = 4321;
  15138. // above ports must be different to avoid false negative
  15139. EXPECT_NE(clientImplMagicPort, port);
  15140. std::string ipV6TestURL = "http://[ff06::c3]";
  15141. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15142. CLIENT_PRIVATE_KEY_FILE);
  15143. EXPECT_EQ(cli.port(), port);
  15144. }
  15145. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15146. auto file_path = "./www/dir/index.html";
  15147. auto dir_path = "./www/dir";
  15148. detail::FileStat stat_file(file_path);
  15149. EXPECT_TRUE(stat_file.is_file());
  15150. EXPECT_FALSE(stat_file.is_dir());
  15151. detail::FileStat stat_dir(dir_path);
  15152. EXPECT_FALSE(stat_dir.is_file());
  15153. EXPECT_TRUE(stat_dir.is_dir());
  15154. }
  15155. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15156. // IPv4 with default HTTP port (80)
  15157. EXPECT_EQ("example.com",
  15158. detail::make_host_and_port_string("example.com", 80, false));
  15159. // IPv4 with default HTTPS port (443)
  15160. EXPECT_EQ("example.com",
  15161. detail::make_host_and_port_string("example.com", 443, true));
  15162. // IPv4 with non-default HTTP port
  15163. EXPECT_EQ("example.com:8080",
  15164. detail::make_host_and_port_string("example.com", 8080, false));
  15165. // IPv4 with non-default HTTPS port
  15166. EXPECT_EQ("example.com:8443",
  15167. detail::make_host_and_port_string("example.com", 8443, true));
  15168. // IPv6 with default HTTP port (80)
  15169. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15170. // IPv6 with default HTTPS port (443)
  15171. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15172. // IPv6 with non-default HTTP port
  15173. EXPECT_EQ("[::1]:8080",
  15174. detail::make_host_and_port_string("::1", 8080, false));
  15175. // IPv6 with non-default HTTPS port
  15176. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15177. // IPv6 full address with default port
  15178. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15179. detail::make_host_and_port_string(
  15180. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15181. // IPv6 full address with non-default port
  15182. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15183. detail::make_host_and_port_string(
  15184. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15185. // IPv6 localhost with non-default port
  15186. EXPECT_EQ("[::1]:3000",
  15187. detail::make_host_and_port_string("::1", 3000, false));
  15188. // IPv6 with zone ID (link-local address) with default port
  15189. EXPECT_EQ("[fe80::1%eth0]",
  15190. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15191. // IPv6 with zone ID (link-local address) with non-default port
  15192. EXPECT_EQ("[fe80::1%eth0]:8080",
  15193. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15194. // Edge case: Port 443 with is_ssl=false (should add port)
  15195. EXPECT_EQ("example.com:443",
  15196. detail::make_host_and_port_string("example.com", 443, false));
  15197. // Edge case: Port 80 with is_ssl=true (should add port)
  15198. EXPECT_EQ("example.com:80",
  15199. detail::make_host_and_port_string("example.com", 80, true));
  15200. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15201. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15202. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15203. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15204. // Security fix: Already bracketed IPv6 should not get double brackets
  15205. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15206. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15207. EXPECT_EQ("[::1]:8080",
  15208. detail::make_host_and_port_string("[::1]", 8080, false));
  15209. EXPECT_EQ("[2001:db8::1]:8080",
  15210. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15211. EXPECT_EQ("[fe80::1%eth0]",
  15212. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15213. EXPECT_EQ("[fe80::1%eth0]:8080",
  15214. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15215. // Edge case: Empty host (should return as-is)
  15216. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15217. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15218. // This is a known limitation but shouldn't crash
  15219. EXPECT_EQ("[host:name]",
  15220. detail::make_host_and_port_string("host:name", 80, false));
  15221. // Port number edge cases (no validation, but should not crash)
  15222. EXPECT_EQ("example.com:0",
  15223. detail::make_host_and_port_string("example.com", 0, false));
  15224. EXPECT_EQ("example.com:-1",
  15225. detail::make_host_and_port_string("example.com", -1, false));
  15226. EXPECT_EQ("example.com:65535",
  15227. detail::make_host_and_port_string("example.com", 65535, false));
  15228. EXPECT_EQ("example.com:65536",
  15229. detail::make_host_and_port_string("example.com", 65536, false));
  15230. }
  15231. #ifdef CPPHTTPLIB_SSL_ENABLED
  15232. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15233. httplib::SSLClient cli("roblox.com", 443);
  15234. cli.set_follow_location(true);
  15235. auto res = cli.Get("/");
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. EXPECT_EQ(StatusCode::OK_200, res->status);
  15238. }
  15239. #endif
  15240. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15241. Server svr;
  15242. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15243. EXPECT_EQ(res.status, 400);
  15244. });
  15245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15246. auto se = detail::scope_exit([&] {
  15247. svr.stop();
  15248. thread.join();
  15249. ASSERT_FALSE(svr.is_running());
  15250. });
  15251. svr.wait_until_ready();
  15252. Client cli(HOST, PORT);
  15253. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15254. }
  15255. TEST(InvalidHeaderCharsTest, is_field_name) {
  15256. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15257. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15258. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15259. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15260. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15261. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15262. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15263. EXPECT_FALSE(detail::fields::is_field_name(""));
  15264. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15265. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15266. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15267. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15268. }
  15269. TEST(InvalidHeaderCharsTest, is_field_value) {
  15270. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15271. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15272. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15273. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15274. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15275. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15276. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15277. EXPECT_TRUE(detail::fields::is_field_value(""));
  15278. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15279. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15280. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15281. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15282. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15283. }
  15284. TEST(InvalidHeaderCharsTest, OnServer) {
  15285. Server svr;
  15286. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15287. std::string header = "Not Set";
  15288. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15289. res.set_header(header, "value");
  15290. res.set_content("Page Content Page Content", "text/plain");
  15291. });
  15292. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15293. std::string header = "Not Set";
  15294. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15295. res.set_header("X-Test", header);
  15296. res.set_content("Page Content Page Content", "text/plain");
  15297. });
  15298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15299. auto se = detail::scope_exit([&] {
  15300. svr.stop();
  15301. thread.join();
  15302. ASSERT_FALSE(svr.is_running());
  15303. });
  15304. svr.wait_until_ready();
  15305. Client cli(HOST, PORT);
  15306. {
  15307. auto res = cli.Get(
  15308. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15310. EXPECT_EQ("Page Content Page Content", res->body);
  15311. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15312. }
  15313. {
  15314. auto res = cli.Get(
  15315. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15317. EXPECT_EQ("Page Content Page Content", res->body);
  15318. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15319. }
  15320. }
  15321. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15322. auto handled = false;
  15323. Server svr;
  15324. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15325. thread t = thread([&] { svr.listen(HOST, PORT); });
  15326. auto se = detail::scope_exit([&] {
  15327. svr.stop();
  15328. t.join();
  15329. ASSERT_FALSE(svr.is_running());
  15330. ASSERT_FALSE(handled);
  15331. });
  15332. svr.wait_until_ready();
  15333. auto req = "POST /test HTTP/1.1\r\n"
  15334. "Content-Length: x\r\n"
  15335. "\r\n";
  15336. std::string response;
  15337. ASSERT_TRUE(send_request(1, req, &response));
  15338. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15339. response.substr(0, response.find("\r\n")));
  15340. }
  15341. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15342. // case-insensitive, and a server that receives a 100-continue expectation in
  15343. // an HTTP/1.0 request MUST ignore it.
  15344. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15345. std::string response;
  15346. ASSERT_TRUE(send_request(1, req, &response, port));
  15347. *got_100 = response.find("100 Continue") != std::string::npos;
  15348. }
  15349. class ExpectTokenTest : public ::testing::Test {
  15350. protected:
  15351. void SetUp() override {
  15352. svr_.Post("/p", [](const Request &, Response &res) {
  15353. res.set_content("ok", "text/plain");
  15354. });
  15355. port_ = svr_.bind_to_any_port(HOST);
  15356. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15357. svr_.wait_until_ready();
  15358. }
  15359. void TearDown() override {
  15360. svr_.stop();
  15361. if (thread_.joinable()) { thread_.join(); }
  15362. }
  15363. std::string request(const char *version, const char *expect_value) const {
  15364. return std::string("POST /p ") + version +
  15365. "\r\n"
  15366. "Host: localhost\r\n"
  15367. "Content-Length: 2\r\n"
  15368. "Connection: close\r\n"
  15369. "Expect: " +
  15370. expect_value +
  15371. "\r\n"
  15372. "\r\n"
  15373. "hi";
  15374. }
  15375. Server svr_;
  15376. int port_ = 0;
  15377. thread thread_;
  15378. };
  15379. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15380. bool got_100 = false;
  15381. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15382. EXPECT_TRUE(got_100);
  15383. }
  15384. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15385. bool got_100 = true;
  15386. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15387. EXPECT_FALSE(got_100);
  15388. }
  15389. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15390. bool got_100 = false;
  15391. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15392. EXPECT_TRUE(got_100);
  15393. }
  15394. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15395. bool got_100 = false;
  15396. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15397. EXPECT_TRUE(got_100);
  15398. }
  15399. // `100 Continue` is sent only when the server starts reading the body, so a
  15400. // request rejected before that never invites the client to send it. The
  15401. // requests below carry the expectation but withhold the body, as a client
  15402. // waiting for `100 Continue` would.
  15403. // A POST that expects `100 Continue` and withholds its two-byte body.
  15404. static std::string expect_headers_only(const std::string &path) {
  15405. return "POST " + path +
  15406. " HTTP/1.1\r\n"
  15407. "Host: localhost\r\n"
  15408. "Content-Length: 2\r\n"
  15409. "Expect: 100-continue\r\n"
  15410. "\r\n";
  15411. }
  15412. class ExpectLazyContinueTest : public ::testing::Test {
  15413. protected:
  15414. void SetUp() override {
  15415. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15416. if (req.path == "/pre-routing") {
  15417. res.status = StatusCode::Unauthorized_401;
  15418. return Server::HandlerResponse::Handled;
  15419. }
  15420. return Server::HandlerResponse::Unhandled;
  15421. });
  15422. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15423. if (req.matched_route == "/pre-request") {
  15424. res.status = StatusCode::Forbidden_403;
  15425. return Server::HandlerResponse::Handled;
  15426. }
  15427. return Server::HandlerResponse::Unhandled;
  15428. });
  15429. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15430. res.set_content("ok", "text/plain");
  15431. });
  15432. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15433. res.set_content("ok", "text/plain");
  15434. });
  15435. svr_.Post("/reader-used", [](const Request &, Response &res,
  15436. const ContentReader &content_reader) {
  15437. std::string body;
  15438. content_reader([&](const char *data, size_t len) {
  15439. body.append(data, len);
  15440. return true;
  15441. });
  15442. res.set_content(body, "text/plain");
  15443. });
  15444. svr_.Post("/reader-unused",
  15445. [](const Request &, Response &res, const ContentReader &) {
  15446. res.set_content("ignored", "text/plain");
  15447. });
  15448. port_ = svr_.bind_to_any_port(HOST);
  15449. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15450. svr_.wait_until_ready();
  15451. }
  15452. void TearDown() override {
  15453. svr_.stop();
  15454. if (thread_.joinable()) { thread_.join(); }
  15455. }
  15456. // Sends `req` and reads until the server closes the connection. Returns
  15457. // false if the read had to wait for the client-side timeout instead.
  15458. bool send_until_closed(const std::string &req, std::string *resp) const {
  15459. auto start = std::chrono::steady_clock::now();
  15460. if (!send_request(3, req, resp, port_)) { return false; }
  15461. auto elapsed = std::chrono::steady_clock::now() - start;
  15462. return elapsed < std::chrono::seconds(2);
  15463. }
  15464. // The final response comes without `100 Continue`, and the server closes
  15465. // the connection since the body may or may not follow.
  15466. void expect_final_without_interim(const std::string &path,
  15467. const char *status_line) const {
  15468. std::string resp;
  15469. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15470. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15471. EXPECT_EQ(0u, resp.find(status_line));
  15472. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15473. }
  15474. Server svr_;
  15475. int port_ = 0;
  15476. thread thread_;
  15477. };
  15478. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15479. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15480. }
  15481. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15482. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15483. }
  15484. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15485. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15486. }
  15487. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15488. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15489. }
  15490. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15491. // The body follows once `100 Continue` has had time to arrive.
  15492. auto req = expect_headers_only("/reader-used");
  15493. req.insert(req.size() - 2, "Connection: close\r\n");
  15494. std::string resp;
  15495. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15496. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15497. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15498. EXPECT_NE(std::string::npos, resp.find("hi"));
  15499. }
  15500. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15501. // Large enough for the client to add `Expect: 100-continue` itself.
  15502. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15503. std::atomic<bool> body_sent{false};
  15504. Client cli(HOST, port_);
  15505. auto res = cli.Post(
  15506. "/pre-request", length,
  15507. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15508. body_sent = true;
  15509. std::string chunk(len, 'x');
  15510. sink.write(chunk.data(), chunk.size());
  15511. return true;
  15512. },
  15513. "application/octet-stream");
  15514. ASSERT_TRUE(res);
  15515. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15516. EXPECT_FALSE(body_sent);
  15517. }
  15518. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15519. Server svr;
  15520. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15521. return StatusCode::ExpectationFailed_417;
  15522. });
  15523. svr.Post("/p", [](const Request &, Response &res) {
  15524. res.set_content("ok", "text/plain");
  15525. });
  15526. auto port = svr.bind_to_any_port(HOST);
  15527. thread t = thread([&] { svr.listen_after_bind(); });
  15528. auto se = detail::scope_exit([&] {
  15529. svr.stop();
  15530. t.join();
  15531. });
  15532. svr.wait_until_ready();
  15533. std::string resp;
  15534. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15535. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15536. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15537. // Exactly one response: the route handler must not run after the 417.
  15538. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15539. }
  15540. #ifndef _WIN32
  15541. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15542. static constexpr char reject[] = "Unauthorized";
  15543. static constexpr char accept[] = "Upload accepted";
  15544. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15545. Server svr;
  15546. svr.set_expect_100_continue_handler(
  15547. [](const Request & /*req*/, Response &res) {
  15548. res.status = StatusCode::Unauthorized_401;
  15549. res.set_content(reject, "text/plain");
  15550. return res.status;
  15551. });
  15552. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15553. res.set_content(accept, "text/plain");
  15554. });
  15555. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15556. auto se = detail::scope_exit([&] {
  15557. svr.stop();
  15558. thread.join();
  15559. ASSERT_FALSE(svr.is_running());
  15560. });
  15561. svr.wait_until_ready();
  15562. {
  15563. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15564. curl_easy_init(), &curl_easy_cleanup};
  15565. ASSERT_NE(curl, nullptr);
  15566. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15567. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15568. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15569. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15570. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15571. &curl_slist_free_all};
  15572. ASSERT_NE(list, nullptr);
  15573. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15574. struct read_data {
  15575. size_t read_size;
  15576. size_t total_size;
  15577. } data = {0, total_size};
  15578. using read_callback_t =
  15579. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15580. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15581. void *userdata) -> size_t {
  15582. read_data *d = (read_data *)userdata;
  15583. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15584. std::fill_n(ptr, size * nmemb, 'A');
  15585. d->read_size += size * nmemb;
  15586. return size * nmemb;
  15587. };
  15588. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15589. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15590. std::vector<char> buffer;
  15591. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15592. using write_callback_t =
  15593. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15594. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15595. void *userdata) -> size_t {
  15596. std::vector<char> *buf = (std::vector<char> *)userdata;
  15597. buf->reserve(buf->size() + size * nmemb + 1);
  15598. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15599. return size * nmemb;
  15600. };
  15601. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15602. {
  15603. const auto res = curl_easy_perform(curl.get());
  15604. ASSERT_EQ(res, CURLE_OK);
  15605. }
  15606. {
  15607. auto response_code = long{};
  15608. const auto res =
  15609. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15610. ASSERT_EQ(res, CURLE_OK);
  15611. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15612. }
  15613. {
  15614. auto dl = curl_off_t{};
  15615. const auto res =
  15616. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15617. ASSERT_EQ(res, CURLE_OK);
  15618. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15619. }
  15620. {
  15621. buffer.push_back('\0');
  15622. ASSERT_STRCASEEQ(buffer.data(), reject);
  15623. }
  15624. }
  15625. }
  15626. #endif
  15627. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15628. // Regression test for #2458.
  15629. //
  15630. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15631. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15632. // ticket can make the client socket spuriously readable during the
  15633. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15634. // the client withholds the body and then blocks reading a response that never
  15635. // comes, failing with `Failed to read connection`.
  15636. //
  15637. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15638. // within the timeout. This raw OpenSSL server deliberately never sends
  15639. // `100 Continue`; the client must still deliver the body and receive 200.
  15640. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15641. signal(SIGPIPE, SIG_IGN);
  15642. const auto port = PORT + 4;
  15643. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15644. ASSERT_NE(srv, INVALID_SOCKET);
  15645. int opt = 1;
  15646. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15647. sockaddr_in addr{};
  15648. addr.sin_family = AF_INET;
  15649. addr.sin_port = htons(static_cast<uint16_t>(port));
  15650. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15651. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15652. ASSERT_EQ(0, ::listen(srv, 1));
  15653. std::atomic<size_t> server_body_bytes{0};
  15654. auto server_thread = std::thread([&] {
  15655. sockaddr_in cli_addr{};
  15656. socklen_t cli_len = sizeof(cli_addr);
  15657. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15658. if (cli == INVALID_SOCKET) { return; }
  15659. // Bound the lifetime of the server side so a buggy client (which never
  15660. // sends the body) cannot make this thread block forever on join.
  15661. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15662. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15663. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15664. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15665. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15666. SSL *ssl = SSL_new(ctx);
  15667. SSL_set_fd(ssl, static_cast<int>(cli));
  15668. if (SSL_accept(ssl) > 0) {
  15669. // Read the request headers. Reading here also flushes the TLS 1.3
  15670. // session tickets to the client. Deliberately do NOT send
  15671. // `100 Continue`.
  15672. std::string buf;
  15673. char tmp[1024];
  15674. while (buf.find("\r\n\r\n") == std::string::npos) {
  15675. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15676. if (n <= 0) { break; }
  15677. buf.append(tmp, static_cast<size_t>(n));
  15678. }
  15679. // A correct client sends the body now; count what arrives.
  15680. auto pos = buf.find("\r\n\r\n");
  15681. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15682. while (body < 4096) {
  15683. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15684. if (n <= 0) { break; }
  15685. body += static_cast<size_t>(n);
  15686. }
  15687. server_body_bytes = body;
  15688. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15689. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15690. SSL_shutdown(ssl);
  15691. }
  15692. SSL_free(ssl);
  15693. detail::close_socket(cli);
  15694. SSL_CTX_free(ctx);
  15695. });
  15696. auto se = detail::scope_exit([&] {
  15697. server_thread.join();
  15698. detail::close_socket(srv);
  15699. });
  15700. SSLClient cli("127.0.0.1", port);
  15701. cli.enable_server_certificate_verification(false);
  15702. cli.set_connection_timeout(5, 0);
  15703. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15704. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15705. std::string body(4096, 'A');
  15706. auto res = cli.Put("/api/test", body, "application/json");
  15707. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15708. EXPECT_EQ(StatusCode::OK_200, res->status);
  15709. EXPECT_EQ(body.size(), server_body_bytes.load());
  15710. }
  15711. #endif
  15712. template <typename S, typename C>
  15713. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15714. svr.Get("/stream", [&](const Request &, Response &res) {
  15715. auto data = new std::string("01234567890123456789");
  15716. res.set_content_provider(
  15717. data->size(), "text/plain",
  15718. [&, data](size_t offset, size_t length, DataSink &sink) {
  15719. const size_t DATA_CHUNK_SIZE = 4;
  15720. const auto &d = *data;
  15721. std::this_thread::sleep_for(std::chrono::seconds(1));
  15722. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15723. return true;
  15724. },
  15725. [data](bool success) {
  15726. EXPECT_FALSE(success);
  15727. delete data;
  15728. });
  15729. });
  15730. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15731. auto i = new size_t(0);
  15732. res.set_content_provider(
  15733. "text/plain",
  15734. [i](size_t, DataSink &sink) {
  15735. if (*i < 5) {
  15736. std::this_thread::sleep_for(std::chrono::seconds(1));
  15737. sink.write("abcd", 4);
  15738. (*i)++;
  15739. } else {
  15740. sink.done();
  15741. }
  15742. return true;
  15743. },
  15744. [i](bool success) {
  15745. EXPECT_FALSE(success);
  15746. delete i;
  15747. });
  15748. });
  15749. svr.Get("/chunked", [&](const Request &, Response &res) {
  15750. auto i = new size_t(0);
  15751. res.set_chunked_content_provider(
  15752. "text/plain",
  15753. [i](size_t, DataSink &sink) {
  15754. if (*i < 5) {
  15755. std::this_thread::sleep_for(std::chrono::seconds(1));
  15756. sink.os << "abcd";
  15757. (*i)++;
  15758. } else {
  15759. sink.done();
  15760. }
  15761. return true;
  15762. },
  15763. [i](bool success) {
  15764. EXPECT_FALSE(success);
  15765. delete i;
  15766. });
  15767. });
  15768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15769. auto se = detail::scope_exit([&] {
  15770. svr.stop();
  15771. listen_thread.join();
  15772. ASSERT_FALSE(svr.is_running());
  15773. });
  15774. svr.wait_until_ready();
  15775. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15776. {
  15777. auto start = std::chrono::steady_clock::now();
  15778. auto res = cli.Get("/stream");
  15779. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15780. std::chrono::steady_clock::now() - start)
  15781. .count();
  15782. ASSERT_FALSE(res);
  15783. EXPECT_EQ(Error::Read, res.error());
  15784. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15785. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15786. }
  15787. {
  15788. auto start = std::chrono::steady_clock::now();
  15789. auto res = cli.Get("/stream_without_length");
  15790. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15791. std::chrono::steady_clock::now() - start)
  15792. .count();
  15793. ASSERT_FALSE(res);
  15794. EXPECT_EQ(Error::Read, res.error());
  15795. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15796. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15797. }
  15798. {
  15799. auto start = std::chrono::steady_clock::now();
  15800. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15801. EXPECT_EQ("abcd", string(data, data_length));
  15802. return true;
  15803. });
  15804. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15805. std::chrono::steady_clock::now() - start)
  15806. .count();
  15807. ASSERT_FALSE(res);
  15808. EXPECT_EQ(Error::Read, res.error());
  15809. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15810. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15811. }
  15812. }
  15813. TEST(MaxTimeoutTest, ContentStream) {
  15814. time_t timeout = 2000;
  15815. time_t threshold = 200;
  15816. Server svr;
  15817. Client cli("localhost", PORT);
  15818. max_timeout_test(svr, cli, timeout, threshold);
  15819. }
  15820. #ifdef CPPHTTPLIB_SSL_ENABLED
  15821. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15822. time_t timeout = 2000;
  15823. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15825. SSLClient cli("localhost", PORT);
  15826. cli.enable_server_certificate_verification(false);
  15827. max_timeout_test(svr, cli, timeout, threshold);
  15828. }
  15829. #endif
  15830. class EventDispatcher {
  15831. public:
  15832. EventDispatcher() {}
  15833. bool wait_event(DataSink *sink) {
  15834. unique_lock<mutex> lk(m_);
  15835. int id = id_;
  15836. // Wait with timeout to prevent hanging if client disconnects
  15837. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15838. [&] { return cid_ == id; })) {
  15839. return false; // Timeout occurred
  15840. }
  15841. sink->write(message_.data(), message_.size());
  15842. return true;
  15843. }
  15844. void send_event(const string &message) {
  15845. lock_guard<mutex> lk(m_);
  15846. cid_ = id_++;
  15847. message_ = message;
  15848. cv_.notify_all();
  15849. }
  15850. private:
  15851. mutex m_;
  15852. condition_variable cv_;
  15853. atomic_int id_{0};
  15854. atomic_int cid_{-1};
  15855. string message_;
  15856. };
  15857. TEST(ClientInThreadTest, Issue2068) {
  15858. EventDispatcher ed;
  15859. Server svr;
  15860. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15861. res.set_chunked_content_provider("text/event-stream",
  15862. [&](size_t /*offset*/, DataSink &sink) {
  15863. return ed.wait_event(&sink);
  15864. });
  15865. });
  15866. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15867. svr.wait_until_ready();
  15868. thread event_thread([&] {
  15869. int id = 0;
  15870. while (svr.is_running()) {
  15871. this_thread::sleep_for(chrono::milliseconds(500));
  15872. std::stringstream ss;
  15873. ss << "data: " << id << "\n\n";
  15874. ed.send_event(ss.str());
  15875. id++;
  15876. }
  15877. });
  15878. auto se = detail::scope_exit([&] {
  15879. svr.stop();
  15880. listen_thread.join();
  15881. event_thread.join();
  15882. ASSERT_FALSE(svr.is_running());
  15883. });
  15884. {
  15885. auto client = detail::make_unique<Client>(HOST, PORT);
  15886. client->set_read_timeout(std::chrono::minutes(10));
  15887. std::atomic<bool> stop{false};
  15888. std::thread t([&] {
  15889. client->Get("/event1",
  15890. [&](const char *, size_t) -> bool { return !stop; });
  15891. });
  15892. std::this_thread::sleep_for(std::chrono::seconds(2));
  15893. stop = true;
  15894. client->stop();
  15895. t.join();
  15896. // Reset client after thread has finished
  15897. client.reset();
  15898. }
  15899. }
  15900. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15901. auto handled = false;
  15902. Server svr;
  15903. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15904. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15905. auto se = detail::scope_exit([&] {
  15906. svr.stop();
  15907. t.join();
  15908. ASSERT_FALSE(svr.is_running());
  15909. ASSERT_FALSE(handled);
  15910. });
  15911. svr.wait_until_ready();
  15912. // Two Content-Length headers with different values — must be rejected
  15913. auto req = "POST /test HTTP/1.1\r\n"
  15914. "Content-Length: 5\r\n"
  15915. "Content-Length: 10\r\n"
  15916. "\r\n"
  15917. "hello";
  15918. std::string response;
  15919. ASSERT_TRUE(send_request(1, req, &response));
  15920. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15921. response.substr(0, response.find("\r\n")));
  15922. }
  15923. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15924. auto handled = false;
  15925. Server svr;
  15926. svr.Post("/test", [&](const Request &, Response &res) {
  15927. handled = true;
  15928. res.set_content("ok", "text/plain");
  15929. });
  15930. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15931. auto se = detail::scope_exit([&] {
  15932. svr.stop();
  15933. t.join();
  15934. ASSERT_FALSE(svr.is_running());
  15935. ASSERT_TRUE(handled);
  15936. });
  15937. svr.wait_until_ready();
  15938. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15939. auto req = "POST /test HTTP/1.1\r\n"
  15940. "Content-Length: 5\r\n"
  15941. "Content-Length: 5\r\n"
  15942. "\r\n"
  15943. "hello";
  15944. std::string response;
  15945. ASSERT_TRUE(send_request(1, req, &response));
  15946. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15947. }
  15948. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15949. Server svr;
  15950. svr.Get("/", [](const Request &req, Response &res) {
  15951. EXPECT_EQ(2U, req.trailers.size());
  15952. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15953. // Denied
  15954. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15955. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15956. // Accepted
  15957. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15958. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15959. EXPECT_TRUE(req.has_trailer("X-World"));
  15960. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15961. res.set_content("ok", "text/plain");
  15962. });
  15963. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15964. auto se = detail::scope_exit([&] {
  15965. svr.stop();
  15966. t.join();
  15967. ASSERT_FALSE(svr.is_running());
  15968. });
  15969. svr.wait_until_ready();
  15970. const std::string req = "GET / HTTP/1.1\r\n"
  15971. "Transfer-Encoding: chunked\r\n"
  15972. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15973. "\r\n"
  15974. "0\r\n"
  15975. "Content-Length: 10\r\n"
  15976. "Host: internal.local\r\n"
  15977. "Content-Type: malicious/content\r\n"
  15978. "Cookie: any\r\n"
  15979. "Set-Cookie: any\r\n"
  15980. "X-Forwarded-For: attacker.com\r\n"
  15981. "X-Real-Ip: 1.1.1.1\r\n"
  15982. "X-Hello: hello\r\n"
  15983. "X-World: world\r\n"
  15984. "\r\n";
  15985. std::string res;
  15986. ASSERT_TRUE(send_request(1, req, &res));
  15987. }
  15988. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15989. // several field lines, and the combined value is what has to be parsed. A
  15990. // Trailer field split across lines therefore declares every name it lists;
  15991. // reading only the first line silently drops the trailers the later lines
  15992. // declare. The prohibited-trailer filter still applies to every line.
  15993. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15994. Server svr;
  15995. size_t observed_trailer_count = 0;
  15996. std::string observed_hello;
  15997. std::string observed_world;
  15998. bool observed_content_length = true;
  15999. svr.Get("/", [&](const Request &req, Response &res) {
  16000. observed_trailer_count = req.trailers.size();
  16001. observed_hello = req.get_trailer_value("X-Hello");
  16002. observed_world = req.get_trailer_value("X-World");
  16003. observed_content_length = req.has_trailer("Content-Length");
  16004. res.set_content("ok", "text/plain");
  16005. });
  16006. auto port = svr.bind_to_any_port(HOST);
  16007. thread t = thread([&]() { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. ASSERT_FALSE(svr.is_running());
  16012. });
  16013. svr.wait_until_ready();
  16014. const std::string req = "GET / HTTP/1.1\r\n"
  16015. "Transfer-Encoding: chunked\r\n"
  16016. "Trailer: X-Hello\r\n"
  16017. "Trailer: X-World, Content-Length\r\n"
  16018. "\r\n"
  16019. "0\r\n"
  16020. "X-Hello: hello\r\n"
  16021. "X-World: world\r\n"
  16022. "Content-Length: 10\r\n"
  16023. "\r\n";
  16024. std::string res;
  16025. ASSERT_TRUE(send_request(1, req, &res, port));
  16026. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16027. // Accepted: both field lines contribute to the declared set
  16028. EXPECT_EQ(2U, observed_trailer_count);
  16029. EXPECT_EQ(observed_hello, "hello");
  16030. EXPECT_EQ(observed_world, "world");
  16031. // Denied: a prohibited name stays prohibited on a later field line
  16032. EXPECT_FALSE(observed_content_length);
  16033. }
  16034. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16035. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16036. // unbounded run of fields that are never declared, because the counter would
  16037. // only advance for declared fields.
  16038. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16039. Server svr;
  16040. bool handler_called = false;
  16041. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16042. handler_called = true;
  16043. res.set_content("ok", "text/plain");
  16044. });
  16045. auto port = svr.bind_to_any_port(HOST);
  16046. thread t = thread([&]() { svr.listen_after_bind(); });
  16047. auto se = detail::scope_exit([&] {
  16048. svr.stop();
  16049. t.join();
  16050. ASSERT_FALSE(svr.is_running());
  16051. });
  16052. svr.wait_until_ready();
  16053. // Declare nothing, then send far more undeclared trailer fields than the
  16054. // header-count limit. Parsing must stop and reject the request rather than
  16055. // read every line.
  16056. std::string req = "GET / HTTP/1.1\r\n"
  16057. "Transfer-Encoding: chunked\r\n"
  16058. "\r\n"
  16059. "0\r\n";
  16060. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16061. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16062. }
  16063. req += "\r\n";
  16064. std::string res;
  16065. ASSERT_TRUE(send_request(1, req, &res, port));
  16066. // The request is rejected before the handler runs.
  16067. EXPECT_FALSE(handler_called);
  16068. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16069. }
  16070. // The set of declared trailer names is capped so a peer cannot grow it without
  16071. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16072. // declared past the cap is not honored, even if the field is actually sent.
  16073. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16074. Server svr;
  16075. // One name inside the cap and one past it, so the test tracks the cap rather
  16076. // than a fixed count.
  16077. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16078. const std::string within_cap_name = "X-T-0";
  16079. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16080. bool observed_within_cap = false;
  16081. bool observed_past_cap = false;
  16082. svr.Get("/", [&](const Request &req, Response &res) {
  16083. observed_within_cap = req.has_trailer(within_cap_name);
  16084. observed_past_cap = req.has_trailer(past_cap_name);
  16085. res.set_content("ok", "text/plain");
  16086. });
  16087. auto port = svr.bind_to_any_port(HOST);
  16088. thread t = thread([&]() { svr.listen_after_bind(); });
  16089. auto se = detail::scope_exit([&] {
  16090. svr.stop();
  16091. t.join();
  16092. ASSERT_FALSE(svr.is_running());
  16093. });
  16094. svr.wait_until_ready();
  16095. // Declare more trailer names than the cap in a single Trailer field, then
  16096. // actually send the first (within the cap) and the last (past it).
  16097. std::string trailer_decl = "Trailer: ";
  16098. for (int i = 0; i < declared_count; i++) {
  16099. if (i != 0) { trailer_decl += ", "; }
  16100. trailer_decl += "X-T-" + std::to_string(i);
  16101. }
  16102. trailer_decl += "\r\n";
  16103. const std::string req = "GET / HTTP/1.1\r\n"
  16104. "Transfer-Encoding: chunked\r\n" +
  16105. trailer_decl +
  16106. "\r\n"
  16107. "0\r\n" +
  16108. within_cap_name + ": a\r\n" + past_cap_name +
  16109. ": b\r\n"
  16110. "\r\n";
  16111. std::string res;
  16112. ASSERT_TRUE(send_request(1, req, &res, port));
  16113. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16114. // A name within the cap is honored; one declared past the cap is dropped.
  16115. EXPECT_TRUE(observed_within_cap);
  16116. EXPECT_FALSE(observed_past_cap);
  16117. }
  16118. // A direct client that is not listed in trusted_proxies must not be able to
  16119. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16120. // the peer address on the actual TCP connection determines whether the
  16121. // header is honored.
  16122. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16123. Server svr;
  16124. // Deliberately does NOT include the loopback address the test client
  16125. // actually connects from, so the direct connection is not a trusted proxy.
  16126. svr.set_trusted_proxies({"203.0.113.66"});
  16127. std::string observed_remote_addr;
  16128. svr.Get("/ip", [&](const Request &req, Response &res) {
  16129. observed_remote_addr = req.remote_addr;
  16130. res.set_content("ok", "text/plain");
  16131. });
  16132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16133. auto se = detail::scope_exit([&] {
  16134. svr.stop();
  16135. t.join();
  16136. ASSERT_FALSE(svr.is_running());
  16137. });
  16138. svr.wait_until_ready();
  16139. Client cli(HOST, PORT);
  16140. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16142. EXPECT_EQ(StatusCode::OK_200, res->status);
  16143. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16144. // ignored entirely and the real connection-level address retained.
  16145. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16146. observed_remote_addr == "127.0.0.1");
  16147. }
  16148. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16149. Server svr;
  16150. std::string observed_remote_addr;
  16151. std::string observed_xff;
  16152. svr.Get("/ip", [&](const Request &req, Response &res) {
  16153. observed_remote_addr = req.remote_addr;
  16154. observed_xff = req.get_header_value("X-Forwarded-For");
  16155. res.set_content("ok", "text/plain");
  16156. });
  16157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16158. auto se = detail::scope_exit([&] {
  16159. svr.stop();
  16160. t.join();
  16161. ASSERT_FALSE(svr.is_running());
  16162. });
  16163. svr.wait_until_ready();
  16164. Client cli(HOST, PORT);
  16165. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16167. EXPECT_EQ(StatusCode::OK_200, res->status);
  16168. EXPECT_EQ(observed_xff, "203.0.113.66");
  16169. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16170. observed_remote_addr == "127.0.0.1");
  16171. }
  16172. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16173. Server svr;
  16174. svr.set_trusted_proxies({"203.0.113.66"});
  16175. std::string observed_remote_addr;
  16176. std::string observed_xff;
  16177. svr.Get("/ip", [&](const Request &req, Response &res) {
  16178. observed_remote_addr = req.remote_addr;
  16179. observed_xff = req.get_header_value("X-Forwarded-For");
  16180. res.set_content("ok", "text/plain");
  16181. });
  16182. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16183. auto se = detail::scope_exit([&] {
  16184. svr.stop();
  16185. t.join();
  16186. ASSERT_FALSE(svr.is_running());
  16187. });
  16188. svr.wait_until_ready();
  16189. Client cli(HOST, PORT);
  16190. auto res = cli.Get("/ip");
  16191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16192. EXPECT_EQ(StatusCode::OK_200, res->status);
  16193. EXPECT_EQ(observed_xff, "");
  16194. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16195. observed_remote_addr == "127.0.0.1");
  16196. }
  16197. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16198. Server svr;
  16199. // Include the loopback address the test client actually connects from, so
  16200. // the direct connection itself is recognized as the trusted proxy hop.
  16201. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16202. std::string observed_remote_addr;
  16203. std::string observed_xff;
  16204. svr.Get("/ip", [&](const Request &req, Response &res) {
  16205. observed_remote_addr = req.remote_addr;
  16206. observed_xff = req.get_header_value("X-Forwarded-For");
  16207. res.set_content("ok", "text/plain");
  16208. });
  16209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16210. auto se = detail::scope_exit([&] {
  16211. svr.stop();
  16212. t.join();
  16213. ASSERT_FALSE(svr.is_running());
  16214. });
  16215. svr.wait_until_ready();
  16216. Client cli(HOST, PORT);
  16217. auto res = cli.Get(
  16218. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16220. EXPECT_EQ(StatusCode::OK_200, res->status);
  16221. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16222. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16223. }
  16224. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16225. Server svr;
  16226. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16227. std::string observed_remote_addr;
  16228. std::string observed_xff;
  16229. svr.Get("/ip", [&](const Request &req, Response &res) {
  16230. observed_remote_addr = req.remote_addr;
  16231. observed_xff = req.get_header_value("X-Forwarded-For");
  16232. res.set_content("ok", "text/plain");
  16233. });
  16234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16235. auto se = detail::scope_exit([&] {
  16236. svr.stop();
  16237. t.join();
  16238. ASSERT_FALSE(svr.is_running());
  16239. });
  16240. svr.wait_until_ready();
  16241. Client cli(HOST, PORT);
  16242. auto res = cli.Get(
  16243. "/ip",
  16244. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16246. EXPECT_EQ(StatusCode::OK_200, res->status);
  16247. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16248. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16249. }
  16250. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16251. Server svr;
  16252. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16253. std::string observed_remote_addr;
  16254. std::string observed_xff;
  16255. svr.Get("/ip", [&](const Request &req, Response &res) {
  16256. observed_remote_addr = req.remote_addr;
  16257. observed_xff = req.get_header_value("X-Forwarded-For");
  16258. res.set_content("ok", "text/plain");
  16259. });
  16260. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16261. auto se = detail::scope_exit([&] {
  16262. svr.stop();
  16263. t.join();
  16264. ASSERT_FALSE(svr.is_running());
  16265. });
  16266. svr.wait_until_ready();
  16267. Client cli(HOST, PORT);
  16268. auto res = cli.Get(
  16269. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16271. EXPECT_EQ(StatusCode::OK_200, res->status);
  16272. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16273. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16274. // and must not be selected.
  16275. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16276. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16277. }
  16278. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16279. Server svr;
  16280. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16281. std::string observed_remote_addr;
  16282. svr.Get("/ip", [&](const Request &req, Response &res) {
  16283. observed_remote_addr = req.remote_addr;
  16284. res.set_content("ok", "text/plain");
  16285. });
  16286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. });
  16292. svr.wait_until_ready();
  16293. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16294. // a forged address and the trusted proxy's own address; the forged value must
  16295. // not win over the address the trusted proxy actually recorded.
  16296. Client cli(HOST, PORT);
  16297. auto res = cli.Get(
  16298. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16300. EXPECT_EQ(StatusCode::OK_200, res->status);
  16301. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16302. }
  16303. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16304. Server svr;
  16305. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16306. std::string observed_remote_addr;
  16307. std::string observed_xff;
  16308. svr.Get("/ip", [&](const Request &req, Response &res) {
  16309. observed_remote_addr = req.remote_addr;
  16310. observed_xff = req.get_header_value("X-Forwarded-For");
  16311. res.set_content("ok", "text/plain");
  16312. });
  16313. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16314. auto se = detail::scope_exit([&] {
  16315. svr.stop();
  16316. t.join();
  16317. ASSERT_FALSE(svr.is_running());
  16318. });
  16319. svr.wait_until_ready();
  16320. Client cli(HOST, PORT);
  16321. auto res = cli.Get(
  16322. "/ip",
  16323. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16325. EXPECT_EQ(StatusCode::OK_200, res->status);
  16326. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16327. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16328. }
  16329. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16330. Server svr;
  16331. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16332. std::string observed_remote_addr;
  16333. std::string observed_xff;
  16334. svr.Get("/ip", [&](const Request &req, Response &res) {
  16335. observed_remote_addr = req.remote_addr;
  16336. observed_xff = req.get_header_value("X-Forwarded-For");
  16337. res.set_content("ok", "text/plain");
  16338. });
  16339. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16340. auto se = detail::scope_exit([&] {
  16341. svr.stop();
  16342. t.join();
  16343. ASSERT_FALSE(svr.is_running());
  16344. });
  16345. svr.wait_until_ready();
  16346. std::string raw_req =
  16347. "GET /ip HTTP/1.1\r\n"
  16348. "Host: localhost\r\n"
  16349. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16350. "Connection: close\r\n"
  16351. "\r\n";
  16352. std::string out;
  16353. ASSERT_TRUE(send_request(5, raw_req, &out));
  16354. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16355. // Header parser trims surrounding whitespace of the header value
  16356. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16357. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16358. }
  16359. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16360. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16361. // their own X-Forwarded-For as a separate field line rather than extending the
  16362. // one the client sent, so every occurrence has to be taken into account.
  16363. // Reading only the first one hands back the address the client chose.
  16364. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16365. Server svr;
  16366. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16367. std::string observed_remote_addr;
  16368. size_t observed_xff_count = 0;
  16369. svr.Get("/ip", [&](const Request &req, Response &res) {
  16370. observed_remote_addr = req.remote_addr;
  16371. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16372. res.set_content("ok", "text/plain");
  16373. });
  16374. auto port = svr.bind_to_any_port(HOST);
  16375. thread t = thread([&]() { svr.listen_after_bind(); });
  16376. auto se = detail::scope_exit([&] {
  16377. svr.stop();
  16378. t.join();
  16379. ASSERT_FALSE(svr.is_running());
  16380. });
  16381. svr.wait_until_ready();
  16382. // The client supplies the first field line; the trusted proxy appends the
  16383. // address it observed as a second one.
  16384. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16385. "Host: localhost\r\n"
  16386. "X-Forwarded-For: 1.2.3.4\r\n"
  16387. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16388. "Connection: close\r\n"
  16389. "\r\n";
  16390. std::string out;
  16391. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16392. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16393. EXPECT_EQ(observed_xff_count, 2U);
  16394. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16395. // The same chain spread over one field line per hop derives the same client
  16396. // address, i.e. the split and the comma-joined representations agree.
  16397. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16398. "Host: localhost\r\n"
  16399. "X-Forwarded-For: 1.2.3.4\r\n"
  16400. "X-Forwarded-For: 198.51.100.23\r\n"
  16401. "X-Forwarded-For: 192.0.2.45\r\n"
  16402. "Connection: close\r\n"
  16403. "\r\n";
  16404. out.clear();
  16405. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16406. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16407. EXPECT_EQ(observed_xff_count, 3U);
  16408. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16409. }
  16410. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16411. // crash the server (it used to call front() on an empty vector inside
  16412. // get_client_ip). The connection-level remote address must be retained instead.
  16413. static void run_malformed_xff_test(const std::string &xff_value) {
  16414. Server svr;
  16415. svr.set_trusted_proxies({"192.0.2.45"});
  16416. std::string observed_remote_addr;
  16417. svr.Get("/ip", [&](const Request &req, Response &res) {
  16418. observed_remote_addr = req.remote_addr;
  16419. res.set_content("ok", "text/plain");
  16420. });
  16421. int port = 0;
  16422. thread t = thread([&]() {
  16423. port = svr.bind_to_any_port(HOST);
  16424. svr.listen_after_bind();
  16425. });
  16426. auto se = detail::scope_exit([&] {
  16427. svr.stop();
  16428. t.join();
  16429. ASSERT_FALSE(svr.is_running());
  16430. });
  16431. svr.wait_until_ready();
  16432. Client cli(HOST, port);
  16433. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16435. EXPECT_EQ(StatusCode::OK_200, res->status);
  16436. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16437. observed_remote_addr == "127.0.0.1");
  16438. }
  16439. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16440. run_malformed_xff_test("");
  16441. }
  16442. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16443. run_malformed_xff_test(",");
  16444. }
  16445. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16446. run_malformed_xff_test(", , ,");
  16447. }
  16448. // The same rule applies to Accept: a request whose acceptable types are spread
  16449. // over several field lines must be negotiated against all of them.
  16450. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16451. // case-insensitive connection options. Comparing the whole field value against
  16452. // one option misses a client that sends several of them, and misses every
  16453. // casing but the one written in the comparison.
  16454. //
  16455. // Sends req, reads the response, then reuses the same socket for a second
  16456. // request to find out whether the server kept the connection.
  16457. static void probe_connection_reuse(int port, const std::string &req,
  16458. bool *announced_close, bool *reusable) {
  16459. auto error = Error::Success;
  16460. auto sock = detail::create_client_socket(
  16461. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16462. /*connection_timeout_sec=*/5, 0,
  16463. /*read_timeout_sec=*/1, 0,
  16464. /*write_timeout_sec=*/5, 0, std::string(), error);
  16465. ASSERT_NE(sock, INVALID_SOCKET);
  16466. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16467. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16468. "Host: localhost\r\n"
  16469. "Connection: close\r\n"
  16470. "\r\n";
  16471. std::string first_response;
  16472. std::string second_response;
  16473. detail::process_client_socket(
  16474. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16475. [&](Stream &strm) {
  16476. if (strm.write(req.data(), req.size()) !=
  16477. static_cast<ssize_t>(req.size())) {
  16478. return false;
  16479. }
  16480. char buf[512];
  16481. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16482. // Headers plus the two-byte body of the handler below
  16483. while (reader.getline()) {
  16484. first_response += reader.ptr();
  16485. if (first_response.find("ok") != std::string::npos) { break; }
  16486. }
  16487. if (strm.write(second.data(), second.size()) !=
  16488. static_cast<ssize_t>(second.size())) {
  16489. return true;
  16490. }
  16491. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16492. while (reader2.getline()) {
  16493. second_response += reader2.ptr();
  16494. if (second_response.find("ok") != std::string::npos) { break; }
  16495. }
  16496. return true;
  16497. });
  16498. *announced_close =
  16499. first_response.find("Connection: close") != std::string::npos;
  16500. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16501. }
  16502. class ConnectionTokenTest : public ::testing::Test {
  16503. protected:
  16504. void SetUp() override {
  16505. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16506. res.set_content("ok", "text/plain");
  16507. });
  16508. port_ = svr_.bind_to_any_port(HOST);
  16509. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16510. svr_.wait_until_ready();
  16511. }
  16512. void TearDown() override {
  16513. svr_.stop();
  16514. if (thread_.joinable()) { thread_.join(); }
  16515. }
  16516. Server svr_;
  16517. int port_ = 0;
  16518. thread thread_;
  16519. };
  16520. // "close" alongside another option still closes the connection, and the
  16521. // response says so rather than leaving the peer to discover it.
  16522. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16523. bool announced_close = false;
  16524. bool reusable = true;
  16525. probe_connection_reuse(port_,
  16526. "GET /keepalive HTTP/1.1\r\n"
  16527. "Host: localhost\r\n"
  16528. "Connection: keep-alive, close\r\n"
  16529. "\r\n",
  16530. &announced_close, &reusable);
  16531. EXPECT_TRUE(announced_close);
  16532. EXPECT_FALSE(reusable);
  16533. }
  16534. // "close" split over two field lines is the same list, so it is honored too.
  16535. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16536. bool announced_close = false;
  16537. bool reusable = true;
  16538. probe_connection_reuse(port_,
  16539. "GET /keepalive HTTP/1.1\r\n"
  16540. "Host: localhost\r\n"
  16541. "Connection: keep-alive\r\n"
  16542. "Connection: close\r\n"
  16543. "\r\n",
  16544. &announced_close, &reusable);
  16545. EXPECT_TRUE(announced_close);
  16546. EXPECT_FALSE(reusable);
  16547. }
  16548. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16549. // keep-alive in the spelling everyone actually sends keeps its connection.
  16550. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16551. bool announced_close = false;
  16552. bool reusable = false;
  16553. probe_connection_reuse(port_,
  16554. "GET /keepalive HTTP/1.0\r\n"
  16555. "Host: localhost\r\n"
  16556. "Connection: keep-alive\r\n"
  16557. "\r\n",
  16558. &announced_close, &reusable);
  16559. EXPECT_FALSE(announced_close);
  16560. EXPECT_TRUE(reusable);
  16561. }
  16562. // A token the value merely contains is not the token itself.
  16563. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16564. bool announced_close = false;
  16565. bool reusable = false;
  16566. probe_connection_reuse(port_,
  16567. "GET /keepalive HTTP/1.1\r\n"
  16568. "Host: localhost\r\n"
  16569. "Connection: notclose\r\n"
  16570. "\r\n",
  16571. &announced_close, &reusable);
  16572. EXPECT_FALSE(announced_close);
  16573. EXPECT_TRUE(reusable);
  16574. }
  16575. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16576. Server svr;
  16577. std::vector<std::string> observed_types;
  16578. svr.Get("/", [&](const Request &req, Response &res) {
  16579. observed_types = req.accept_content_types;
  16580. res.set_content("ok", "text/plain");
  16581. });
  16582. auto port = svr.bind_to_any_port(HOST);
  16583. thread t = thread([&]() { svr.listen_after_bind(); });
  16584. auto se = detail::scope_exit([&] {
  16585. svr.stop();
  16586. t.join();
  16587. ASSERT_FALSE(svr.is_running());
  16588. });
  16589. svr.wait_until_ready();
  16590. Client cli(HOST, port);
  16591. Headers headers;
  16592. headers.emplace("Accept", "text/plain;q=0.5");
  16593. headers.emplace("Accept", "application/json");
  16594. auto res = cli.Get("/", headers);
  16595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16596. EXPECT_EQ(StatusCode::OK_200, res->status);
  16597. // Sorted by q-value, so the second field line's type comes first
  16598. ASSERT_EQ(2U, observed_types.size());
  16599. EXPECT_EQ("application/json", observed_types[0]);
  16600. EXPECT_EQ("text/plain", observed_types[1]);
  16601. }
  16602. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16603. // empty field line must not contribute a bare comma to the combined value.
  16604. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16605. Server svr;
  16606. std::vector<std::string> observed_types;
  16607. svr.Get("/", [&](const Request &req, Response &res) {
  16608. observed_types = req.accept_content_types;
  16609. res.set_content("ok", "text/plain");
  16610. });
  16611. auto port = svr.bind_to_any_port(HOST);
  16612. thread t = thread([&]() { svr.listen_after_bind(); });
  16613. auto se = detail::scope_exit([&] {
  16614. svr.stop();
  16615. t.join();
  16616. ASSERT_FALSE(svr.is_running());
  16617. });
  16618. svr.wait_until_ready();
  16619. // Empty first field line, then a real one
  16620. std::string raw_req = "GET / HTTP/1.1\r\n"
  16621. "Host: localhost\r\n"
  16622. "Accept:\r\n"
  16623. "Accept: application/json\r\n"
  16624. "Connection: close\r\n"
  16625. "\r\n";
  16626. std::string out;
  16627. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16628. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16629. ASSERT_EQ(1U, observed_types.size());
  16630. EXPECT_EQ("application/json", observed_types[0]);
  16631. }
  16632. // The skip in get_combined_header_value() is what keeps an empty field line
  16633. // from contributing a bare comma. Only a trailing empty field line exercises
  16634. // it: a leading one is already covered by the "combined is still empty" check,
  16635. // and parse_accept_header() now ignores the empty element either way, so the
  16636. // request-level test above can no longer tell the two apart.
  16637. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16638. Headers headers;
  16639. headers.emplace("Accept", "text/html");
  16640. headers.emplace("Accept", "");
  16641. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16642. headers.clear();
  16643. headers.emplace("Accept", "");
  16644. headers.emplace("Accept", "application/json");
  16645. EXPECT_EQ("application/json",
  16646. detail::get_combined_header_value(headers, "Accept"));
  16647. }
  16648. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16649. // An encoding offered on a later Accept-Encoding field line is still offered.
  16650. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16651. Server svr;
  16652. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16653. res.set_content(std::string(1024, 'x'), "text/plain");
  16654. });
  16655. auto port = svr.bind_to_any_port(HOST);
  16656. thread t = thread([&]() { svr.listen_after_bind(); });
  16657. auto se = detail::scope_exit([&] {
  16658. svr.stop();
  16659. t.join();
  16660. ASSERT_FALSE(svr.is_running());
  16661. });
  16662. svr.wait_until_ready();
  16663. Client cli(HOST, port);
  16664. cli.set_decompress(false);
  16665. Headers headers;
  16666. headers.emplace("Accept-Encoding", "identity");
  16667. headers.emplace("Accept-Encoding", "gzip");
  16668. auto res = cli.Get("/", headers);
  16669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16670. EXPECT_EQ(StatusCode::OK_200, res->status);
  16671. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16672. }
  16673. #endif
  16674. #ifndef _WIN32
  16675. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16676. Server svr;
  16677. svr.Post("/post", [&](const Request &req, Response &res) {
  16678. res.set_content(req.body, "text/plain");
  16679. });
  16680. svr.Put("/put", [&](const Request &req, Response &res) {
  16681. res.set_content(req.body, "text/plain");
  16682. });
  16683. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16684. res.set_content(req.body, "text/plain");
  16685. });
  16686. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16687. res.set_content(req.body, "text/plain");
  16688. });
  16689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16690. auto se = detail::scope_exit([&] {
  16691. svr.stop();
  16692. t.join();
  16693. ASSERT_FALSE(svr.is_running());
  16694. });
  16695. svr.wait_until_ready();
  16696. std::string resp;
  16697. // POST without Content-Length
  16698. ASSERT_TRUE(send_request(5,
  16699. "POST /post HTTP/1.1\r\n"
  16700. "Host: localhost\r\n"
  16701. "Connection: close\r\n"
  16702. "\r\n",
  16703. &resp));
  16704. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16705. // PUT without Content-Length
  16706. resp.clear();
  16707. ASSERT_TRUE(send_request(5,
  16708. "PUT /put HTTP/1.1\r\n"
  16709. "Host: localhost\r\n"
  16710. "Connection: close\r\n"
  16711. "\r\n",
  16712. &resp));
  16713. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16714. // PATCH without Content-Length
  16715. resp.clear();
  16716. ASSERT_TRUE(send_request(5,
  16717. "PATCH /patch HTTP/1.1\r\n"
  16718. "Host: localhost\r\n"
  16719. "Connection: close\r\n"
  16720. "\r\n",
  16721. &resp));
  16722. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16723. // DELETE without Content-Length
  16724. resp.clear();
  16725. ASSERT_TRUE(send_request(5,
  16726. "DELETE /delete HTTP/1.1\r\n"
  16727. "Host: localhost\r\n"
  16728. "Connection: close\r\n"
  16729. "\r\n",
  16730. &resp));
  16731. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16732. }
  16733. #endif
  16734. //==============================================================================
  16735. // open_stream() Tests
  16736. //==============================================================================
  16737. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16738. std::string result;
  16739. char buf[8192];
  16740. ssize_t n;
  16741. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16742. result.append(buf, static_cast<size_t>(n));
  16743. }
  16744. return result;
  16745. }
  16746. // Mock stream for unit tests
  16747. class MockStream : public Stream {
  16748. public:
  16749. std::string data;
  16750. size_t pos = 0;
  16751. ssize_t error_after = -1; // -1 = no error
  16752. explicit MockStream(const std::string &d, ssize_t err = -1)
  16753. : data(d), error_after(err) {}
  16754. bool is_readable() const override { return true; }
  16755. bool wait_readable() const override { return true; }
  16756. bool wait_writable() const override { return true; }
  16757. ssize_t read(char *ptr, size_t size) override {
  16758. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16759. if (pos >= data.size()) return 0;
  16760. size_t limit =
  16761. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16762. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16763. std::memcpy(ptr, data.data() + pos, to_read);
  16764. pos += to_read;
  16765. return static_cast<ssize_t>(to_read);
  16766. }
  16767. ssize_t write(const char *, size_t) override { return -1; }
  16768. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16769. ip = "127.0.0.1";
  16770. port = 0;
  16771. }
  16772. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16773. ip = "127.0.0.1";
  16774. port = 0;
  16775. }
  16776. socket_t socket() const override { return INVALID_SOCKET; }
  16777. time_t duration() const override { return 0; }
  16778. };
  16779. TEST(StreamHandleTest, Basic) {
  16780. ClientImpl::StreamHandle handle;
  16781. EXPECT_FALSE(handle.is_valid());
  16782. handle.response = detail::make_unique<Response>();
  16783. handle.error = Error::Connection;
  16784. EXPECT_FALSE(handle.is_valid());
  16785. handle.error = Error::Success;
  16786. EXPECT_TRUE(handle.is_valid());
  16787. }
  16788. TEST(BodyReaderTest, Basic) {
  16789. MockStream stream("Hello, World!");
  16790. detail::BodyReader reader;
  16791. reader.stream = &stream;
  16792. reader.content_length = 13;
  16793. char buf[32];
  16794. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16795. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16796. EXPECT_TRUE(reader.eof);
  16797. }
  16798. TEST(BodyReaderTest, NoStream) {
  16799. detail::BodyReader reader;
  16800. char buf[32];
  16801. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16802. EXPECT_EQ(Error::Connection, reader.last_error);
  16803. }
  16804. TEST(BodyReaderTest, Error) {
  16805. MockStream stream("Hello, World!", 5);
  16806. detail::BodyReader reader;
  16807. reader.stream = &stream;
  16808. reader.content_length = 13;
  16809. char buf[32];
  16810. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16811. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16812. EXPECT_EQ(Error::Read, reader.last_error);
  16813. }
  16814. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16815. // Mock-based StreamHandle tests relying on private internals are removed.
  16816. class OpenStreamTest : public ::testing::Test {
  16817. protected:
  16818. void SetUp() override {
  16819. svr_.Get("/hello", [](const Request &, Response &res) {
  16820. res.set_content("Hello World!", "text/plain");
  16821. });
  16822. svr_.Get("/large", [](const Request &, Response &res) {
  16823. res.set_content(std::string(10000, 'X'), "text/plain");
  16824. });
  16825. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16826. res.set_content("Hello World!", "image/jpeg");
  16827. res.set_header("Content-Encoding", "UTF-8");
  16828. });
  16829. svr_.Get("/chunked", [](const Request &, Response &res) {
  16830. res.set_chunked_content_provider("text/plain",
  16831. [](size_t offset, DataSink &sink) {
  16832. if (offset < 15) {
  16833. sink.write("chunk", 5);
  16834. return true;
  16835. }
  16836. sink.done();
  16837. return true;
  16838. });
  16839. });
  16840. svr_.Get("/compressible", [](const Request &, Response &res) {
  16841. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16842. DataSink &sink) {
  16843. if (offset < 100 * 1024) {
  16844. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16845. sink.write(chunk.data(), chunk.size());
  16846. return true;
  16847. }
  16848. sink.done();
  16849. return true;
  16850. });
  16851. });
  16852. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16853. [](const Request & /*req*/, Response &res) {
  16854. auto i = new int(0);
  16855. res.set_header("Trailer", "Content-Length, X-Allowed");
  16856. res.set_chunked_content_provider(
  16857. "text/plain",
  16858. [i](size_t /*offset*/, DataSink &sink) {
  16859. switch (*i) {
  16860. case 0: sink.os << "123"; break;
  16861. case 1: sink.os << "456"; break;
  16862. case 2: sink.os << "789"; break;
  16863. case 3: {
  16864. sink.done_with_trailer(
  16865. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16866. } break;
  16867. }
  16868. (*i)++;
  16869. return true;
  16870. },
  16871. [i](bool success) {
  16872. EXPECT_TRUE(success);
  16873. delete i;
  16874. });
  16875. });
  16876. // Echo headers endpoint for header-related tests
  16877. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16878. std::string body;
  16879. for (const auto &h : req.headers) {
  16880. body.append(h.first);
  16881. body.push_back(':');
  16882. body.append(h.second);
  16883. body.push_back('\n');
  16884. }
  16885. res.set_content(body, "text/plain");
  16886. });
  16887. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16888. std::string body;
  16889. for (const auto &h : req.headers) {
  16890. body.append(h.first);
  16891. body.push_back(':');
  16892. body.append(h.second);
  16893. body.push_back('\n');
  16894. }
  16895. res.set_content(body, "text/plain");
  16896. });
  16897. port_ = svr_.bind_to_any_port("127.0.0.1");
  16898. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16899. svr_.wait_until_ready();
  16900. }
  16901. void TearDown() override {
  16902. svr_.stop();
  16903. if (thread_.joinable()) thread_.join();
  16904. }
  16905. Server svr_;
  16906. std::thread thread_;
  16907. int port_ = 0;
  16908. };
  16909. TEST_F(OpenStreamTest, Basic) {
  16910. Client cli("127.0.0.1", port_);
  16911. auto handle = cli.open_stream("GET", "/hello");
  16912. EXPECT_TRUE(handle.is_valid());
  16913. EXPECT_EQ("Hello World!", read_all(handle));
  16914. }
  16915. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16916. Client cli("127.0.0.1", port_);
  16917. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16918. ASSERT_TRUE(handle.is_valid());
  16919. EXPECT_EQ("Hello World!", read_all(handle));
  16920. }
  16921. TEST_F(OpenStreamTest, SmallBuffer) {
  16922. Client cli("127.0.0.1", port_);
  16923. auto handle = cli.open_stream("GET", "/hello");
  16924. std::string result;
  16925. char buf[4];
  16926. ssize_t n;
  16927. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16928. result.append(buf, static_cast<size_t>(n));
  16929. EXPECT_EQ("Hello World!", result);
  16930. }
  16931. TEST_F(OpenStreamTest, DefaultHeaders) {
  16932. Client cli("127.0.0.1", port_);
  16933. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16934. {
  16935. auto handle = cli.open_stream("GET", "/echo-headers");
  16936. ASSERT_TRUE(handle.is_valid());
  16937. auto body = read_all(handle);
  16938. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16939. std::string::npos);
  16940. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16941. std::string::npos);
  16942. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16943. }
  16944. // open_stream POST with body and no explicit content_type should NOT add
  16945. // text/plain Content-Type (behavior differs from non-streaming path), but
  16946. // should include Content-Length
  16947. {
  16948. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16949. ASSERT_TRUE(handle.is_valid());
  16950. auto body = read_all(handle);
  16951. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16952. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16953. }
  16954. // open_stream POST with explicit Content-Type should preserve it
  16955. {
  16956. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16957. {{"Content-Type", "application/custom"}},
  16958. "{}", "application/custom");
  16959. ASSERT_TRUE(handle.is_valid());
  16960. auto body = read_all(handle);
  16961. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16962. }
  16963. // User-specified User-Agent must not be overwritten for stream API
  16964. {
  16965. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16966. {{"User-Agent", "MyAgent/1.2"}});
  16967. ASSERT_TRUE(handle.is_valid());
  16968. auto body = read_all(handle);
  16969. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16970. }
  16971. }
  16972. TEST_F(OpenStreamTest, Large) {
  16973. Client cli("127.0.0.1", port_);
  16974. auto handle = cli.open_stream("GET", "/large");
  16975. EXPECT_EQ(10000u, read_all(handle).size());
  16976. }
  16977. TEST_F(OpenStreamTest, ConnectionError) {
  16978. Client cli("127.0.0.1", 9999);
  16979. auto handle = cli.open_stream("GET", "/hello");
  16980. EXPECT_FALSE(handle.is_valid());
  16981. }
  16982. TEST_F(OpenStreamTest, Chunked) {
  16983. Client cli("127.0.0.1", port_);
  16984. auto handle = cli.open_stream("GET", "/chunked");
  16985. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16986. "Transfer-Encoding") == "chunked");
  16987. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16988. }
  16989. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16990. Client cli("127.0.0.1", port_);
  16991. auto handle =
  16992. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16993. ASSERT_TRUE(handle.is_valid());
  16994. // Consume body to allow trailers to be received/parsed
  16995. auto body = read_all(handle);
  16996. // Explicitly parse trailers (ensure trailers are available for assertion)
  16997. handle.parse_trailers_if_needed();
  16998. EXPECT_EQ(std::string("123456789"), body);
  16999. // The response should include a Trailer header declaring both names
  17000. ASSERT_TRUE(handle.response);
  17001. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17002. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17003. handle.response->get_header_value("Trailer"));
  17004. // Prohibited trailer must not be present
  17005. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17006. // Allowed trailer should be present
  17007. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17008. EXPECT_EQ(std::string("yes"),
  17009. handle.response->get_trailer_value("X-Allowed"));
  17010. // Verify trailers are NOT present as regular headers
  17011. EXPECT_EQ(std::string(""),
  17012. handle.response->get_header_value("Content-Length"));
  17013. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17014. }
  17015. static std::thread serve_single_response(std::promise<int> &port_promise,
  17016. const std::string &response) {
  17017. return std::thread([&port_promise, response] {
  17018. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17019. default_socket_options(srv);
  17020. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17021. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17022. sockaddr_in addr{};
  17023. addr.sin_family = AF_INET;
  17024. addr.sin_port = htons(0); // Let OS assign a free port
  17025. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17026. int opt = 1;
  17027. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17028. #ifdef _WIN32
  17029. reinterpret_cast<const char *>(&opt),
  17030. #else
  17031. &opt,
  17032. #endif
  17033. sizeof(opt));
  17034. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17035. ::listen(srv, 1) != 0) {
  17036. port_promise.set_value(-1);
  17037. detail::close_socket(srv);
  17038. return;
  17039. }
  17040. socklen_t addr_len = sizeof(addr);
  17041. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17042. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17043. sockaddr_in cli_addr{};
  17044. socklen_t cli_len = sizeof(cli_addr);
  17045. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17046. if (cli != INVALID_SOCKET) {
  17047. // Read the complete HTTP request (until the blank line that terminates
  17048. // headers) before sending the response. If the server closes the socket
  17049. // while the client's request data is still unread in the kernel receive
  17050. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17051. // connection on both sides: it discards the client's receive buffer
  17052. // (which already holds our response) and causes any in-progress write on
  17053. // the client to fail with ECONNRESET. Reading all request data first
  17054. // ensures close() emits a graceful FIN.
  17055. {
  17056. char rbuf[256];
  17057. std::string req;
  17058. while (req.find("\r\n\r\n") == std::string::npos) {
  17059. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17060. if (n <= 0) { break; }
  17061. req.append(rbuf, static_cast<size_t>(n));
  17062. }
  17063. }
  17064. ::send(cli,
  17065. #ifdef _WIN32
  17066. static_cast<const char *>(response.c_str()),
  17067. static_cast<int>(response.size()),
  17068. #else
  17069. response.c_str(), response.size(),
  17070. #endif
  17071. 0);
  17072. detail::close_socket(cli);
  17073. }
  17074. detail::close_socket(srv);
  17075. });
  17076. }
  17077. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17078. #ifndef _WIN32
  17079. signal(SIGPIPE, SIG_IGN);
  17080. #endif
  17081. std::promise<int> port_promise;
  17082. auto port_future = port_promise.get_future();
  17083. auto server_thread =
  17084. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17085. "Content-Type: text/plain\r\n"
  17086. "Content-Length: not-a-number\r\n"
  17087. "Connection: close\r\n"
  17088. "\r\n"
  17089. "hello");
  17090. auto port = port_future.get();
  17091. ASSERT_GT(port, 0);
  17092. Client cli("127.0.0.1", port);
  17093. auto handle = cli.open_stream("GET", "/");
  17094. EXPECT_FALSE(handle.is_valid());
  17095. server_thread.join();
  17096. }
  17097. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17098. #ifndef _WIN32
  17099. signal(SIGPIPE, SIG_IGN);
  17100. #endif
  17101. std::promise<int> port_promise;
  17102. auto port_future = port_promise.get_future();
  17103. auto server_thread = serve_single_response(
  17104. port_promise, "HTTP/1.1 200 OK\r\n"
  17105. "Content-Type: text/plain\r\n"
  17106. "Content-Length: 99999999999999999999999999\r\n"
  17107. "Connection: close\r\n"
  17108. "\r\n"
  17109. "hello");
  17110. auto port = port_future.get();
  17111. ASSERT_GT(port, 0);
  17112. // Historically std::stoull would throw std::out_of_range here and crash
  17113. // the process, then parsing silently clamped to a bogus framing length and
  17114. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17115. // so the stream fails to open, matching the not-a-number case above. The
  17116. // process still must NOT terminate.
  17117. Client cli("127.0.0.1", port);
  17118. auto handle = cli.open_stream("GET", "/");
  17119. EXPECT_FALSE(handle.is_valid());
  17120. server_thread.join();
  17121. }
  17122. // Serves `response` to the single request `fn` makes with a fresh client.
  17123. template <typename Fn>
  17124. static void with_single_response(const std::string &response, Fn fn) {
  17125. #ifndef _WIN32
  17126. signal(SIGPIPE, SIG_IGN);
  17127. #endif
  17128. std::promise<int> port_promise;
  17129. auto port_future = port_promise.get_future();
  17130. auto server_thread = serve_single_response(port_promise, response);
  17131. auto se = detail::scope_exit([&] { server_thread.join(); });
  17132. auto port = port_future.get();
  17133. ASSERT_GT(port, 0);
  17134. Client cli("127.0.0.1", port);
  17135. fn(cli);
  17136. }
  17137. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17138. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17139. // the chunked coding and drop Content-Length, so a front-end that trusts
  17140. // Content-Length would disagree about where the body ends (response
  17141. // smuggling). The client must reject such a response.
  17142. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17143. for (const char *te : {"chunked", "gzip, chunked"}) {
  17144. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17145. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17146. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17147. "5\r\nhello\r\n0\r\n\r\n";
  17148. with_single_response(response, [&](Client &cli) {
  17149. auto res = cli.Get("/");
  17150. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17151. EXPECT_EQ(Error::Read, res.error()) << te;
  17152. });
  17153. with_single_response(response, [&](Client &cli) {
  17154. auto handle = cli.open_stream("GET", "/");
  17155. EXPECT_FALSE(handle.is_valid()) << te;
  17156. EXPECT_EQ(Error::Read, handle.error) << te;
  17157. });
  17158. }
  17159. }
  17160. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17161. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17162. // closing the connection (unlike a request, which must be rejected).
  17163. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17164. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17165. "Transfer-Encoding: chunked\r\n"
  17166. "Connection: close\r\n"
  17167. "\r\n"
  17168. "5\r\nhello\r\n0\r\n\r\n",
  17169. "HTTP/1.1 200 OK\r\n"
  17170. "Transfer-Encoding: gzip\r\n"
  17171. "Connection: close\r\n"
  17172. "\r\n"
  17173. "hello"}) {
  17174. with_single_response(response, [&](Client &cli) {
  17175. auto res = cli.Get("/");
  17176. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17177. EXPECT_EQ("hello", res->body);
  17178. });
  17179. with_single_response(response, [&](Client &cli) {
  17180. auto handle = cli.open_stream("GET", "/");
  17181. ASSERT_TRUE(handle.is_valid()) << response;
  17182. EXPECT_EQ("hello", read_all(handle));
  17183. });
  17184. }
  17185. }
  17186. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17187. // framing headers describe nothing to read and must not be rejected.
  17188. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17189. const std::string framing = "Content-Length: 5\r\n"
  17190. "Transfer-Encoding: chunked\r\n"
  17191. "Connection: close\r\n"
  17192. "\r\n";
  17193. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17194. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17195. });
  17196. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17197. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17198. });
  17199. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17200. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17201. with_single_response(response, [&](Client &cli) {
  17202. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17203. });
  17204. with_single_response(response, [&](Client &cli) {
  17205. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17206. });
  17207. }
  17208. }
  17209. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17210. TEST_F(OpenStreamTest, Gzip) {
  17211. Client cli("127.0.0.1", port_);
  17212. auto handle = cli.open_stream("GET", "/compressible", {},
  17213. {{"Accept-Encoding", "gzip"}});
  17214. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17215. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17216. }
  17217. #endif
  17218. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17219. TEST_F(OpenStreamTest, Brotli) {
  17220. Client cli("127.0.0.1", port_);
  17221. auto handle =
  17222. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17223. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17224. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17225. }
  17226. #endif
  17227. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17228. TEST_F(OpenStreamTest, Zstd) {
  17229. Client cli("127.0.0.1", port_);
  17230. auto handle = cli.open_stream("GET", "/compressible", {},
  17231. {{"Accept-Encoding", "zstd"}});
  17232. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17233. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17234. }
  17235. #endif
  17236. #ifdef CPPHTTPLIB_SSL_ENABLED
  17237. class SSLOpenStreamTest : public ::testing::Test {
  17238. protected:
  17239. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17240. void SetUp() override {
  17241. svr_.Get("/hello", [](const Request &, Response &res) {
  17242. res.set_content("Hello SSL World!", "text/plain");
  17243. });
  17244. svr_.Get("/chunked", [](const Request &, Response &res) {
  17245. res.set_chunked_content_provider("text/plain",
  17246. [](size_t offset, DataSink &sink) {
  17247. if (offset < 15) {
  17248. sink.write("chunk", 5);
  17249. return true;
  17250. }
  17251. sink.done();
  17252. return true;
  17253. });
  17254. });
  17255. svr_.Post("/echo", [](const Request &req, Response &res) {
  17256. res.set_content(req.body, req.get_header_value("Content-Type"));
  17257. });
  17258. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17259. std::string body = req.body;
  17260. res.set_chunked_content_provider(
  17261. "text/plain", [body](size_t offset, DataSink &sink) {
  17262. if (offset < body.size()) {
  17263. sink.write(body.data() + offset, body.size() - offset);
  17264. }
  17265. sink.done();
  17266. return true;
  17267. });
  17268. });
  17269. port_ = svr_.bind_to_any_port("127.0.0.1");
  17270. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17271. svr_.wait_until_ready();
  17272. }
  17273. void TearDown() override {
  17274. svr_.stop();
  17275. if (thread_.joinable()) thread_.join();
  17276. }
  17277. SSLServer svr_;
  17278. std::thread thread_;
  17279. int port_ = 0;
  17280. };
  17281. TEST_F(SSLOpenStreamTest, Basic) {
  17282. SSLClient cli("127.0.0.1", port_);
  17283. cli.enable_server_certificate_verification(false);
  17284. auto handle = cli.open_stream("GET", "/hello");
  17285. ASSERT_TRUE(handle.is_valid());
  17286. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17287. }
  17288. TEST_F(SSLOpenStreamTest, Chunked) {
  17289. SSLClient cli("127.0.0.1", port_);
  17290. cli.enable_server_certificate_verification(false);
  17291. auto handle = cli.open_stream("GET", "/chunked");
  17292. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17293. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17294. "Transfer-Encoding") == "chunked");
  17295. auto body = read_all(handle);
  17296. EXPECT_EQ("chunkchunkchunk", body);
  17297. }
  17298. TEST_F(SSLOpenStreamTest, Post) {
  17299. SSLClient cli("127.0.0.1", port_);
  17300. cli.enable_server_certificate_verification(false);
  17301. auto handle =
  17302. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17303. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17304. EXPECT_EQ(200, handle.response->status);
  17305. auto body = read_all(handle);
  17306. EXPECT_EQ("Hello SSL POST", body);
  17307. }
  17308. TEST_F(SSLOpenStreamTest, PostChunked) {
  17309. SSLClient cli("127.0.0.1", port_);
  17310. cli.enable_server_certificate_verification(false);
  17311. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17312. "Chunked SSL Data", "text/plain");
  17313. ASSERT_TRUE(handle.is_valid());
  17314. EXPECT_EQ(200, handle.response->status);
  17315. auto body = read_all(handle);
  17316. EXPECT_EQ("Chunked SSL Data", body);
  17317. }
  17318. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17319. // Content-Length is terminated by the server closing the connection. When the
  17320. // SSL peer sends a close_notify after the body, the client must treat it as a
  17321. // clean EOF and return a successful response rather than an error.
  17322. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17324. ASSERT_TRUE(svr.is_valid());
  17325. svr.set_keep_alive_max_count(1);
  17326. const std::string expected_body = "Hello from connection-close response!";
  17327. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17328. res.set_content_provider("text/plain",
  17329. [&](size_t offset, DataSink &sink) -> bool {
  17330. if (offset < expected_body.size()) {
  17331. sink.write(expected_body.data() + offset,
  17332. expected_body.size() - offset);
  17333. }
  17334. sink.done();
  17335. return true;
  17336. });
  17337. });
  17338. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17339. auto se = detail::scope_exit([&] {
  17340. svr.stop();
  17341. listen_thread.join();
  17342. ASSERT_FALSE(svr.is_running());
  17343. });
  17344. svr.wait_until_ready();
  17345. SSLClient cli(HOST, PORT);
  17346. cli.enable_server_certificate_verification(false);
  17347. auto res = cli.Get("/no-content-length");
  17348. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17349. EXPECT_EQ(StatusCode::OK_200, res->status);
  17350. EXPECT_EQ(expected_body, res->body);
  17351. }
  17352. #endif // CPPHTTPLIB_SSL_ENABLED
  17353. //==============================================================================
  17354. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17355. // results for various scenarios.
  17356. //==============================================================================
  17357. TEST(ParityTest, GetVsOpenStream) {
  17358. Server svr;
  17359. const std::string path = "/parity";
  17360. const std::string content = "Parity test content: hello world";
  17361. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17362. res.set_content(content, "text/plain");
  17363. });
  17364. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17365. auto se = detail::scope_exit([&] {
  17366. svr.stop();
  17367. t.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. });
  17370. svr.wait_until_ready();
  17371. Client cli(HOST, PORT);
  17372. // Non-stream path
  17373. auto r1 = cli.Get(path);
  17374. ASSERT_TRUE(r1);
  17375. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17376. // Stream path
  17377. auto h = cli.open_stream("GET", path);
  17378. ASSERT_TRUE(h.is_valid());
  17379. EXPECT_EQ(r1->body, read_all(h));
  17380. }
  17381. // Helper to compress data with provided compressor type T
  17382. template <typename Compressor>
  17383. static std::string compress_payload_for_parity(const std::string &in) {
  17384. std::string out;
  17385. Compressor compressor;
  17386. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17387. [&](const char *data, size_t n) {
  17388. out.append(data, n);
  17389. return true;
  17390. });
  17391. EXPECT_TRUE(ok);
  17392. return out;
  17393. }
  17394. // Helper function for compression parity tests
  17395. template <typename Compressor>
  17396. static void test_compression_parity(const std::string &original,
  17397. const std::string &path,
  17398. const std::string &encoding) {
  17399. const std::string compressed =
  17400. compress_payload_for_parity<Compressor>(original);
  17401. Server svr;
  17402. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17403. res.set_content(compressed, "application/octet-stream");
  17404. res.set_header("Content-Encoding", encoding);
  17405. });
  17406. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17407. auto se = detail::scope_exit([&] {
  17408. svr.stop();
  17409. t.join();
  17410. ASSERT_FALSE(svr.is_running());
  17411. });
  17412. svr.wait_until_ready();
  17413. Client cli(HOST, PORT);
  17414. // Non-streaming
  17415. {
  17416. auto res = cli.Get(path);
  17417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17418. EXPECT_EQ(StatusCode::OK_200, res->status);
  17419. EXPECT_EQ(original, res->body);
  17420. }
  17421. // Streaming
  17422. {
  17423. auto h = cli.open_stream("GET", path);
  17424. ASSERT_TRUE(h.is_valid());
  17425. EXPECT_EQ(original, read_all(h));
  17426. }
  17427. }
  17428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17429. TEST(ParityTest, Gzip) {
  17430. test_compression_parity<detail::gzip_compressor>(
  17431. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17432. }
  17433. #endif
  17434. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17435. TEST(ParityTest, Brotli) {
  17436. test_compression_parity<detail::brotli_compressor>(
  17437. "Hello, brotli parity test payload", "/parity-br", "br");
  17438. }
  17439. #endif
  17440. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17441. TEST(ParityTest, Zstd) {
  17442. test_compression_parity<detail::zstd_compressor>(
  17443. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17444. }
  17445. #endif
  17446. //==============================================================================
  17447. // New Stream API Tests
  17448. //==============================================================================
  17449. inline std::string read_body(httplib::stream::Result &result) {
  17450. std::string body;
  17451. while (result.next()) {
  17452. body.append(result.data(), result.size());
  17453. }
  17454. return body;
  17455. }
  17456. TEST(ClientConnectionTest, Basic) {
  17457. httplib::ClientConnection conn;
  17458. EXPECT_FALSE(conn.is_open());
  17459. conn.sock = 1;
  17460. EXPECT_TRUE(conn.is_open());
  17461. httplib::ClientConnection conn2(std::move(conn));
  17462. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17463. conn2.sock = INVALID_SOCKET;
  17464. }
  17465. // Unified test server for all stream::* tests
  17466. class StreamApiTest : public ::testing::Test {
  17467. protected:
  17468. void SetUp() override {
  17469. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17470. res.set_content("Hello World!", "text/plain");
  17471. });
  17472. svr_.Get("/echo-params",
  17473. [](const httplib::Request &req, httplib::Response &res) {
  17474. std::string r;
  17475. for (const auto &p : req.params) {
  17476. if (!r.empty()) r += "&";
  17477. r += p.first + "=" + p.second;
  17478. }
  17479. res.set_content(r, "text/plain");
  17480. });
  17481. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17482. res.set_content(req.body, req.get_header_value("Content-Type"));
  17483. });
  17484. svr_.Post("/echo-headers",
  17485. [](const httplib::Request &req, httplib::Response &res) {
  17486. std::string r;
  17487. for (const auto &h : req.headers)
  17488. r += h.first + ": " + h.second + "\n";
  17489. res.set_content(r, "text/plain");
  17490. });
  17491. svr_.Post("/echo-params",
  17492. [](const httplib::Request &req, httplib::Response &res) {
  17493. std::string r = "params:";
  17494. for (const auto &p : req.params)
  17495. r += p.first + "=" + p.second + ";";
  17496. res.set_content(r + " body:" + req.body, "text/plain");
  17497. });
  17498. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17499. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17500. });
  17501. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17502. res.set_content("PUT:" + req.body, "text/plain");
  17503. });
  17504. svr_.Patch("/echo",
  17505. [](const httplib::Request &req, httplib::Response &res) {
  17506. res.set_content("PATCH:" + req.body, "text/plain");
  17507. });
  17508. svr_.Delete(
  17509. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17510. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17511. "text/plain");
  17512. });
  17513. svr_.Get("/head-test",
  17514. [](const httplib::Request &, httplib::Response &res) {
  17515. res.set_content("body for HEAD", "text/plain");
  17516. });
  17517. svr_.Options("/options",
  17518. [](const httplib::Request &, httplib::Response &res) {
  17519. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17520. });
  17521. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17522. svr_.wait_until_ready();
  17523. }
  17524. void TearDown() override {
  17525. svr_.stop();
  17526. if (thread_.joinable()) thread_.join();
  17527. }
  17528. httplib::Server svr_;
  17529. std::thread thread_;
  17530. };
  17531. // stream::Get tests
  17532. TEST_F(StreamApiTest, GetBasic) {
  17533. httplib::Client cli(HOST, PORT);
  17534. auto result = httplib::stream::Get(cli, "/hello");
  17535. ASSERT_TRUE(result.is_valid());
  17536. EXPECT_EQ(200, result.status());
  17537. EXPECT_EQ("Hello World!", read_body(result));
  17538. }
  17539. TEST_F(StreamApiTest, GetWithParams) {
  17540. httplib::Client cli(HOST, PORT);
  17541. httplib::Params params{{"foo", "bar"}};
  17542. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17543. ASSERT_TRUE(result.is_valid());
  17544. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17545. }
  17546. TEST_F(StreamApiTest, GetConnectionError) {
  17547. httplib::Client cli(HOST, 9999);
  17548. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17549. }
  17550. TEST_F(StreamApiTest, Get404) {
  17551. httplib::Client cli(HOST, PORT);
  17552. auto result = httplib::stream::Get(cli, "/nonexistent");
  17553. EXPECT_TRUE(result.is_valid());
  17554. EXPECT_EQ(404, result.status());
  17555. }
  17556. // stream::Post tests
  17557. TEST_F(StreamApiTest, PostBasic) {
  17558. httplib::Client cli(HOST, PORT);
  17559. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17560. "application/json");
  17561. ASSERT_TRUE(result.is_valid());
  17562. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17563. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17564. }
  17565. TEST_F(StreamApiTest, PostWithHeaders) {
  17566. httplib::Client cli(HOST, PORT);
  17567. httplib::Headers headers{{"X-Custom", "value"}};
  17568. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17569. "text/plain");
  17570. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17571. }
  17572. TEST_F(StreamApiTest, PostWithParams) {
  17573. httplib::Client cli(HOST, PORT);
  17574. httplib::Params params{{"k", "v"}};
  17575. auto result =
  17576. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17577. auto body = read_body(result);
  17578. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17579. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17580. }
  17581. TEST_F(StreamApiTest, PostLarge) {
  17582. httplib::Client cli(HOST, PORT);
  17583. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17584. size_t total = 0;
  17585. while (result.next()) {
  17586. total += result.size();
  17587. }
  17588. EXPECT_EQ(100u * 1024u, total);
  17589. }
  17590. // stream::Put/Patch tests
  17591. TEST_F(StreamApiTest, PutAndPatch) {
  17592. httplib::Client cli(HOST, PORT);
  17593. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17594. EXPECT_EQ("PUT:test", read_body(put));
  17595. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17596. EXPECT_EQ("PATCH:test", read_body(patch));
  17597. }
  17598. // stream::Delete tests
  17599. TEST_F(StreamApiTest, Delete) {
  17600. httplib::Client cli(HOST, PORT);
  17601. auto del1 = httplib::stream::Delete(cli, "/resource");
  17602. EXPECT_EQ("Deleted", read_body(del1));
  17603. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17604. EXPECT_EQ("Deleted:data", read_body(del2));
  17605. }
  17606. // stream::Head/Options tests
  17607. TEST_F(StreamApiTest, HeadAndOptions) {
  17608. httplib::Client cli(HOST, PORT);
  17609. auto head = httplib::stream::Head(cli, "/head-test");
  17610. EXPECT_TRUE(head.is_valid());
  17611. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17612. auto opts = httplib::stream::Options(cli, "/options");
  17613. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17614. }
  17615. // SSL stream::* tests
  17616. #ifdef CPPHTTPLIB_SSL_ENABLED
  17617. class SSLStreamApiTest : public ::testing::Test {
  17618. protected:
  17619. void SetUp() override {
  17620. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17621. res.set_content("Hello SSL!", "text/plain");
  17622. });
  17623. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17624. res.set_content(req.body, "text/plain");
  17625. });
  17626. port_ = svr_.bind_to_any_port("127.0.0.1");
  17627. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17628. svr_.wait_until_ready();
  17629. }
  17630. void TearDown() override {
  17631. svr_.stop();
  17632. if (thread_.joinable()) thread_.join();
  17633. }
  17634. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17635. std::thread thread_;
  17636. int port_ = 0;
  17637. };
  17638. TEST_F(SSLStreamApiTest, GetAndPost) {
  17639. httplib::SSLClient cli("127.0.0.1", port_);
  17640. cli.enable_server_certificate_verification(false);
  17641. auto get = httplib::stream::Get(cli, "/hello");
  17642. EXPECT_EQ("Hello SSL!", read_body(get));
  17643. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17644. EXPECT_EQ("test", read_body(post));
  17645. }
  17646. #endif
  17647. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17648. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17649. // BodyReader
  17650. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17651. // Test that read timeout during streaming is detected
  17652. // Use a large content-length response where server delays mid-stream
  17653. Server svr;
  17654. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17655. // Send a large response with delay in the middle
  17656. res.set_content_provider(
  17657. 1000, // content_length
  17658. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17659. if (offset < 100) {
  17660. // Send first 100 bytes immediately
  17661. std::string data(100, 'A');
  17662. sink.write(data.c_str(), data.size());
  17663. return true;
  17664. }
  17665. // Then delay longer than client timeout
  17666. std::this_thread::sleep_for(std::chrono::seconds(3));
  17667. std::string data(900, 'B');
  17668. sink.write(data.c_str(), data.size());
  17669. return true;
  17670. });
  17671. });
  17672. auto port = 8091;
  17673. std::thread t([&]() { svr.listen("localhost", port); });
  17674. svr.wait_until_ready();
  17675. Client cli("localhost", port);
  17676. cli.set_read_timeout(1, 0); // 1 second timeout
  17677. auto handle = cli.open_stream("GET", "/slow-stream");
  17678. ASSERT_TRUE(handle.is_valid());
  17679. char buf[256];
  17680. ssize_t total = 0;
  17681. ssize_t n;
  17682. bool got_error = false;
  17683. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17684. total += n;
  17685. }
  17686. if (n < 0) {
  17687. got_error = true;
  17688. // Should be timeout or read error
  17689. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17690. handle.get_read_error() == Error::Read)
  17691. << "Actual error: " << to_string(handle.get_read_error());
  17692. }
  17693. // Either we got an error, or we got less data than expected
  17694. EXPECT_TRUE(got_error || total < 1000)
  17695. << "Expected timeout but got all " << total << " bytes";
  17696. svr.stop();
  17697. t.join();
  17698. }
  17699. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17700. // Test connection closed detection via BodyReader
  17701. Server svr;
  17702. std::atomic<bool> close_now{false};
  17703. svr.Get("/will-close", [&](const Request &, Response &res) {
  17704. res.set_content_provider(
  17705. 10000, // Large content_length that we won't fully send
  17706. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17707. if (offset < 100) {
  17708. std::string data(100, 'X');
  17709. sink.write(data.c_str(), data.size());
  17710. return true;
  17711. }
  17712. // Wait for signal then abort
  17713. while (!close_now) {
  17714. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17715. }
  17716. return false; // Abort - server will close connection
  17717. });
  17718. });
  17719. auto port = 8092;
  17720. std::thread t([&]() { svr.listen("localhost", port); });
  17721. svr.wait_until_ready();
  17722. Client cli("localhost", port);
  17723. auto handle = cli.open_stream("GET", "/will-close");
  17724. ASSERT_TRUE(handle.is_valid());
  17725. char buf[256];
  17726. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17727. EXPECT_GT(n, 0) << "First read should succeed";
  17728. // Signal server to close
  17729. close_now = true;
  17730. // Keep reading until error or EOF
  17731. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17732. // Keep reading
  17733. }
  17734. // Should get an error since content_length wasn't satisfied
  17735. if (n < 0) {
  17736. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17737. handle.get_read_error() == Error::Read)
  17738. << "Actual error: " << to_string(handle.get_read_error());
  17739. }
  17740. svr.stop();
  17741. t.join();
  17742. }
  17743. #ifdef CPPHTTPLIB_SSL_ENABLED
  17744. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17745. // Test that read timeout during SSL streaming is detected
  17746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17747. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17748. res.set_content_provider(
  17749. 1000, "text/plain",
  17750. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17751. if (offset < 100) {
  17752. std::string data(100, 'A');
  17753. sink.write(data.c_str(), data.size());
  17754. return true;
  17755. }
  17756. std::this_thread::sleep_for(std::chrono::seconds(3));
  17757. std::string data(900, 'B');
  17758. sink.write(data.c_str(), data.size());
  17759. return true;
  17760. });
  17761. });
  17762. auto port = 8093;
  17763. std::thread t([&]() { svr.listen("localhost", port); });
  17764. svr.wait_until_ready();
  17765. SSLClient cli("localhost", port);
  17766. cli.enable_server_certificate_verification(false);
  17767. cli.set_read_timeout(1, 0); // 1 second timeout
  17768. auto handle = cli.open_stream("GET", "/slow-stream");
  17769. ASSERT_TRUE(handle.is_valid());
  17770. char buf[256];
  17771. ssize_t total = 0;
  17772. ssize_t n;
  17773. bool got_error = false;
  17774. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17775. total += n;
  17776. }
  17777. if (n < 0) {
  17778. got_error = true;
  17779. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17780. handle.get_read_error() == Error::Read)
  17781. << "Actual error: " << to_string(handle.get_read_error());
  17782. }
  17783. EXPECT_TRUE(got_error || total < 1000)
  17784. << "Expected timeout but got all " << total << " bytes";
  17785. svr.stop();
  17786. t.join();
  17787. }
  17788. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17789. // Test SSL connection closed detection
  17790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17791. std::atomic<bool> close_now{false};
  17792. svr.Get("/will-close", [&](const Request &, Response &res) {
  17793. res.set_content_provider(
  17794. 10000, "text/plain",
  17795. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17796. if (offset < 100) {
  17797. std::string data(100, 'X');
  17798. sink.write(data.c_str(), data.size());
  17799. return true;
  17800. }
  17801. while (!close_now) {
  17802. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17803. }
  17804. return false;
  17805. });
  17806. });
  17807. auto port = 8094;
  17808. std::thread t([&]() { svr.listen("localhost", port); });
  17809. svr.wait_until_ready();
  17810. SSLClient cli("localhost", port);
  17811. cli.enable_server_certificate_verification(false);
  17812. auto handle = cli.open_stream("GET", "/will-close");
  17813. ASSERT_TRUE(handle.is_valid());
  17814. char buf[256];
  17815. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17816. EXPECT_GT(n, 0);
  17817. // Signal server to close
  17818. close_now = true;
  17819. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17820. // Keep reading
  17821. }
  17822. if (n < 0) {
  17823. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17824. handle.get_read_error() == Error::Read)
  17825. << "Actual error: " << to_string(handle.get_read_error());
  17826. }
  17827. svr.stop();
  17828. t.join();
  17829. }
  17830. #endif
  17831. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17832. using namespace httplib;
  17833. // Create a test file
  17834. const char *fname = "etag_testfile.txt";
  17835. const char *content = "etag-content";
  17836. {
  17837. std::ofstream ofs(fname);
  17838. ofs << content;
  17839. ASSERT_TRUE(ofs.good());
  17840. }
  17841. Server svr;
  17842. svr.set_mount_point("/static", ".");
  17843. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17844. svr.wait_until_ready();
  17845. Client cli(HOST, PORT);
  17846. // First request: should get 200 with ETag header
  17847. auto res1 = cli.Get("/static/etag_testfile.txt");
  17848. ASSERT_TRUE(res1);
  17849. ASSERT_EQ(200, res1->status);
  17850. ASSERT_TRUE(res1->has_header("ETag"));
  17851. std::string etag = res1->get_header_value("ETag");
  17852. EXPECT_FALSE(etag.empty());
  17853. // Verify ETag format: W/"hex-hex"
  17854. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17855. EXPECT_EQ('W', etag[0]);
  17856. EXPECT_EQ('/', etag[1]);
  17857. EXPECT_EQ('"', etag[2]);
  17858. EXPECT_EQ('"', etag.back());
  17859. // Exact match: expect 304 Not Modified
  17860. Headers h2 = {{"If-None-Match", etag}};
  17861. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17862. ASSERT_TRUE(res2);
  17863. EXPECT_EQ(304, res2->status);
  17864. // Wildcard match: expect 304 Not Modified
  17865. Headers h3 = {{"If-None-Match", "*"}};
  17866. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17867. ASSERT_TRUE(res3);
  17868. EXPECT_EQ(304, res3->status);
  17869. // Non-matching ETag: expect 200
  17870. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17871. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17872. ASSERT_TRUE(res4);
  17873. EXPECT_EQ(200, res4->status);
  17874. // Multiple ETags with one matching: expect 304
  17875. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17876. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17877. ASSERT_TRUE(res5);
  17878. EXPECT_EQ(304, res5->status);
  17879. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17880. // that equivalent to the single comma-separated list above, so the match on
  17881. // the second line must still be found.
  17882. Headers h6;
  17883. h6.emplace("If-None-Match", "W/\"other\"");
  17884. h6.emplace("If-None-Match", etag);
  17885. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17886. ASSERT_TRUE(res6);
  17887. EXPECT_EQ(304, res6->status);
  17888. svr.stop();
  17889. t.join();
  17890. std::remove(fname);
  17891. }
  17892. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17893. using namespace httplib;
  17894. Server svr;
  17895. svr.set_mount_point("/static", ".");
  17896. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17897. svr.wait_until_ready();
  17898. Client cli(HOST, PORT);
  17899. // Send If-None-Match: * to a non-existent file
  17900. Headers h = {{"If-None-Match", "*"}};
  17901. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17903. EXPECT_EQ(404, res->status);
  17904. svr.stop();
  17905. t.join();
  17906. }
  17907. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17908. using namespace httplib;
  17909. // Create a test file
  17910. const char *fname = "etag_boundary_testfile.txt";
  17911. const char *content = "boundary-test";
  17912. {
  17913. std::ofstream ofs(fname);
  17914. ofs << content;
  17915. ASSERT_TRUE(ofs.good());
  17916. }
  17917. Server svr;
  17918. svr.set_mount_point("/static", ".");
  17919. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17920. svr.wait_until_ready();
  17921. Client cli(HOST, PORT);
  17922. // Get the actual ETag
  17923. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17924. ASSERT_TRUE(res1);
  17925. ASSERT_EQ(200, res1->status);
  17926. ASSERT_TRUE(res1->has_header("ETag"));
  17927. std::string etag = res1->get_header_value("ETag");
  17928. // Test 1: Very long ETag value (longer than actual ETag)
  17929. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17930. Headers h1 = {{"If-None-Match", "W/"
  17931. "\"very-long-etag-value-that-is-much-longer-"
  17932. "than-the-actual-etag-value\""}};
  17933. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17934. ASSERT_TRUE(res2);
  17935. EXPECT_EQ(200, res2->status); // Should not match
  17936. // Test 2: Long string followed by wildcard
  17937. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17938. // string)
  17939. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17940. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17941. ASSERT_TRUE(res3);
  17942. EXPECT_EQ(304, res3->status); // Should match on "*"
  17943. // Test 3: Wildcard followed by long string
  17944. // Should match on "*" immediately and return 304
  17945. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17946. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17947. ASSERT_TRUE(res4);
  17948. EXPECT_EQ(304, res4->status); // Should match on "*"
  17949. // Test 4: Multiple long non-matching values
  17950. // Should NOT match and return 200 (test that all comparisons are safe)
  17951. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17952. "W/\"second-long-non-matching-value\", "
  17953. "W/\"third-long-non-matching-value\""}};
  17954. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17955. ASSERT_TRUE(res5);
  17956. EXPECT_EQ(200, res5->status); // Should not match
  17957. // Test 5: Single character that is not "*" (edge case)
  17958. Headers h5 = {{"If-None-Match", "X"}};
  17959. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17960. ASSERT_TRUE(res6);
  17961. EXPECT_EQ(200, res6->status); // Should not match
  17962. svr.stop();
  17963. t.join();
  17964. std::remove(fname);
  17965. }
  17966. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17967. using namespace httplib;
  17968. // Create a test file
  17969. const char *fname = "ims_testfile.txt";
  17970. const char *content = "if-modified-since-test";
  17971. {
  17972. std::ofstream ofs(fname);
  17973. ofs << content;
  17974. ASSERT_TRUE(ofs.good());
  17975. }
  17976. Server svr;
  17977. svr.set_mount_point("/static", ".");
  17978. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17979. svr.wait_until_ready();
  17980. Client cli(HOST, PORT);
  17981. // First request: should get 200 with Last-Modified header
  17982. auto res1 = cli.Get("/static/ims_testfile.txt");
  17983. ASSERT_TRUE(res1);
  17984. ASSERT_EQ(200, res1->status);
  17985. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17986. std::string last_modified = res1->get_header_value("Last-Modified");
  17987. EXPECT_FALSE(last_modified.empty());
  17988. // If-Modified-Since with same time: expect 304
  17989. Headers h2 = {{"If-Modified-Since", last_modified}};
  17990. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17991. ASSERT_TRUE(res2);
  17992. EXPECT_EQ(304, res2->status);
  17993. // If-Modified-Since with future time: expect 304
  17994. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17995. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17996. ASSERT_TRUE(res3);
  17997. EXPECT_EQ(304, res3->status);
  17998. // If-Modified-Since with past time: expect 200
  17999. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18000. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18001. ASSERT_TRUE(res4);
  18002. EXPECT_EQ(200, res4->status);
  18003. // If-None-Match takes precedence over If-Modified-Since
  18004. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18005. ASSERT_TRUE(res1->has_header("ETag"));
  18006. std::string etag = res1->get_header_value("ETag");
  18007. Headers h5 = {{"If-None-Match", etag},
  18008. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18009. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18010. ASSERT_TRUE(res5);
  18011. EXPECT_EQ(304, res5->status);
  18012. svr.stop();
  18013. t.join();
  18014. std::remove(fname);
  18015. }
  18016. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18017. using namespace httplib;
  18018. Server svr;
  18019. // Endpoint that returns compressible content
  18020. svr.Get("/compressible", [](const Request &, Response &res) {
  18021. // Return a large enough body to trigger compression
  18022. std::string body(1000, 'a');
  18023. res.set_content(body, "text/plain");
  18024. });
  18025. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18026. svr.wait_until_ready();
  18027. Client cli(HOST, PORT);
  18028. // Request with gzip support: should get Vary header when compressed
  18029. cli.set_compress(true);
  18030. auto res1 = cli.Get("/compressible");
  18031. ASSERT_TRUE(res1);
  18032. EXPECT_EQ(200, res1->status);
  18033. // If Content-Encoding is set, Vary should also be set
  18034. if (res1->has_header("Content-Encoding")) {
  18035. EXPECT_TRUE(res1->has_header("Vary"));
  18036. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18037. }
  18038. // Request without Accept-Encoding header: should not have compression
  18039. Headers h_no_compress;
  18040. auto res2 = cli.Get("/compressible", h_no_compress);
  18041. ASSERT_TRUE(res2);
  18042. EXPECT_EQ(200, res2->status);
  18043. // Verify Vary header is present when compression is applied
  18044. // (the exact behavior depends on server configuration)
  18045. svr.stop();
  18046. t.join();
  18047. }
  18048. TEST(ETagTest, IfRangeWithETag) {
  18049. using namespace httplib;
  18050. // Create a test file with known content
  18051. const char *fname = "if_range_testfile.txt";
  18052. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18053. {
  18054. std::ofstream ofs(fname);
  18055. ofs << content;
  18056. ASSERT_TRUE(ofs.good());
  18057. }
  18058. Server svr;
  18059. svr.set_mount_point("/static", ".");
  18060. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18061. svr.wait_until_ready();
  18062. Client cli(HOST, PORT);
  18063. // First request: get ETag
  18064. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18065. ASSERT_TRUE(res1);
  18066. ASSERT_EQ(200, res1->status);
  18067. ASSERT_TRUE(res1->has_header("ETag"));
  18068. std::string etag = res1->get_header_value("ETag");
  18069. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18070. // Since our server generates weak ETags (W/"..."), If-Range with our
  18071. // ETag should NOT result in partial content - it should return full content.
  18072. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18073. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18074. ASSERT_TRUE(res2);
  18075. // Weak ETag in If-Range -> full content (200), not partial (206)
  18076. EXPECT_EQ(200, res2->status);
  18077. EXPECT_EQ(content, res2->body);
  18078. EXPECT_FALSE(res2->has_header("Content-Range"));
  18079. // Range request with non-matching If-Range (ETag): should get 200 (full
  18080. // content)
  18081. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18082. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18083. ASSERT_TRUE(res3);
  18084. EXPECT_EQ(200, res3->status);
  18085. EXPECT_EQ(content, res3->body);
  18086. EXPECT_FALSE(res3->has_header("Content-Range"));
  18087. // Range request with strong ETag (hypothetical - our server doesn't generate
  18088. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18089. // should return full content)
  18090. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18091. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18092. ASSERT_TRUE(res4);
  18093. EXPECT_EQ(200, res4->status);
  18094. EXPECT_EQ(content, res4->body);
  18095. EXPECT_FALSE(res4->has_header("Content-Range"));
  18096. svr.stop();
  18097. t.join();
  18098. std::remove(fname);
  18099. }
  18100. TEST(ETagTest, IfRangeWithDate) {
  18101. using namespace httplib;
  18102. // Create a test file
  18103. const char *fname = "if_range_date_testfile.txt";
  18104. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18105. {
  18106. std::ofstream ofs(fname);
  18107. ofs << content;
  18108. ASSERT_TRUE(ofs.good());
  18109. }
  18110. Server svr;
  18111. svr.set_mount_point("/static", ".");
  18112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18113. svr.wait_until_ready();
  18114. Client cli(HOST, PORT);
  18115. // First request: get Last-Modified
  18116. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18117. ASSERT_TRUE(res1);
  18118. ASSERT_EQ(200, res1->status);
  18119. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18120. std::string last_modified = res1->get_header_value("Last-Modified");
  18121. // Range request with matching If-Range (date): should get 206
  18122. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18123. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18124. ASSERT_TRUE(res2);
  18125. EXPECT_EQ(206, res2->status);
  18126. EXPECT_EQ("FGHIJ", res2->body);
  18127. // Range request with old If-Range date: should get 200 (full content)
  18128. Headers h3 = {{"Range", "bytes=5-9"},
  18129. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18130. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18131. ASSERT_TRUE(res3);
  18132. EXPECT_EQ(200, res3->status);
  18133. EXPECT_EQ(content, res3->body);
  18134. // Range request with future If-Range date: should get 206
  18135. Headers h4 = {{"Range", "bytes=0-4"},
  18136. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18137. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18138. ASSERT_TRUE(res4);
  18139. EXPECT_EQ(206, res4->status);
  18140. EXPECT_EQ("ABCDE", res4->body);
  18141. svr.stop();
  18142. t.join();
  18143. std::remove(fname);
  18144. }
  18145. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18146. using namespace httplib;
  18147. const char *fname = "etag_malformed.txt";
  18148. const char *content = "malformed-etag";
  18149. {
  18150. std::ofstream ofs(fname);
  18151. ofs << content;
  18152. ASSERT_TRUE(ofs.good());
  18153. }
  18154. Server svr;
  18155. svr.set_mount_point("/static", ".");
  18156. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18157. svr.wait_until_ready();
  18158. Client cli(HOST, PORT);
  18159. // baseline: should get 200 and an ETag
  18160. auto res1 = cli.Get("/static/etag_malformed.txt");
  18161. ASSERT_TRUE(res1);
  18162. ASSERT_EQ(200, res1->status);
  18163. ASSERT_TRUE(res1->has_header("ETag"));
  18164. // Malformed ETag value (missing quotes) should be treated as non-matching
  18165. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18166. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18167. ASSERT_TRUE(res_bad);
  18168. EXPECT_EQ(200, res_bad->status);
  18169. // Whitespace-only header value should be considered invalid / non-matching
  18170. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18171. "Host: localhost\r\n"
  18172. "If-None-Match: \r\n"
  18173. "Connection: close\r\n"
  18174. "\r\n";
  18175. std::string out;
  18176. ASSERT_TRUE(send_request(5, raw_req, &out));
  18177. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18178. svr.stop();
  18179. t.join();
  18180. std::remove(fname);
  18181. }
  18182. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18183. using namespace httplib;
  18184. const char *fname = "ims_invalid_format.txt";
  18185. const char *content = "ims-bad-format";
  18186. {
  18187. std::ofstream ofs(fname);
  18188. ofs << content;
  18189. ASSERT_TRUE(ofs.good());
  18190. }
  18191. Server svr;
  18192. svr.set_mount_point("/static", ".");
  18193. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18194. svr.wait_until_ready();
  18195. Client cli(HOST, PORT);
  18196. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18197. ASSERT_TRUE(res1);
  18198. ASSERT_EQ(200, res1->status);
  18199. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18200. // If-Modified-Since with invalid format should not result in 304
  18201. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18202. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18203. ASSERT_TRUE(res_bad);
  18204. EXPECT_EQ(200, res_bad->status);
  18205. // If-Range with invalid date format should be treated as mismatch -> full
  18206. // content (200)
  18207. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18208. {"If-Range", "invalid-date"}};
  18209. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18210. ASSERT_TRUE(res_ifrange);
  18211. EXPECT_EQ(200, res_ifrange->status);
  18212. svr.stop();
  18213. t.join();
  18214. std::remove(fname);
  18215. }
  18216. TEST(ETagTest, IfRangeWithMalformedETag) {
  18217. using namespace httplib;
  18218. const char *fname = "ifrange_malformed.txt";
  18219. const std::string content = "0123456789";
  18220. {
  18221. std::ofstream ofs(fname);
  18222. ofs << content;
  18223. ASSERT_TRUE(ofs.good());
  18224. }
  18225. Server svr;
  18226. svr.set_mount_point("/static", ".");
  18227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18228. svr.wait_until_ready();
  18229. Client cli(HOST, PORT);
  18230. // First request: get ETag
  18231. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18232. ASSERT_TRUE(res1);
  18233. ASSERT_EQ(200, res1->status);
  18234. ASSERT_TRUE(res1->has_header("ETag"));
  18235. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18236. // full content (200)
  18237. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18238. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18239. ASSERT_TRUE(res2);
  18240. EXPECT_EQ(200, res2->status);
  18241. EXPECT_EQ(content, res2->body);
  18242. svr.stop();
  18243. t.join();
  18244. std::remove(fname);
  18245. }
  18246. TEST(ETagTest, ExtremeLargeDateValues) {
  18247. using namespace httplib;
  18248. const char *fname = "ims_extreme_date.txt";
  18249. const char *content = "ims-extreme-date";
  18250. {
  18251. std::ofstream ofs(fname);
  18252. ofs << content;
  18253. ASSERT_TRUE(ofs.good());
  18254. }
  18255. Server svr;
  18256. svr.set_mount_point("/static", ".");
  18257. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18258. svr.wait_until_ready();
  18259. Client cli(HOST, PORT);
  18260. auto res1 = cli.Get(std::string("/static/") + fname);
  18261. ASSERT_TRUE(res1);
  18262. ASSERT_EQ(200, res1->status);
  18263. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18264. // Extremely large year that may overflow date parsing routines.
  18265. Headers h_large_date = {
  18266. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18267. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18268. ASSERT_TRUE(res_bad);
  18269. // Expect server to treat this as invalid/mismatch and return full content
  18270. EXPECT_EQ(200, res_bad->status);
  18271. // If-Range with extremely large date should be treated as mismatch -> full
  18272. // content (200)
  18273. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18274. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18275. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18276. ASSERT_TRUE(res_ifrange);
  18277. EXPECT_EQ(200, res_ifrange->status);
  18278. svr.stop();
  18279. t.join();
  18280. std::remove(fname);
  18281. }
  18282. TEST(ETagTest, NegativeFileModificationTime) {
  18283. using namespace httplib;
  18284. const char *fname = "ims_negative_mtime.txt";
  18285. const std::string content = "negative-mtime";
  18286. {
  18287. std::ofstream ofs(fname);
  18288. ofs << content;
  18289. ASSERT_TRUE(ofs.good());
  18290. }
  18291. // Try to set file mtime to a negative value. This may fail on some
  18292. // platforms/filesystems; if it fails, the test will still verify server
  18293. // behaves safely by performing a regular conditional request.
  18294. #if defined(__APPLE__) || defined(__linux__)
  18295. bool set_negative = false;
  18296. do {
  18297. struct timeval times[2];
  18298. // access time: now
  18299. times[0].tv_sec = time(nullptr);
  18300. times[0].tv_usec = 0;
  18301. // modification time: negative (e.g., -1)
  18302. times[1].tv_sec = -1;
  18303. times[1].tv_usec = 0;
  18304. if (utimes(fname, times) == 0) { set_negative = true; }
  18305. } while (0);
  18306. #else
  18307. bool set_negative = false;
  18308. #endif
  18309. Server svr;
  18310. svr.set_mount_point("/static", ".");
  18311. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18312. svr.wait_until_ready();
  18313. Client cli(HOST, PORT);
  18314. auto res1 = cli.Get(std::string("/static/") + fname);
  18315. ASSERT_TRUE(res1);
  18316. ASSERT_EQ(200, res1->status);
  18317. bool has_last_modified = res1->has_header("Last-Modified");
  18318. std::string last_modified;
  18319. if (has_last_modified) {
  18320. last_modified = res1->get_header_value("Last-Modified");
  18321. }
  18322. if (set_negative) {
  18323. // If we successfully set a negative mtime, ensure server returns a
  18324. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18325. // with an old date and ensure server handles it without crash.
  18326. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18327. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18328. ASSERT_TRUE(res2);
  18329. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18330. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18331. } else {
  18332. // Could not set negative mtime on this platform; fall back to verifying
  18333. // that normal invalid/malformed dates are treated safely (non-304).
  18334. Headers h_bad_date = {
  18335. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18336. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18337. ASSERT_TRUE(res_bad);
  18338. EXPECT_EQ(200, res_bad->status);
  18339. }
  18340. svr.stop();
  18341. t.join();
  18342. std::remove(fname);
  18343. }
  18344. //==============================================================================
  18345. // SSE Parsing Tests
  18346. //==============================================================================
  18347. class SSEParsingTest : public ::testing::Test {
  18348. protected:
  18349. // Test helper that mimics SSE parsing behavior
  18350. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18351. int &retry_ms) {
  18352. // Blank line signals end of event
  18353. if (line.empty() || line == "\r") { return true; }
  18354. // Lines starting with ':' are comments (ignored)
  18355. if (!line.empty() && line[0] == ':') { return false; }
  18356. // Find the colon separator
  18357. auto colon_pos = line.find(':');
  18358. if (colon_pos == std::string::npos) {
  18359. // Line with no colon is treated as field name with empty value
  18360. return false;
  18361. }
  18362. std::string field = line.substr(0, colon_pos);
  18363. std::string value;
  18364. // Value starts after colon, skip optional single space
  18365. if (colon_pos + 1 < line.size()) {
  18366. size_t value_start = colon_pos + 1;
  18367. if (line[value_start] == ' ') { value_start++; }
  18368. value = line.substr(value_start);
  18369. // Remove trailing \r if present
  18370. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18371. }
  18372. // Handle known fields
  18373. if (field == "event") {
  18374. msg.event = value;
  18375. } else if (field == "data") {
  18376. // Multiple data lines are concatenated with newlines
  18377. if (!msg.data.empty()) { msg.data += "\n"; }
  18378. msg.data += value;
  18379. } else if (field == "id") {
  18380. // Empty id is valid (clears the last event ID)
  18381. msg.id = value;
  18382. } else if (field == "retry") {
  18383. // Parse retry interval in milliseconds
  18384. {
  18385. int v = 0;
  18386. auto res =
  18387. detail::from_chars(value.data(), value.data() + value.size(), v);
  18388. if (res.ec == std::errc{}) { retry_ms = v; }
  18389. }
  18390. }
  18391. // Unknown fields are ignored per SSE spec
  18392. return false;
  18393. }
  18394. };
  18395. // Test: Single-line data
  18396. TEST_F(SSEParsingTest, SingleLineData) {
  18397. sse::SSEMessage msg;
  18398. int retry_ms = 3000;
  18399. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18400. EXPECT_EQ(msg.data, "hello");
  18401. EXPECT_EQ(msg.event, "message");
  18402. // Blank line ends event
  18403. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18404. }
  18405. // Test: Multi-line data
  18406. TEST_F(SSEParsingTest, MultiLineData) {
  18407. sse::SSEMessage msg;
  18408. int retry_ms = 3000;
  18409. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18410. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18411. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18412. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18413. }
  18414. // Test: Custom event types
  18415. TEST_F(SSEParsingTest, CustomEventType) {
  18416. sse::SSEMessage msg;
  18417. int retry_ms = 3000;
  18418. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18419. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18420. EXPECT_EQ(msg.event, "update");
  18421. EXPECT_EQ(msg.data, "payload");
  18422. }
  18423. // Test: Event ID handling
  18424. TEST_F(SSEParsingTest, EventIdHandling) {
  18425. sse::SSEMessage msg;
  18426. int retry_ms = 3000;
  18427. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18428. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18429. EXPECT_EQ(msg.id, "12345");
  18430. }
  18431. // Test: Empty event ID (clears last event ID)
  18432. TEST_F(SSEParsingTest, EmptyEventId) {
  18433. sse::SSEMessage msg;
  18434. msg.id = "previous";
  18435. int retry_ms = 3000;
  18436. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18437. EXPECT_EQ(msg.id, "");
  18438. }
  18439. // Test: Retry field parsing
  18440. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18441. sse::SSEMessage msg;
  18442. int retry_ms = 3000;
  18443. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18444. EXPECT_EQ(retry_ms, 5000);
  18445. }
  18446. // Test: Invalid retry value
  18447. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18448. sse::SSEMessage msg;
  18449. int retry_ms = 3000;
  18450. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18451. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18452. }
  18453. // Test: Comments (lines starting with :)
  18454. TEST_F(SSEParsingTest, CommentsIgnored) {
  18455. sse::SSEMessage msg;
  18456. int retry_ms = 3000;
  18457. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18458. EXPECT_EQ(msg.data, "");
  18459. EXPECT_EQ(msg.event, "message");
  18460. }
  18461. // Test: Colon in value
  18462. TEST_F(SSEParsingTest, ColonInValue) {
  18463. sse::SSEMessage msg;
  18464. int retry_ms = 3000;
  18465. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18466. EXPECT_EQ(msg.data, "hello:world:test");
  18467. }
  18468. // Test: Line with no colon (field name only)
  18469. TEST_F(SSEParsingTest, FieldNameOnly) {
  18470. sse::SSEMessage msg;
  18471. int retry_ms = 3000;
  18472. // According to SSE spec, this is treated as field name with empty value
  18473. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18474. // Since we don't recognize "data" without colon, data should be empty
  18475. EXPECT_EQ(msg.data, "");
  18476. }
  18477. // Test: Trailing \r handling
  18478. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18479. sse::SSEMessage msg;
  18480. int retry_ms = 3000;
  18481. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18482. EXPECT_EQ(msg.data, "hello");
  18483. }
  18484. // Test: Unknown fields ignored
  18485. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18486. sse::SSEMessage msg;
  18487. int retry_ms = 3000;
  18488. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18489. EXPECT_EQ(msg.data, "");
  18490. EXPECT_EQ(msg.event, "message");
  18491. }
  18492. // Test: Space after colon is optional
  18493. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18494. sse::SSEMessage msg1, msg2;
  18495. int retry_ms = 3000;
  18496. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18497. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18498. EXPECT_EQ(msg1.data, "hello");
  18499. EXPECT_EQ(msg2.data, "hello");
  18500. }
  18501. // Test: SSEMessage clear
  18502. TEST_F(SSEParsingTest, MessageClear) {
  18503. sse::SSEMessage msg;
  18504. msg.event = "custom";
  18505. msg.data = "some data";
  18506. msg.id = "123";
  18507. msg.clear();
  18508. EXPECT_EQ(msg.event, "message");
  18509. EXPECT_EQ(msg.data, "");
  18510. EXPECT_EQ(msg.id, "");
  18511. }
  18512. // Test: Complete event parsing
  18513. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18514. sse::SSEMessage msg;
  18515. int retry_ms = 3000;
  18516. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18517. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18518. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18519. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18520. // Blank line ends event
  18521. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18522. EXPECT_EQ(msg.event, "notification");
  18523. EXPECT_EQ(msg.id, "evt-42");
  18524. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18525. EXPECT_EQ(retry_ms, 1000);
  18526. }
  18527. //==============================================================================
  18528. // Integration Tests with Server
  18529. //==============================================================================
  18530. class SSEIntegrationTest : public ::testing::Test {
  18531. protected:
  18532. void SetUp() override {
  18533. stop_server_.store(false);
  18534. events_.clear();
  18535. server_ = httplib::detail::make_unique<Server>();
  18536. setup_server();
  18537. start_server();
  18538. }
  18539. void TearDown() override {
  18540. stop_server_.store(true);
  18541. event_cv_.notify_all();
  18542. server_->stop();
  18543. if (server_thread_.joinable()) { server_thread_.join(); }
  18544. }
  18545. void setup_server() {
  18546. // Simple SSE endpoint
  18547. server_->Get("/events", [this](const Request &req, Response &res) {
  18548. auto last_id = req.get_header_value("Last-Event-ID");
  18549. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18550. res.set_chunked_content_provider(
  18551. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18552. std::unique_lock<std::mutex> lock(event_mutex_);
  18553. if (event_cv_.wait_for(
  18554. lock, std::chrono::milliseconds(200), [this] {
  18555. return !events_.empty() || stop_server_.load();
  18556. })) {
  18557. if (stop_server_.load()) { return false; }
  18558. if (!events_.empty()) {
  18559. std::string event = events_.front();
  18560. events_.erase(events_.begin());
  18561. sink.write(event.data(), event.size());
  18562. return true;
  18563. }
  18564. }
  18565. return !stop_server_.load();
  18566. });
  18567. });
  18568. // Endpoint that returns error
  18569. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18570. res.status = 500;
  18571. res.set_content("Internal Server Error", "text/plain");
  18572. });
  18573. // Endpoint for custom event types
  18574. server_->Get("/custom-events", [](const Request &, Response &res) {
  18575. res.set_chunked_content_provider(
  18576. "text/event-stream", [](size_t offset, DataSink &sink) {
  18577. if (offset == 0) {
  18578. std::string event = "event: update\ndata: updated\n\n"
  18579. "event: delete\ndata: deleted\n\n";
  18580. sink.write(event.data(), event.size());
  18581. }
  18582. return false; // End stream after sending
  18583. });
  18584. });
  18585. }
  18586. void start_server() {
  18587. port_ = server_->bind_to_any_port(HOST);
  18588. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18589. // Wait for server to start
  18590. while (!server_->is_running()) {
  18591. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18592. }
  18593. }
  18594. int get_port() const { return port_; }
  18595. void send_event(const std::string &event) {
  18596. std::lock_guard<std::mutex> lock(event_mutex_);
  18597. events_.push_back(event);
  18598. event_cv_.notify_all();
  18599. }
  18600. std::unique_ptr<Server> server_;
  18601. std::thread server_thread_;
  18602. std::mutex event_mutex_;
  18603. std::condition_variable event_cv_;
  18604. std::vector<std::string> events_;
  18605. std::atomic<bool> stop_server_{false};
  18606. std::string last_received_event_id_;
  18607. int port_ = 0;
  18608. };
  18609. // Test: Successful connection and on_open callback
  18610. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18611. // Add a simple endpoint that sends one event and closes
  18612. server_->Get("/simple-event", [](const Request &, Response &res) {
  18613. res.set_chunked_content_provider(
  18614. "text/event-stream", [](size_t offset, DataSink &sink) {
  18615. if (offset == 0) {
  18616. std::string event = "data: hello\n\n";
  18617. sink.write(event.data(), event.size());
  18618. }
  18619. return false; // Close stream after sending
  18620. });
  18621. });
  18622. Client client("localhost", get_port());
  18623. sse::SSEClient sse(client, "/simple-event");
  18624. std::atomic<bool> open_called{false};
  18625. std::atomic<bool> message_received{false};
  18626. sse.on_open([&open_called]() { open_called.store(true); });
  18627. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18628. if (msg.data == "hello") { message_received.store(true); }
  18629. });
  18630. sse.set_reconnect_interval(100);
  18631. sse.set_max_reconnect_attempts(1);
  18632. // Start async
  18633. sse.start_async();
  18634. // Wait for message to be processed
  18635. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18636. sse.stop();
  18637. EXPECT_TRUE(open_called.load());
  18638. EXPECT_TRUE(message_received.load());
  18639. }
  18640. // Test: on_message callback
  18641. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18642. // Endpoint that sends multiple events then closes
  18643. server_->Get("/multi-event", [](const Request &, Response &res) {
  18644. res.set_chunked_content_provider(
  18645. "text/event-stream", [](size_t offset, DataSink &sink) {
  18646. if (offset == 0) {
  18647. std::string events = "data: message1\n\ndata: message2\n\n";
  18648. sink.write(events.data(), events.size());
  18649. }
  18650. return false;
  18651. });
  18652. });
  18653. Client client("localhost", get_port());
  18654. sse::SSEClient sse(client, "/multi-event");
  18655. std::vector<std::string> received_messages;
  18656. std::mutex messages_mutex;
  18657. sse.on_message([&](const sse::SSEMessage &msg) {
  18658. std::lock_guard<std::mutex> lock(messages_mutex);
  18659. received_messages.push_back(msg.data);
  18660. });
  18661. sse.set_reconnect_interval(100);
  18662. sse.set_max_reconnect_attempts(1);
  18663. sse.start_async();
  18664. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18665. sse.stop();
  18666. std::lock_guard<std::mutex> lock(messages_mutex);
  18667. EXPECT_GE(received_messages.size(), 2u);
  18668. if (received_messages.size() >= 2) {
  18669. EXPECT_EQ(received_messages[0], "message1");
  18670. EXPECT_EQ(received_messages[1], "message2");
  18671. }
  18672. }
  18673. // Test: on_event for specific types
  18674. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18675. Client client("localhost", get_port());
  18676. sse::SSEClient sse(client, "/custom-events");
  18677. std::atomic<bool> update_received{false};
  18678. std::atomic<bool> delete_received{false};
  18679. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18680. if (msg.data == "updated") { update_received.store(true); }
  18681. });
  18682. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18683. if (msg.data == "deleted") { delete_received.store(true); }
  18684. });
  18685. sse.set_max_reconnect_attempts(1);
  18686. sse.start_async();
  18687. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18688. sse.stop();
  18689. EXPECT_TRUE(update_received.load());
  18690. EXPECT_TRUE(delete_received.load());
  18691. }
  18692. // Test: on_error callback on connection failure
  18693. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18694. // Connect to a non-existent port
  18695. Client client("localhost", 59999);
  18696. sse::SSEClient sse(client, "/events");
  18697. std::atomic<bool> error_called{false};
  18698. Error received_error = Error::Success;
  18699. sse.on_error([&](Error err) {
  18700. error_called.store(true);
  18701. received_error = err;
  18702. });
  18703. sse.set_reconnect_interval(50);
  18704. sse.set_max_reconnect_attempts(1);
  18705. sse.start_async();
  18706. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18707. sse.stop();
  18708. EXPECT_TRUE(error_called.load());
  18709. EXPECT_NE(received_error, Error::Success);
  18710. }
  18711. // Test: Last-Event-ID header sent on reconnect
  18712. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18713. // Endpoint that sends event with ID
  18714. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18715. res.set_chunked_content_provider(
  18716. "text/event-stream", [](size_t offset, DataSink &sink) {
  18717. if (offset == 0) {
  18718. std::string event = "id: evt-123\ndata: test\n\n";
  18719. sink.write(event.data(), event.size());
  18720. }
  18721. return false;
  18722. });
  18723. });
  18724. Client client("localhost", get_port());
  18725. sse::SSEClient sse(client, "/event-with-id");
  18726. std::atomic<bool> id_received{false};
  18727. sse.on_message([&](const sse::SSEMessage &msg) {
  18728. if (!msg.id.empty()) { id_received.store(true); }
  18729. });
  18730. sse.set_reconnect_interval(100);
  18731. sse.set_max_reconnect_attempts(1);
  18732. sse.start_async();
  18733. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18734. sse.stop();
  18735. EXPECT_TRUE(id_received.load());
  18736. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18737. }
  18738. // Test: Manual stop
  18739. TEST_F(SSEIntegrationTest, ManualStop) {
  18740. // Endpoint that sends one event and stays open briefly
  18741. std::atomic<bool> handler_running{true};
  18742. server_->Get("/stay-open", [&handler_running](const Request &,
  18743. Response &res) {
  18744. res.set_chunked_content_provider(
  18745. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18746. if (offset == 0) {
  18747. std::string event = "data: connected\n\n";
  18748. sink.write(event.data(), event.size());
  18749. }
  18750. // Keep connection open while handler_running is true
  18751. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18752. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18753. }
  18754. return false;
  18755. });
  18756. });
  18757. Client client("localhost", get_port());
  18758. sse::SSEClient sse(client, "/stay-open");
  18759. std::atomic<bool> connected{false};
  18760. sse.on_open([&connected]() { connected.store(true); });
  18761. sse.set_reconnect_interval(100);
  18762. sse.set_max_reconnect_attempts(1);
  18763. sse.start_async();
  18764. // Wait for connection to establish
  18765. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18766. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18767. }
  18768. EXPECT_TRUE(connected.load());
  18769. EXPECT_TRUE(sse.is_connected());
  18770. // Signal handler to stop
  18771. handler_running.store(false);
  18772. // Stop SSE client
  18773. sse.stop();
  18774. EXPECT_FALSE(sse.is_connected());
  18775. }
  18776. // Test: SSEClient with custom headers
  18777. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18778. // Setup a server endpoint that checks for custom header
  18779. std::atomic<bool> header_received{false};
  18780. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18781. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18782. header_received.store(true);
  18783. }
  18784. res.set_chunked_content_provider("text/event-stream",
  18785. [](size_t, DataSink &) { return false; });
  18786. });
  18787. Client client("localhost", get_port());
  18788. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18789. sse::SSEClient sse(client, "/header-check", headers);
  18790. sse.set_max_reconnect_attempts(1);
  18791. sse.start_async();
  18792. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18793. sse.stop();
  18794. EXPECT_TRUE(header_received.load());
  18795. }
  18796. // Test: Reconnect interval configuration
  18797. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18798. Client client("localhost", get_port());
  18799. sse::SSEClient sse(client, "/events");
  18800. auto &result = sse.set_reconnect_interval(500);
  18801. // Builder pattern should return reference to self
  18802. EXPECT_EQ(&result, &sse);
  18803. }
  18804. // Test: Max reconnect attempts
  18805. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18806. // Connect to non-existent port to force reconnects
  18807. Client client("localhost", 59998);
  18808. sse::SSEClient sse(client, "/events");
  18809. std::atomic<int> error_count{0};
  18810. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18811. sse.set_reconnect_interval(50);
  18812. sse.set_max_reconnect_attempts(2);
  18813. auto start = std::chrono::steady_clock::now();
  18814. sse.start(); // Blocking call
  18815. auto end = std::chrono::steady_clock::now();
  18816. // Should have stopped after 2 failed attempts
  18817. EXPECT_GE(error_count.load(), 2);
  18818. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18819. auto duration =
  18820. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18821. #ifdef _WIN32
  18822. // Windows is much slower for socket connection failures
  18823. EXPECT_LT(duration.count(), 7000);
  18824. #else
  18825. EXPECT_LT(duration.count(), 1000);
  18826. #endif
  18827. }
  18828. // Test: Multi-line data in integration
  18829. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18830. // Endpoint with multi-line data
  18831. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18832. res.set_chunked_content_provider(
  18833. "text/event-stream", [](size_t offset, DataSink &sink) {
  18834. if (offset == 0) {
  18835. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18836. sink.write(event.data(), event.size());
  18837. }
  18838. return false;
  18839. });
  18840. });
  18841. Client client("localhost", get_port());
  18842. sse::SSEClient sse(client, "/multiline-data");
  18843. std::string received_data;
  18844. std::mutex data_mutex;
  18845. sse.on_message([&](const sse::SSEMessage &msg) {
  18846. std::lock_guard<std::mutex> lock(data_mutex);
  18847. received_data = msg.data;
  18848. });
  18849. sse.set_reconnect_interval(100);
  18850. sse.set_max_reconnect_attempts(1);
  18851. sse.start_async();
  18852. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18853. sse.stop();
  18854. std::lock_guard<std::mutex> lock(data_mutex);
  18855. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18856. }
  18857. // Test: Auto-reconnect after server disconnection
  18858. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18859. std::atomic<int> connection_count{0};
  18860. std::atomic<int> message_count{0};
  18861. // Endpoint that sends one event and closes, forcing reconnect
  18862. server_->Get("/reconnect-test",
  18863. [&connection_count](const Request &, Response &res) {
  18864. connection_count.fetch_add(1);
  18865. res.set_chunked_content_provider(
  18866. "text/event-stream", [](size_t offset, DataSink &sink) {
  18867. if (offset == 0) {
  18868. std::string event = "data: hello\n\n";
  18869. sink.write(event.data(), event.size());
  18870. }
  18871. return false; // Close connection after sending
  18872. });
  18873. });
  18874. Client client("localhost", get_port());
  18875. sse::SSEClient sse(client, "/reconnect-test");
  18876. sse.on_message([&message_count](const sse::SSEMessage &) {
  18877. message_count.fetch_add(1);
  18878. });
  18879. sse.set_reconnect_interval(100);
  18880. sse.set_max_reconnect_attempts(3);
  18881. sse.start_async();
  18882. // Wait long enough for multiple reconnects
  18883. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18884. sse.stop();
  18885. // Should have connected multiple times (initial + reconnects)
  18886. EXPECT_GE(connection_count.load(), 2);
  18887. // Should have received messages from multiple connections
  18888. EXPECT_GE(message_count.load(), 2);
  18889. }
  18890. // Test: Last-Event-ID sent on reconnect
  18891. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18892. std::atomic<int> connection_count{0};
  18893. std::vector<std::string> received_last_event_ids;
  18894. std::mutex id_mutex;
  18895. // Endpoint that checks Last-Event-ID header and sends event with ID
  18896. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18897. int conn = connection_count.fetch_add(1);
  18898. // Capture the Last-Event-ID header from each connection
  18899. {
  18900. std::lock_guard<std::mutex> lock(id_mutex);
  18901. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18902. }
  18903. res.set_chunked_content_provider(
  18904. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18905. if (offset == 0) {
  18906. std::string event =
  18907. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18908. sink.write(event.data(), event.size());
  18909. }
  18910. return false;
  18911. });
  18912. });
  18913. Client client("localhost", get_port());
  18914. sse::SSEClient sse(client, "/reconnect-with-id");
  18915. sse.set_reconnect_interval(100);
  18916. sse.set_max_reconnect_attempts(3);
  18917. sse.start_async();
  18918. // Wait for at least 2 connections
  18919. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18920. sse.stop();
  18921. // Verify behavior
  18922. std::lock_guard<std::mutex> lock(id_mutex);
  18923. EXPECT_GE(received_last_event_ids.size(), 2u);
  18924. // First connection should have no Last-Event-ID
  18925. if (!received_last_event_ids.empty()) {
  18926. EXPECT_EQ(received_last_event_ids[0], "");
  18927. }
  18928. // Second connection should have Last-Event-ID from first connection
  18929. if (received_last_event_ids.size() >= 2) {
  18930. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18931. }
  18932. }
  18933. // Test: set_headers updates headers used on reconnect
  18934. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18935. std::vector<std::string> received_tokens;
  18936. std::mutex token_mutex;
  18937. // Endpoint that captures Authorization header
  18938. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18939. {
  18940. std::lock_guard<std::mutex> lock(token_mutex);
  18941. received_tokens.push_back(req.get_header_value("Authorization"));
  18942. }
  18943. res.set_chunked_content_provider(
  18944. "text/event-stream", [](size_t offset, DataSink &sink) {
  18945. if (offset == 0) {
  18946. std::string event = "data: hello\n\n";
  18947. sink.write(event.data(), event.size());
  18948. }
  18949. return false; // Close connection to trigger reconnect
  18950. });
  18951. });
  18952. Client client("localhost", get_port());
  18953. Headers headers = {{"Authorization", "Bearer old-token"}};
  18954. sse::SSEClient sse(client, "/auth-check", headers);
  18955. // Update headers on each successful connection
  18956. sse.on_open(
  18957. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18958. sse.set_reconnect_interval(100);
  18959. sse.set_max_reconnect_attempts(3);
  18960. sse.start_async();
  18961. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18962. sse.stop();
  18963. std::lock_guard<std::mutex> lock(token_mutex);
  18964. ASSERT_GE(received_tokens.size(), 2u);
  18965. // First connection uses original header
  18966. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18967. // Second connection uses updated header from set_headers
  18968. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18969. }
  18970. // Test: 401 allows reconnection (so on_error can refresh headers)
  18971. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18972. std::atomic<int> connection_count{0};
  18973. // Endpoint: returns 401 on first attempt, 200 on second
  18974. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18975. int conn = connection_count.fetch_add(1);
  18976. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18977. res.status = StatusCode::Unauthorized_401;
  18978. res.set_content("Unauthorized", "text/plain");
  18979. return;
  18980. }
  18981. res.set_chunked_content_provider(
  18982. "text/event-stream", [](size_t offset, DataSink &sink) {
  18983. if (offset == 0) {
  18984. std::string event = "data: authenticated\n\n";
  18985. sink.write(event.data(), event.size());
  18986. }
  18987. return false;
  18988. });
  18989. });
  18990. Client client("localhost", get_port());
  18991. Headers headers = {{"Authorization", "Bearer expired"}};
  18992. sse::SSEClient sse(client, "/auth-retry", headers);
  18993. std::atomic<bool> message_received{false};
  18994. // Refresh token on error
  18995. sse.on_error(
  18996. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18997. sse.on_message([&](const sse::SSEMessage &msg) {
  18998. if (msg.data == "authenticated") { message_received.store(true); }
  18999. });
  19000. sse.set_reconnect_interval(100);
  19001. sse.set_max_reconnect_attempts(3);
  19002. sse.start_async();
  19003. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19004. sse.stop();
  19005. // Should have reconnected after 401 and succeeded with new token
  19006. EXPECT_GE(connection_count.load(), 2);
  19007. EXPECT_TRUE(message_received.load());
  19008. }
  19009. TEST(Issue2318Test, EmptyHostString) {
  19010. {
  19011. httplib::Client cli_empty("", PORT);
  19012. auto res = cli_empty.Get("/");
  19013. ASSERT_FALSE(res);
  19014. EXPECT_EQ(httplib::Error::Connection, res.error());
  19015. }
  19016. {
  19017. httplib::Client cli(" ", PORT);
  19018. auto res = cli.Get("/");
  19019. ASSERT_FALSE(res);
  19020. EXPECT_EQ(httplib::Error::Connection, res.error());
  19021. }
  19022. }
  19023. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19024. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19025. Server svr;
  19026. // Set a small payload limit (1KB)
  19027. svr.set_payload_max_length(1024);
  19028. svr.Post("/test", [&](const Request &req, Response &res) {
  19029. res.set_content("Body size: " + std::to_string(req.body.size()),
  19030. "text/plain");
  19031. });
  19032. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19033. auto se = detail::scope_exit([&] {
  19034. svr.stop();
  19035. listen_thread.join();
  19036. });
  19037. svr.wait_until_ready();
  19038. // Create data that compresses well but exceeds limit when decompressed
  19039. // 8KB of repeated null bytes compresses to a very small size
  19040. std::string original_data(8 * 1024, '\0');
  19041. // Compress the data using gzip
  19042. std::string compressed_data;
  19043. detail::gzip_compressor compressor;
  19044. compressor.compress(original_data.data(), original_data.size(), true,
  19045. [&](const char *data, size_t size) {
  19046. compressed_data.append(data, size);
  19047. return true;
  19048. });
  19049. // Verify compression worked (compressed should be much smaller)
  19050. ASSERT_LT(compressed_data.size(), original_data.size());
  19051. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19052. // Send compressed data with Content-Encoding: gzip
  19053. Client cli(HOST, PORT);
  19054. Headers headers = {{"Content-Encoding", "gzip"}};
  19055. auto res =
  19056. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19057. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19059. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19060. }
  19061. #endif
  19062. // ============================================================================
  19063. // OpenSSL-Specific Tests
  19064. // ============================================================================
  19065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19066. X509 *readCertificate(const std::string &strFileName) {
  19067. std::ifstream inStream(strFileName);
  19068. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19069. std::istreambuf_iterator<char>());
  19070. if (strCertPEM.empty()) return (nullptr);
  19071. BIO *pbCert = BIO_new(BIO_s_mem());
  19072. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19073. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19074. BIO_free(pbCert);
  19075. return (pCert);
  19076. }
  19077. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19078. std::ifstream inStream(strFileName);
  19079. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19080. std::istreambuf_iterator<char>());
  19081. if (strPrivateKeyPEM.empty()) return (nullptr);
  19082. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19083. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19084. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19085. BIO_free(pbPrivKey);
  19086. return (pPrivateKey);
  19087. }
  19088. TEST(BindServerTest, UpdateCerts) {
  19089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19090. int port = svr.bind_to_any_port("0.0.0.0");
  19091. ASSERT_TRUE(svr.is_valid());
  19092. ASSERT_TRUE(port > 0);
  19093. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19094. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19095. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19096. ASSERT_TRUE(cert != nullptr);
  19097. ASSERT_TRUE(ca_cert != nullptr);
  19098. ASSERT_TRUE(key != nullptr);
  19099. X509_STORE *cert_store = X509_STORE_new();
  19100. X509_STORE_add_cert(cert_store, ca_cert);
  19101. // svr.update_certs(cert, key, cert_store); // deprecated
  19102. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19103. CLIENT_CA_CERT_FILE);
  19104. ASSERT_TRUE(svr.is_valid());
  19105. svr.stop();
  19106. X509_STORE_free(cert_store);
  19107. X509_free(cert);
  19108. X509_free(ca_cert);
  19109. EVP_PKEY_free(key);
  19110. }
  19111. // Test that update_certs() updates client CA list correctly
  19112. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19113. // Start with file-based constructor
  19114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19115. ASSERT_TRUE(svr.is_valid());
  19116. // Initially no client CA list should be set
  19117. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19118. ASSERT_TRUE(ssl_ctx != nullptr);
  19119. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19120. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19121. EXPECT_EQ(0, count_before);
  19122. // Now update with client CA (PEM string)
  19123. std::string cert_pem, key_pem, ca_pem;
  19124. read_file(SERVER_CERT_FILE, cert_pem);
  19125. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19126. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19127. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19128. ASSERT_TRUE(svr.is_valid());
  19129. // Now client CA list should be set
  19130. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19131. ASSERT_TRUE(ca_list_after != nullptr);
  19132. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19133. }
  19134. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19135. // Test that the file-path SSLServer constructor properly sets the client CA
  19136. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19138. ASSERT_TRUE(svr.is_valid());
  19139. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19140. ASSERT_TRUE(ssl_ctx != nullptr);
  19141. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19142. ASSERT_TRUE(ca_list != nullptr);
  19143. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19144. }
  19145. #endif
  19146. // ============================================================================
  19147. // MbedTLS-Specific Tests
  19148. // ============================================================================
  19149. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19150. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19151. using namespace httplib::tls;
  19152. // Track if callback was invoked
  19153. bool callback_invoked = false;
  19154. // The callback receives void* ctx which is actually MbedTlsContext*
  19155. // We can access the mbedtls_ssl_config via the context
  19156. auto setup_callback = [&callback_invoked](void *ctx) {
  19157. callback_invoked = true;
  19158. // Cast to MbedTlsContext* to access the ssl config
  19159. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19160. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19161. // Use static variables to hold certificate data (simplified for test)
  19162. static mbedtls_x509_crt own_cert;
  19163. static mbedtls_pk_context own_key;
  19164. static mbedtls_x509_crt ca_chain;
  19165. static bool initialized = false;
  19166. if (!initialized) {
  19167. mbedtls_x509_crt_init(&own_cert);
  19168. mbedtls_pk_init(&own_key);
  19169. mbedtls_x509_crt_init(&ca_chain);
  19170. // Load server certificate
  19171. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19172. return false;
  19173. }
  19174. // Load server private key.
  19175. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19176. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19177. #if MBEDTLS_VERSION_MAJOR == 3
  19178. ,
  19179. mbedtls_ctr_drbg_random, nullptr
  19180. #endif
  19181. ) != 0) {
  19182. return false;
  19183. }
  19184. // Load CA chain for client verification
  19185. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19186. return false;
  19187. }
  19188. initialized = true;
  19189. }
  19190. // Configure the SSL config
  19191. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19192. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19193. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19194. // Set minimum TLS version using mbedTLS native API
  19195. #if MBEDTLS_VERSION_MAJOR >= 3
  19196. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19197. #else
  19198. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19199. MBEDTLS_SSL_MINOR_VERSION_3);
  19200. #endif
  19201. return true;
  19202. };
  19203. SSLServer svr(setup_callback);
  19204. ASSERT_TRUE(svr.is_valid());
  19205. ASSERT_TRUE(callback_invoked);
  19206. svr.Get("/test", [&](const Request &req, Response &res) {
  19207. res.set_content("test", "text/plain");
  19208. auto cert = req.peer_cert();
  19209. ASSERT_TRUE(static_cast<bool>(cert));
  19210. auto common_name = cert.subject_cn();
  19211. EXPECT_EQ("Common Name", common_name);
  19212. });
  19213. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19214. auto se = detail::scope_exit([&] {
  19215. svr.stop();
  19216. t.join();
  19217. ASSERT_FALSE(svr.is_running());
  19218. });
  19219. svr.wait_until_ready();
  19220. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19221. cli.enable_server_certificate_verification(false);
  19222. cli.set_connection_timeout(30);
  19223. auto res = cli.Get("/test");
  19224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19225. ASSERT_EQ(StatusCode::OK_200, res->status);
  19226. }
  19227. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19228. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19229. // keep-alive SSL session, which reads through that config in
  19230. // mbedtls_ssl_close_notify.
  19231. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19233. ASSERT_TRUE(svr.is_valid());
  19234. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19235. res.set_content("test", "text/plain");
  19236. });
  19237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19238. auto se = detail::scope_exit([&] {
  19239. svr.stop();
  19240. t.join();
  19241. ASSERT_FALSE(svr.is_running());
  19242. });
  19243. svr.wait_until_ready();
  19244. {
  19245. SSLClient cli(HOST, PORT);
  19246. cli.enable_server_certificate_verification(false);
  19247. cli.set_keep_alive(true);
  19248. auto res = cli.Get("/test");
  19249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19250. ASSERT_EQ(StatusCode::OK_200, res->status);
  19251. // cli is destructed here with the keep-alive SSL session still open.
  19252. }
  19253. }
  19254. #endif
  19255. // WebSocket Tests
  19256. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19257. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19258. // defining the meaning of these bits has been negotiated.
  19259. auto make_frame = [](uint8_t first_byte) {
  19260. std::string frame;
  19261. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19262. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19263. frame += "Hello";
  19264. return frame;
  19265. };
  19266. // RSV1 set (0x40)
  19267. {
  19268. detail::BufferStream strm;
  19269. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19270. ws::Opcode opcode;
  19271. std::string payload;
  19272. bool fin;
  19273. EXPECT_EQ(
  19274. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19275. ws::impl::FrameRead::Fail);
  19276. }
  19277. // RSV2 set (0x20)
  19278. {
  19279. detail::BufferStream strm;
  19280. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19281. ws::Opcode opcode;
  19282. std::string payload;
  19283. bool fin;
  19284. EXPECT_EQ(
  19285. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19286. ws::impl::FrameRead::Fail);
  19287. }
  19288. // RSV3 set (0x10)
  19289. {
  19290. detail::BufferStream strm;
  19291. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19292. ws::Opcode opcode;
  19293. std::string payload;
  19294. bool fin;
  19295. EXPECT_EQ(
  19296. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19297. ws::impl::FrameRead::Fail);
  19298. }
  19299. // No RSV bits set - should succeed
  19300. {
  19301. detail::BufferStream strm;
  19302. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19303. ws::Opcode opcode;
  19304. std::string payload;
  19305. bool fin;
  19306. EXPECT_EQ(
  19307. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19308. ws::impl::FrameRead::Ok);
  19309. EXPECT_EQ(ws::Opcode::Text, opcode);
  19310. EXPECT_EQ("Hello", payload);
  19311. EXPECT_TRUE(fin);
  19312. }
  19313. }
  19314. TEST(WebSocketTest, ControlFrameValidation) {
  19315. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19316. // payload length <= 125.
  19317. // Ping with FIN=0 - must be rejected
  19318. {
  19319. detail::BufferStream strm;
  19320. std::string frame;
  19321. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19322. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19323. strm.write(frame.data(), frame.size());
  19324. ws::Opcode opcode;
  19325. std::string payload;
  19326. bool fin;
  19327. EXPECT_EQ(
  19328. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19329. ws::impl::FrameRead::Fail);
  19330. }
  19331. // Close with FIN=0 - must be rejected
  19332. {
  19333. detail::BufferStream strm;
  19334. std::string frame;
  19335. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19336. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19337. strm.write(frame.data(), frame.size());
  19338. ws::Opcode opcode;
  19339. std::string payload;
  19340. bool fin;
  19341. EXPECT_EQ(
  19342. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19343. ws::impl::FrameRead::Fail);
  19344. }
  19345. // Ping with payload_len=126 (extended length) - must be rejected
  19346. {
  19347. detail::BufferStream strm;
  19348. std::string frame;
  19349. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19350. frame += static_cast<char>(126); // payload_len=126 (>125)
  19351. frame += static_cast<char>(0x00); // extended length high byte
  19352. frame += static_cast<char>(126); // extended length low byte
  19353. frame += std::string(126, 'x');
  19354. strm.write(frame.data(), frame.size());
  19355. ws::Opcode opcode;
  19356. std::string payload;
  19357. bool fin;
  19358. EXPECT_EQ(
  19359. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19360. ws::impl::FrameRead::Fail);
  19361. }
  19362. // Ping with FIN=1 and payload_len=125 - should succeed
  19363. {
  19364. detail::BufferStream strm;
  19365. std::string frame;
  19366. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19367. frame += static_cast<char>(125); // payload_len=125
  19368. frame += std::string(125, 'x');
  19369. strm.write(frame.data(), frame.size());
  19370. ws::Opcode opcode;
  19371. std::string payload;
  19372. bool fin;
  19373. EXPECT_EQ(
  19374. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19375. ws::impl::FrameRead::Ok);
  19376. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19377. EXPECT_EQ(125u, payload.size());
  19378. EXPECT_TRUE(fin);
  19379. }
  19380. }
  19381. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19382. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19383. // length MUST be 0.
  19384. // MSB set - must be rejected
  19385. {
  19386. detail::BufferStream strm;
  19387. std::string frame;
  19388. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19389. frame += static_cast<char>(127); // 64-bit extended length
  19390. frame += static_cast<char>(0x80); // MSB set (invalid)
  19391. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19392. strm.write(frame.data(), frame.size());
  19393. ws::Opcode opcode;
  19394. std::string payload;
  19395. bool fin;
  19396. EXPECT_EQ(
  19397. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19398. ws::impl::FrameRead::Fail);
  19399. }
  19400. // MSB clear - should pass length parsing (will be rejected by max_len,
  19401. // but that's a different check; use a small length to verify)
  19402. {
  19403. detail::BufferStream strm;
  19404. std::string frame;
  19405. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19406. frame += static_cast<char>(127); // 64-bit extended length
  19407. frame += std::string(7, '\0'); // high bytes = 0
  19408. frame += static_cast<char>(0x03); // length = 3
  19409. frame += "abc";
  19410. strm.write(frame.data(), frame.size());
  19411. ws::Opcode opcode;
  19412. std::string payload;
  19413. bool fin;
  19414. EXPECT_EQ(
  19415. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19416. ws::impl::FrameRead::Ok);
  19417. EXPECT_EQ(ws::Opcode::Text, opcode);
  19418. EXPECT_EQ("abc", payload);
  19419. }
  19420. }
  19421. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19422. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19423. // Valid UTF-8
  19424. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19425. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19426. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19427. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19428. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19429. // Invalid UTF-8
  19430. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19431. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19432. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19433. EXPECT_FALSE(
  19434. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19435. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19436. }
  19437. TEST(WebSocketTest, ConnectAndDisconnect) {
  19438. Server svr;
  19439. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19440. std::string msg;
  19441. while (ws.read(msg)) {}
  19442. });
  19443. auto port = svr.bind_to_any_port(HOST);
  19444. std::thread t([&]() { svr.listen_after_bind(); });
  19445. svr.wait_until_ready();
  19446. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19447. auto res = client.connect();
  19448. ASSERT_TRUE(res);
  19449. EXPECT_EQ(Error::Success, res.error());
  19450. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19451. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19452. EXPECT_TRUE(client.is_open());
  19453. client.close();
  19454. EXPECT_FALSE(client.is_open());
  19455. svr.stop();
  19456. t.join();
  19457. }
  19458. TEST(WebSocketTest, ValidURL) {
  19459. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19460. EXPECT_TRUE(ws1.is_valid());
  19461. ws::WebSocketClient ws2("ws://example.com/path");
  19462. EXPECT_TRUE(ws2.is_valid());
  19463. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19464. EXPECT_TRUE(ws3.is_valid());
  19465. #ifdef CPPHTTPLIB_SSL_ENABLED
  19466. ws::WebSocketClient wss1("wss://example.com/path");
  19467. EXPECT_TRUE(wss1.is_valid());
  19468. ws::WebSocketClient wss2("wss://example.com:443/path");
  19469. EXPECT_TRUE(wss2.is_valid());
  19470. #endif
  19471. }
  19472. TEST(WebSocketTest, InvalidURL) {
  19473. // No scheme
  19474. ws::WebSocketClient ws1("localhost:8080/path");
  19475. EXPECT_FALSE(ws1.is_valid());
  19476. // No path
  19477. ws::WebSocketClient ws2("ws://localhost:8080");
  19478. EXPECT_FALSE(ws2.is_valid());
  19479. // Empty string
  19480. ws::WebSocketClient ws3("");
  19481. EXPECT_FALSE(ws3.is_valid());
  19482. // Missing host
  19483. ws::WebSocketClient ws4("ws://:8080/path");
  19484. EXPECT_FALSE(ws4.is_valid());
  19485. // Port number overflow — should not crash
  19486. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19487. EXPECT_FALSE(ws5.is_valid());
  19488. // Port out of range
  19489. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19490. EXPECT_FALSE(ws6.is_valid());
  19491. }
  19492. TEST(WebSocketTest, UnsupportedScheme) {
  19493. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19494. ws::WebSocketClient ws1("http://localhost:8080/path");
  19495. EXPECT_FALSE(ws1.is_valid());
  19496. ws::WebSocketClient ws2("https://localhost:8080/path");
  19497. EXPECT_FALSE(ws2.is_valid());
  19498. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19499. EXPECT_FALSE(ws3.is_valid());
  19500. #else
  19501. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19502. std::invalid_argument);
  19503. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19504. std::invalid_argument);
  19505. #endif
  19506. }
  19507. TEST(WebSocketTest, ConnectWhenInvalid) {
  19508. ws::WebSocketClient ws("not a valid url");
  19509. EXPECT_FALSE(ws.is_valid());
  19510. auto res = ws.connect();
  19511. EXPECT_FALSE(res);
  19512. EXPECT_EQ(Error::Connection, res.error());
  19513. EXPECT_EQ(-1, res.status());
  19514. }
  19515. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19516. // Grab a port that is free, then close it again so nothing listens there
  19517. Server svr;
  19518. auto port = svr.bind_to_any_port(HOST);
  19519. svr.stop();
  19520. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19521. auto res = client.connect();
  19522. ASSERT_FALSE(res);
  19523. EXPECT_EQ(Error::Connection, res.error());
  19524. EXPECT_EQ(-1, res.status());
  19525. }
  19526. TEST(WebSocketTest, DefaultPort) {
  19527. ws::WebSocketClient ws1("ws://example.com/path");
  19528. EXPECT_TRUE(ws1.is_valid());
  19529. // ws:// defaults to port 80 (verified by successful parse)
  19530. #ifdef CPPHTTPLIB_SSL_ENABLED
  19531. ws::WebSocketClient ws2("wss://example.com/path");
  19532. EXPECT_TRUE(ws2.is_valid());
  19533. // wss:// defaults to port 443 (verified by successful parse)
  19534. #endif
  19535. }
  19536. TEST(WebSocketTest, IPv6LiteralAddress) {
  19537. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19538. EXPECT_TRUE(ws1.is_valid());
  19539. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19540. EXPECT_TRUE(ws2.is_valid());
  19541. }
  19542. TEST(WebSocketTest, ComplexPath) {
  19543. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19544. EXPECT_TRUE(ws1.is_valid());
  19545. ws::WebSocketClient ws2("ws://localhost:8080/");
  19546. EXPECT_TRUE(ws2.is_valid());
  19547. }
  19548. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19549. Server svr;
  19550. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19551. std::string msg;
  19552. while (ws.read(msg)) {}
  19553. });
  19554. auto port = svr.bind_to_any_port(HOST);
  19555. std::thread t([&]() { svr.listen_after_bind(); });
  19556. svr.wait_until_ready();
  19557. auto another_host = "example.com";
  19558. auto wrong_ip = "192.0.2.1";
  19559. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19560. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19561. ASSERT_TRUE(client.connect());
  19562. EXPECT_TRUE(client.is_open());
  19563. client.close();
  19564. svr.stop();
  19565. t.join();
  19566. }
  19567. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19568. Server svr;
  19569. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19570. std::string msg;
  19571. while (ws.read(msg)) {}
  19572. });
  19573. auto port = svr.bind_to_any_port(HOST);
  19574. std::thread t([&]() { svr.listen_after_bind(); });
  19575. svr.wait_until_ready();
  19576. auto wrong_ip = "192.0.2.1";
  19577. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19578. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19579. client.set_connection_timeout(1);
  19580. client.set_read_timeout(1);
  19581. client.set_write_timeout(1);
  19582. EXPECT_FALSE(client.connect());
  19583. EXPECT_FALSE(client.is_open());
  19584. svr.stop();
  19585. t.join();
  19586. }
  19587. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19588. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19589. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19590. // (RFC 6761) is only a map key and the Host header value.
  19591. auto host = "target.invalid";
  19592. Server svr;
  19593. std::string received_host;
  19594. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19595. received_host = req.get_header_value("Host");
  19596. std::string msg;
  19597. while (ws.read(msg)) {}
  19598. });
  19599. auto port = svr.bind_to_any_port(HOST);
  19600. std::thread t([&]() { svr.listen_after_bind(); });
  19601. // ASSERT_* below returns from the test body, which would leave t joinable
  19602. // and make ~thread call std::terminate.
  19603. auto se = detail::scope_exit([&] {
  19604. svr.stop();
  19605. if (t.joinable()) { t.join(); }
  19606. });
  19607. svr.wait_until_ready();
  19608. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19609. std::to_string(port) + "/ws");
  19610. client.set_hostname_addr_map({{host, HOST}});
  19611. ASSERT_TRUE(client.connect());
  19612. EXPECT_TRUE(client.is_open());
  19613. client.close();
  19614. svr.stop();
  19615. t.join();
  19616. // The mapping only redirects the connection; the identity stays host_.
  19617. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19618. }
  19619. class WebSocketIntegrationTest : public ::testing::Test {
  19620. protected:
  19621. void SetUp() override {
  19622. server_ = httplib::detail::make_unique<Server>();
  19623. setup_server();
  19624. start_server();
  19625. }
  19626. void TearDown() override {
  19627. server_->stop();
  19628. if (server_thread_.joinable()) { server_thread_.join(); }
  19629. }
  19630. void setup_server() {
  19631. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19632. std::string msg;
  19633. ws::ReadResult ret;
  19634. while ((ret = ws.read(msg))) {
  19635. if (ret == ws::Binary) {
  19636. ws.send(msg.data(), msg.size());
  19637. } else {
  19638. ws.send(msg);
  19639. }
  19640. }
  19641. });
  19642. server_->WebSocket("/ws-echo-string",
  19643. [](const Request &, ws::WebSocket &ws) {
  19644. std::string msg;
  19645. while (ws.read(msg)) {
  19646. ws.send("echo: " + msg);
  19647. }
  19648. });
  19649. server_->WebSocket(
  19650. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19651. // Echo back request metadata
  19652. ws.send("path:" + req.path);
  19653. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19654. std::string msg;
  19655. while (ws.read(msg)) {}
  19656. });
  19657. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19658. std::string msg;
  19659. ws.read(msg); // wait for a message
  19660. ws.close();
  19661. });
  19662. server_->WebSocket("/ws-close-status",
  19663. [](const Request &, ws::WebSocket &ws) {
  19664. std::string msg;
  19665. ws.read(msg); // wait for a message
  19666. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19667. });
  19668. server_->WebSocket(
  19669. "/ws-subprotocol",
  19670. [](const Request &, ws::WebSocket &ws) {
  19671. std::string msg;
  19672. while (ws.read(msg)) {
  19673. ws.send(msg);
  19674. }
  19675. },
  19676. [](const std::vector<std::string> &protocols) -> std::string {
  19677. for (const auto &p : protocols) {
  19678. if (p == "graphql-ws") { return p; }
  19679. }
  19680. return "";
  19681. });
  19682. }
  19683. void start_server() {
  19684. port_ = server_->bind_to_any_port(HOST);
  19685. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19686. server_->wait_until_ready();
  19687. }
  19688. std::unique_ptr<Server> server_;
  19689. std::thread server_thread_;
  19690. int port_ = 0;
  19691. };
  19692. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19694. "/ws-echo");
  19695. ASSERT_TRUE(client.connect());
  19696. ASSERT_TRUE(client.is_open());
  19697. ASSERT_TRUE(client.send("Hello WebSocket"));
  19698. std::string msg;
  19699. EXPECT_EQ(ws::Text, client.read(msg));
  19700. EXPECT_EQ("Hello WebSocket", msg);
  19701. client.close();
  19702. }
  19703. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19704. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19705. "/ws-echo");
  19706. ASSERT_TRUE(client.connect());
  19707. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19708. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19709. std::string msg;
  19710. EXPECT_EQ(ws::Binary, client.read(msg));
  19711. EXPECT_EQ(binary_data, msg);
  19712. client.close();
  19713. }
  19714. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19716. "/ws-echo");
  19717. ASSERT_TRUE(client.connect());
  19718. for (int i = 0; i < 10; i++) {
  19719. auto text = "message " + std::to_string(i);
  19720. ASSERT_TRUE(client.send(text));
  19721. std::string msg;
  19722. ASSERT_TRUE(client.read(msg));
  19723. EXPECT_EQ(text, msg);
  19724. }
  19725. client.close();
  19726. }
  19727. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19729. "/ws-close");
  19730. ASSERT_TRUE(client.connect());
  19731. // Send a message to trigger the server to close
  19732. ASSERT_TRUE(client.send("trigger close"));
  19733. // The server will close, so read should return false
  19734. std::string msg;
  19735. EXPECT_FALSE(client.read(msg));
  19736. EXPECT_FALSE(client.is_open());
  19737. }
  19738. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19740. "/ws-echo");
  19741. ASSERT_TRUE(client.connect());
  19742. // 128KB message
  19743. std::string large_data(128 * 1024, 'X');
  19744. ASSERT_TRUE(client.send(large_data));
  19745. std::string msg;
  19746. ASSERT_TRUE(client.read(msg));
  19747. EXPECT_EQ(large_data, msg);
  19748. client.close();
  19749. }
  19750. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19752. "/ws-echo");
  19753. ASSERT_TRUE(client.connect());
  19754. const int num_threads = 4;
  19755. std::vector<std::thread> threads;
  19756. std::atomic<int> send_count{0};
  19757. for (int t = 0; t < num_threads; t++) {
  19758. threads.emplace_back([&client, &send_count, t]() {
  19759. for (int i = 0; i < 5; i++) {
  19760. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19761. if (client.send(text)) { send_count++; }
  19762. }
  19763. });
  19764. }
  19765. for (auto &th : threads) {
  19766. th.join();
  19767. }
  19768. int received = 0;
  19769. std::string msg;
  19770. while (received < send_count.load()) {
  19771. if (!client.read(msg)) { break; }
  19772. received++;
  19773. }
  19774. EXPECT_EQ(send_count.load(), received);
  19775. client.close();
  19776. }
  19777. TEST_F(WebSocketIntegrationTest, ReadString) {
  19778. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19779. "/ws-echo-string");
  19780. ASSERT_TRUE(client.connect());
  19781. ASSERT_TRUE(client.send("hello"));
  19782. std::string msg;
  19783. ASSERT_TRUE(client.read(msg));
  19784. EXPECT_EQ("echo: hello", msg);
  19785. ASSERT_TRUE(client.send("world"));
  19786. ASSERT_TRUE(client.read(msg));
  19787. EXPECT_EQ("echo: world", msg);
  19788. client.close();
  19789. }
  19790. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19791. Headers headers = {{"X-Test-Header", "test-value"}};
  19792. ws::WebSocketClient client(
  19793. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19794. ASSERT_TRUE(client.connect());
  19795. std::string msg;
  19796. ASSERT_TRUE(client.read(msg));
  19797. EXPECT_EQ("path:/ws-request-info", msg);
  19798. ASSERT_TRUE(client.read(msg));
  19799. EXPECT_EQ("header:test-value", msg);
  19800. client.close();
  19801. }
  19802. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19804. "/ws-echo");
  19805. client.set_read_timeout(1, 0); // 1 second
  19806. ASSERT_TRUE(client.connect());
  19807. // Don't send anything — server echo handler waits for a message, so read()
  19808. // should time out. The connection survives it: nothing was consumed.
  19809. std::string msg;
  19810. EXPECT_EQ(client.read(msg), ws::Timeout);
  19811. EXPECT_TRUE(client.is_open());
  19812. // And it is still usable afterwards.
  19813. EXPECT_TRUE(client.send("after timeout"));
  19814. EXPECT_EQ(client.read(msg), ws::Text);
  19815. EXPECT_EQ(msg, "after timeout");
  19816. }
  19817. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19818. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19819. "/ws-echo");
  19820. client.set_read_timeout(1, 0);
  19821. ASSERT_TRUE(client.connect());
  19822. ASSERT_TRUE(client.send("first"));
  19823. std::string msg;
  19824. ASSERT_EQ(client.read(msg), ws::Text);
  19825. ASSERT_EQ(msg, "first");
  19826. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19827. // not be used with a read timeout: it would reprocess the previous message.
  19828. EXPECT_EQ(client.read(msg), ws::Timeout);
  19829. EXPECT_EQ(msg, "first");
  19830. }
  19831. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19833. "/ws-echo");
  19834. ASSERT_TRUE(client.connect());
  19835. // Setting it once the connection is open reaches the live stream, not just
  19836. // the seed for the next connect().
  19837. client.set_read_timeout(1, 0);
  19838. std::string msg;
  19839. EXPECT_EQ(client.read(msg), ws::Timeout);
  19840. EXPECT_TRUE(client.is_open());
  19841. }
  19842. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19844. "/ws-echo");
  19845. client.set_read_timeout(5, 0);
  19846. ASSERT_TRUE(client.connect());
  19847. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19848. // The server should reject it and close the connection.
  19849. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19850. client.send(oversized);
  19851. // The server's read() should have failed due to payload limit,
  19852. // so our read() should return false (connection closed).
  19853. std::string msg;
  19854. EXPECT_FALSE(client.read(msg));
  19855. }
  19856. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19858. "/ws-echo");
  19859. client.set_read_timeout(10, 0);
  19860. ASSERT_TRUE(client.connect());
  19861. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19862. // This should succeed.
  19863. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19864. ASSERT_TRUE(client.send(at_limit));
  19865. std::string msg;
  19866. ASSERT_TRUE(client.read(msg));
  19867. EXPECT_EQ(at_limit.size(), msg.size());
  19868. client.close();
  19869. }
  19870. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19872. "/nonexistent");
  19873. auto res = client.connect();
  19874. EXPECT_FALSE(res);
  19875. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19876. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19877. EXPECT_FALSE(client.is_open());
  19878. }
  19879. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19880. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19881. "/ws-echo");
  19882. ASSERT_TRUE(client.connect());
  19883. ASSERT_TRUE(client.send(""));
  19884. std::string msg;
  19885. EXPECT_EQ(ws::Text, client.read(msg));
  19886. EXPECT_EQ("", msg);
  19887. client.close();
  19888. }
  19889. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19891. "/ws-echo");
  19892. // First connection
  19893. ASSERT_TRUE(client.connect());
  19894. ASSERT_TRUE(client.send("first"));
  19895. std::string msg;
  19896. ASSERT_TRUE(client.read(msg));
  19897. EXPECT_EQ("first", msg);
  19898. client.close();
  19899. EXPECT_FALSE(client.is_open());
  19900. // Reconnect using the same client object
  19901. ASSERT_TRUE(client.connect());
  19902. ASSERT_TRUE(client.is_open());
  19903. ASSERT_TRUE(client.send("second"));
  19904. ASSERT_TRUE(client.read(msg));
  19905. EXPECT_EQ("second", msg);
  19906. client.close();
  19907. }
  19908. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19909. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19910. "/ws-close-status");
  19911. ASSERT_TRUE(client.connect());
  19912. // Trigger the server to close with GoingAway status
  19913. ASSERT_TRUE(client.send("trigger"));
  19914. // read() should return false after receiving the close frame
  19915. std::string msg;
  19916. EXPECT_FALSE(client.read(msg));
  19917. EXPECT_FALSE(client.is_open());
  19918. }
  19919. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19921. "/ws-echo");
  19922. ASSERT_TRUE(client.connect());
  19923. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19924. EXPECT_FALSE(client.is_open());
  19925. }
  19926. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19927. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19928. ws::WebSocketClient client(
  19929. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19930. ASSERT_TRUE(client.connect());
  19931. // Server should have selected graphql-ws
  19932. EXPECT_EQ("graphql-ws", client.subprotocol());
  19933. client.close();
  19934. }
  19935. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19936. Headers headers;
  19937. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19938. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19939. ws::WebSocketClient client(
  19940. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19941. ASSERT_TRUE(client.connect());
  19942. // The offer on the second field line counts too, so graphql-ws is selected
  19943. EXPECT_EQ("graphql-ws", client.subprotocol());
  19944. client.close();
  19945. }
  19946. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19947. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19948. ws::WebSocketClient client(
  19949. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19950. ASSERT_TRUE(client.connect());
  19951. // Server should not have selected any subprotocol
  19952. EXPECT_TRUE(client.subprotocol().empty());
  19953. client.close();
  19954. }
  19955. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19956. // Connect without requesting any subprotocol
  19957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19958. "/ws-subprotocol");
  19959. ASSERT_TRUE(client.connect());
  19960. EXPECT_TRUE(client.subprotocol().empty());
  19961. client.close();
  19962. }
  19963. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19965. "/ws-echo");
  19966. client.set_tcp_nodelay(true);
  19967. client.set_connection_timeout(3, 0);
  19968. bool socket_options_called = false;
  19969. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19970. ASSERT_TRUE(client.connect());
  19971. ASSERT_TRUE(client.is_open());
  19972. EXPECT_TRUE(socket_options_called);
  19973. ASSERT_TRUE(client.send("hello"));
  19974. std::string msg;
  19975. auto result = client.read(msg);
  19976. EXPECT_EQ(result, ws::ReadResult::Text);
  19977. EXPECT_EQ(msg, "hello");
  19978. client.close();
  19979. }
  19980. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19982. "/ws-echo");
  19983. client.set_connection_timeout(std::chrono::seconds(3));
  19984. client.set_write_timeout(std::chrono::seconds(3));
  19985. // A sub-second remainder exercises the seconds/microseconds split.
  19986. client.set_read_timeout(std::chrono::milliseconds(1500));
  19987. ASSERT_TRUE(client.connect());
  19988. auto start = std::chrono::steady_clock::now();
  19989. std::string msg;
  19990. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  19991. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19992. std::chrono::steady_clock::now() - start)
  19993. .count();
  19994. // Above 1s so that dropping the microseconds half of the split fails here.
  19995. // Ignoring the setter altogether would not reach this line at all: a client
  19996. // waits forever by default.
  19997. EXPECT_GE(elapsed, 1400);
  19998. EXPECT_LT(elapsed, 30000);
  19999. }
  20000. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20001. Server svr;
  20002. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20003. if (!req.has_header("Authorization")) {
  20004. res.status = StatusCode::Unauthorized_401;
  20005. res.set_content("Unauthorized", "text/plain");
  20006. return Server::HandlerResponse::Handled;
  20007. }
  20008. return Server::HandlerResponse::Unhandled;
  20009. });
  20010. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20011. std::string msg;
  20012. while (ws.read(msg)) {
  20013. ws.send(msg);
  20014. }
  20015. });
  20016. auto port = svr.bind_to_any_port("localhost");
  20017. std::thread t([&]() { svr.listen_after_bind(); });
  20018. svr.wait_until_ready();
  20019. // Without Authorization header - should be rejected before upgrade
  20020. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20021. EXPECT_FALSE(client1.connect());
  20022. // The rejection is framed like any other HTTP response
  20023. {
  20024. Client cli("localhost", port);
  20025. Headers headers = {{"Upgrade", "websocket"},
  20026. {"Connection", "Upgrade"},
  20027. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20028. {"Sec-WebSocket-Version", "13"}};
  20029. auto res = cli.Get("/ws", headers);
  20030. ASSERT_TRUE(res);
  20031. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20032. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20033. EXPECT_EQ("Unauthorized", res->body);
  20034. }
  20035. // With Authorization header - should succeed
  20036. Headers headers = {{"Authorization", "Bearer token123"}};
  20037. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20038. headers);
  20039. ASSERT_TRUE(client2.connect());
  20040. ASSERT_TRUE(client2.send("hello"));
  20041. std::string msg;
  20042. ASSERT_TRUE(client2.read(msg));
  20043. EXPECT_EQ("hello", msg);
  20044. client2.close();
  20045. svr.stop();
  20046. t.join();
  20047. }
  20048. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20049. Server svr;
  20050. std::atomic<int> pre_request_calls{0};
  20051. std::atomic<bool> route_matched{false};
  20052. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20053. pre_request_calls++;
  20054. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20055. if (req.get_header_value("Authorization") != "Bearer token123") {
  20056. res.status = StatusCode::Unauthorized_401;
  20057. res.set_content("Unauthorized", "text/plain");
  20058. return Server::HandlerResponse::Handled;
  20059. }
  20060. return Server::HandlerResponse::Unhandled;
  20061. });
  20062. std::atomic<bool> handler_called{false};
  20063. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20064. handler_called = true;
  20065. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20066. });
  20067. auto port = svr.bind_to_any_port("localhost");
  20068. std::thread t([&]() { svr.listen_after_bind(); });
  20069. svr.wait_until_ready();
  20070. // Without Authorization header - should be rejected before upgrade
  20071. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20072. "/ws/1");
  20073. EXPECT_FALSE(client1.connect());
  20074. EXPECT_FALSE(handler_called);
  20075. EXPECT_EQ(1, pre_request_calls);
  20076. EXPECT_TRUE(route_matched);
  20077. // The rejection is an ordinary HTTP response, not a protocol switch
  20078. {
  20079. Client cli("localhost", port);
  20080. Headers headers = {{"Upgrade", "websocket"},
  20081. {"Connection", "Upgrade"},
  20082. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20083. {"Sec-WebSocket-Version", "13"}};
  20084. auto res = cli.Get("/ws/1", headers);
  20085. ASSERT_TRUE(res);
  20086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20087. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20088. EXPECT_EQ("Unauthorized", res->body);
  20089. }
  20090. EXPECT_FALSE(handler_called);
  20091. // With Authorization header - should succeed
  20092. Headers headers = {{"Authorization", "Bearer token123"}};
  20093. ws::WebSocketClient client2(
  20094. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20095. ASSERT_TRUE(client2.connect());
  20096. std::string msg;
  20097. ASSERT_TRUE(client2.read(msg));
  20098. EXPECT_EQ("/ws/:id 2", msg);
  20099. EXPECT_TRUE(handler_called);
  20100. client2.close();
  20101. svr.stop();
  20102. t.join();
  20103. }
  20104. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20105. Server svr;
  20106. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20107. // A read timeout is how a handler gets control back. Without it, a handler
  20108. // parked in read() can never write on the connection it is reading.
  20109. ws.set_read_timeout(std::chrono::milliseconds(100));
  20110. std::string msg;
  20111. while (ws.is_open()) {
  20112. auto r = ws.read(msg);
  20113. if (r == httplib::ws::Timeout) {
  20114. ws.send("tick");
  20115. continue;
  20116. }
  20117. if (r == httplib::ws::Fail) { break; }
  20118. ws.send(msg);
  20119. }
  20120. });
  20121. auto port = svr.bind_to_any_port("localhost");
  20122. std::thread t([&]() { svr.listen_after_bind(); });
  20123. svr.wait_until_ready();
  20124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20125. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20126. ASSERT_TRUE(client.connect());
  20127. // The client sends nothing, so anything it receives came out of the
  20128. // handler's timeout path.
  20129. std::string msg;
  20130. ASSERT_EQ(client.read(msg), ws::Text);
  20131. EXPECT_EQ("tick", msg);
  20132. client.close();
  20133. svr.stop();
  20134. t.join();
  20135. }
  20136. // Stream::read may return fewer bytes than asked for. This is that contract at
  20137. // its worst -- one byte per call -- which is what a frame header straddling a
  20138. // read buffer's boundary looks like to the frame parser.
  20139. class WsByteAtATimeStream : public Stream {
  20140. public:
  20141. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20142. bool is_readable() const override { return true; }
  20143. bool wait_readable() const override { return true; }
  20144. bool wait_writable() const override { return true; }
  20145. ssize_t read(char *ptr, size_t size) override {
  20146. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20147. *ptr = data_[pos_++];
  20148. return 1;
  20149. }
  20150. ssize_t write(const char *, size_t size) override {
  20151. return static_cast<ssize_t>(size);
  20152. }
  20153. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20154. ip = "127.0.0.1";
  20155. port = 0;
  20156. }
  20157. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20158. ip = "127.0.0.1";
  20159. port = 0;
  20160. }
  20161. socket_t socket() const override { return INVALID_SOCKET; }
  20162. time_t duration() const override { return 0; }
  20163. private:
  20164. std::string data_;
  20165. size_t pos_ = 0;
  20166. };
  20167. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20168. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20169. // length and the mask key are all multi-byte fields here. Each used to be
  20170. // read with a single read() call, which fails as soon as one is split.
  20171. std::string body(200, 'x');
  20172. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20173. std::string frame;
  20174. frame += static_cast<char>(0x81); // FIN + Text
  20175. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20176. frame += static_cast<char>(body.size() >> 8);
  20177. frame += static_cast<char>(body.size() & 0xff);
  20178. for (size_t i = 0; i < 4; i++) {
  20179. frame += static_cast<char>(mask[i]);
  20180. }
  20181. for (size_t i = 0; i < body.size(); i++) {
  20182. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20183. }
  20184. WsByteAtATimeStream strm(frame);
  20185. ws::Opcode opcode;
  20186. std::string payload;
  20187. bool fin = false;
  20188. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20189. /*expect_masked=*/true, 1024),
  20190. ws::impl::FrameRead::Ok);
  20191. EXPECT_TRUE(fin);
  20192. EXPECT_EQ(opcode, ws::Opcode::Text);
  20193. EXPECT_EQ(payload, body);
  20194. }
  20195. TEST(WebSocketTest, QueryStringInHandshake) {
  20196. Server svr;
  20197. std::mutex mtx;
  20198. std::string received_target;
  20199. std::string received_token;
  20200. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20201. {
  20202. std::lock_guard<std::mutex> lock(mtx);
  20203. received_target = req.target;
  20204. if (req.has_param("token")) {
  20205. received_token = req.get_param_value("token");
  20206. }
  20207. }
  20208. std::string msg;
  20209. while (ws.read(msg)) {
  20210. ws.send(msg);
  20211. }
  20212. });
  20213. auto port = svr.bind_to_any_port("localhost");
  20214. std::thread t([&]() { svr.listen_after_bind(); });
  20215. svr.wait_until_ready();
  20216. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20217. "/ws?token=ABC&session=123");
  20218. ASSERT_TRUE(client.connect());
  20219. // Round-trip ensures the handler has run and captured the request.
  20220. ASSERT_TRUE(client.send("hello"));
  20221. std::string msg;
  20222. ASSERT_TRUE(client.read(msg));
  20223. EXPECT_EQ("hello", msg);
  20224. client.close();
  20225. {
  20226. std::lock_guard<std::mutex> lock(mtx);
  20227. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20228. EXPECT_EQ("ABC", received_token);
  20229. }
  20230. svr.stop();
  20231. t.join();
  20232. }
  20233. // Run a handshake against a throwaway server and hand the request the server
  20234. // received back to the caller, so tests can assert on the headers the client
  20235. // actually put on the wire.
  20236. static void capture_websocket_handshake_request(
  20237. const Headers &client_headers,
  20238. std::function<void(const Request &, int port)> verify) {
  20239. Server svr;
  20240. std::mutex mtx;
  20241. Request received;
  20242. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20243. {
  20244. std::lock_guard<std::mutex> lock(mtx);
  20245. received = req;
  20246. }
  20247. std::string msg;
  20248. while (ws.read(msg)) {
  20249. ws.send(msg);
  20250. }
  20251. });
  20252. auto port = svr.bind_to_any_port("localhost");
  20253. std::thread t([&]() { svr.listen_after_bind(); });
  20254. auto se = detail::scope_exit([&] {
  20255. svr.stop();
  20256. t.join();
  20257. });
  20258. svr.wait_until_ready();
  20259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20260. client_headers);
  20261. ASSERT_TRUE(client.connect());
  20262. ASSERT_TRUE(client.send("hello"));
  20263. std::string msg;
  20264. ASSERT_TRUE(client.read(msg));
  20265. client.close();
  20266. {
  20267. std::lock_guard<std::mutex> lock(mtx);
  20268. verify(received, port);
  20269. }
  20270. }
  20271. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20272. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20273. // Non-default port must be present in the Host header. Default ports
  20274. // (80/443) are omitted; that logic is covered by
  20275. // MakeHostAndPortStringTest.
  20276. EXPECT_EQ("localhost:" + std::to_string(port),
  20277. req.get_header_value("Host"));
  20278. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20279. req.get_header_value("User-Agent"));
  20280. EXPECT_FALSE(req.has_header("Accept"));
  20281. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20282. EXPECT_FALSE(req.has_header("Content-Length"));
  20283. });
  20284. }
  20285. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20286. capture_websocket_handshake_request(
  20287. {{"Host", "example.com"},
  20288. {"User-Agent", "custom-agent"},
  20289. {"X-Custom", "value"}},
  20290. [](const Request &req, int) {
  20291. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20292. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20293. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20294. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20295. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20296. });
  20297. }
  20298. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20299. capture_websocket_handshake_request(
  20300. {{"Upgrade", "bogus"},
  20301. {"Connection", "close"},
  20302. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20303. {"Sec-WebSocket-Version", "8"}},
  20304. [](const Request &req, int) {
  20305. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20306. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20307. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20308. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20309. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20310. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20311. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20312. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20313. req.get_header_value("Sec-WebSocket-Key"));
  20314. });
  20315. }
  20316. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20317. // A header the client refuses to send must abort the handshake before any
  20318. // part of it reaches the wire; a lone request line would otherwise sit in
  20319. // the peer's buffer as a truncated request.
  20320. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20321. ASSERT_NE(INVALID_SOCKET, srv);
  20322. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20323. sockaddr_in addr{};
  20324. addr.sin_family = AF_INET;
  20325. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20326. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20327. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20328. ASSERT_EQ(0, ::listen(srv, 1));
  20329. sockaddr_in bound{};
  20330. socklen_t bound_len = sizeof(bound);
  20331. ASSERT_EQ(
  20332. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20333. auto port = ntohs(bound.sin_port);
  20334. ssize_t received = -1;
  20335. std::thread t([&] {
  20336. // Bound every blocking call so a regression fails the test with a bad
  20337. // value instead of hanging the suite.
  20338. fd_set rfds;
  20339. FD_ZERO(&rfds);
  20340. FD_SET(srv, &rfds);
  20341. timeval tv{5, 0};
  20342. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20343. 0) {
  20344. return;
  20345. }
  20346. sockaddr_in cli_addr{};
  20347. socklen_t cli_len = sizeof(cli_addr);
  20348. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20349. if (cli == INVALID_SOCKET) { return; }
  20350. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20351. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20352. char buf[4096];
  20353. received = ::recv(cli, buf, sizeof(buf), 0);
  20354. });
  20355. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20356. // connect() has already shut the socket down by the time it returns false,
  20357. // so the peer sees EOF without waiting for the client to be destroyed.
  20358. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20359. {{"X-Bad", "a\r\nInjected: 1"}});
  20360. EXPECT_FALSE(client.connect());
  20361. t.join();
  20362. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20363. EXPECT_EQ(0, received);
  20364. }
  20365. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20366. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20367. // contains "upgrade" as a substring is a different token and must not
  20368. // start a WebSocket handshake.
  20369. auto make_request = [](const std::vector<std::string> &connection_values) {
  20370. Request req;
  20371. req.method = "GET";
  20372. req.headers.emplace("Upgrade", "websocket");
  20373. for (const auto &value : connection_values) {
  20374. req.headers.emplace("Connection", value);
  20375. }
  20376. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20377. req.headers.emplace("Sec-WebSocket-Version", "13");
  20378. return req;
  20379. };
  20380. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20381. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20382. EXPECT_TRUE(
  20383. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20384. EXPECT_TRUE(
  20385. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20386. EXPECT_TRUE(
  20387. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20388. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20389. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20390. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20391. EXPECT_FALSE(
  20392. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20393. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20394. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20395. }
  20396. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20397. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20398. // asks recipients to match each protocol-name case-insensitively, and RFC
  20399. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20400. // client naming websocket alongside another protocol, or on a second field
  20401. // line, is offering websocket; a value that merely contains "websocket" as a
  20402. // substring is a different protocol name and is not.
  20403. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20404. Request req;
  20405. req.method = "GET";
  20406. for (const auto &value : upgrade_values) {
  20407. req.headers.emplace("Upgrade", value);
  20408. }
  20409. req.headers.emplace("Connection", "Upgrade");
  20410. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20411. req.headers.emplace("Sec-WebSocket-Version", "13");
  20412. return req;
  20413. };
  20414. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20415. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20416. EXPECT_TRUE(
  20417. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20418. EXPECT_TRUE(
  20419. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20420. EXPECT_TRUE(
  20421. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20422. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20423. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20424. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20425. EXPECT_FALSE(
  20426. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20427. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20428. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20429. }
  20430. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20431. Server svr;
  20432. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20433. auto port = svr.bind_to_any_port("localhost");
  20434. std::thread t([&]() { svr.listen_after_bind(); });
  20435. auto se = detail::scope_exit([&] {
  20436. svr.stop();
  20437. t.join();
  20438. });
  20439. svr.wait_until_ready();
  20440. Headers headers = {{"Upgrade", "websocket"},
  20441. {"Connection", "notupgrade"},
  20442. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20443. {"Sec-WebSocket-Version", "13"}};
  20444. Client cli("localhost", port);
  20445. auto res = cli.Get("/ws", headers);
  20446. // The route exists only as a WebSocket route, so a request that fails the
  20447. // handshake check falls through to ordinary routing.
  20448. ASSERT_TRUE(res);
  20449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20450. }
  20451. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20452. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20453. // Connection value is the only thing left for the client to reject.
  20454. Server svr;
  20455. svr.Get("/ws", [](const Request &req, Response &res) {
  20456. res.status = StatusCode::SwitchingProtocol_101;
  20457. res.set_header("Upgrade", "websocket");
  20458. res.set_header("Connection", "notupgrade");
  20459. res.set_header("Sec-WebSocket-Accept",
  20460. detail::websocket_accept_key(
  20461. req.get_header_value("Sec-WebSocket-Key")));
  20462. });
  20463. auto port = svr.bind_to_any_port("localhost");
  20464. std::thread t([&]() { svr.listen_after_bind(); });
  20465. auto se = detail::scope_exit([&] {
  20466. svr.stop();
  20467. t.join();
  20468. });
  20469. svr.wait_until_ready();
  20470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20471. auto res = client.connect();
  20472. EXPECT_FALSE(res);
  20473. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20474. EXPECT_FALSE(client.is_open());
  20475. }
  20476. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20477. // The socket path doubles as the URL host, so it must not contain '/'.
  20478. const char *shard = getenv("GTEST_SHARD_INDEX");
  20479. const std::string sock_path =
  20480. shard ? std::string("httplib-ws-") + shard + ".sock"
  20481. : std::string("httplib-ws.sock");
  20482. std::remove(sock_path.c_str());
  20483. Server svr;
  20484. std::mutex mtx;
  20485. std::string received_host;
  20486. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20487. {
  20488. std::lock_guard<std::mutex> lock(mtx);
  20489. received_host = req.get_header_value("Host");
  20490. }
  20491. std::string msg;
  20492. while (ws.read(msg)) {
  20493. ws.send(msg);
  20494. }
  20495. });
  20496. svr.set_address_family(AF_UNIX);
  20497. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20498. auto se = detail::scope_exit([&] {
  20499. svr.stop();
  20500. t.join();
  20501. std::remove(sock_path.c_str());
  20502. });
  20503. svr.wait_until_ready();
  20504. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20505. client.set_address_family(AF_UNIX);
  20506. ASSERT_TRUE(client.connect());
  20507. ASSERT_TRUE(client.send("hello"));
  20508. std::string msg;
  20509. ASSERT_TRUE(client.read(msg));
  20510. client.close();
  20511. {
  20512. std::lock_guard<std::mutex> lock(mtx);
  20513. // There is no host:port for a Unix socket, so the same "localhost"
  20514. // placeholder the HTTP client uses is expected.
  20515. EXPECT_EQ("localhost", received_host);
  20516. }
  20517. }
  20518. // Two threads must never parse WebSocket frames from the same stream.
  20519. // close() used to read the peer's Close reply with its own frame read, so it
  20520. // raced a reader thread that was in the middle of a payload: the payload loop
  20521. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20522. // so bytes taken by close() were replaced with bytes from further along the
  20523. // stream. The message kept its length and silently changed content.
  20524. //
  20525. // The raw peer below sends a frame header plus part of the payload, waits for
  20526. // the handler to call close(), and only then sends the rest. Whichever thread
  20527. // would win the race for those bytes, the message must arrive intact, because
  20528. // close() must not touch the stream while read() owns it.
  20529. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20530. #ifndef _WIN32
  20531. signal(SIGPIPE, SIG_IGN);
  20532. #endif
  20533. const size_t payload_len = 120; // fits the 7-bit length field
  20534. const size_t prefix_len = 8;
  20535. const int attempts = 8;
  20536. std::string expected(payload_len, '\0');
  20537. for (size_t i = 0; i < payload_len; i++) {
  20538. expected[i] = static_cast<char>('a' + i % 26);
  20539. }
  20540. std::atomic<bool> peer_stalled{false};
  20541. std::atomic<bool> handler_done{false};
  20542. std::mutex received_mutex;
  20543. std::vector<std::string> received;
  20544. // Bound every wait, so a regression fails the test instead of hanging the
  20545. // suite.
  20546. auto wait_for = [](const std::atomic<bool> &flag) {
  20547. for (int i = 0; i < 500 && !flag; i++) {
  20548. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20549. }
  20550. };
  20551. Server svr;
  20552. svr.set_websocket_ping_interval(0);
  20553. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20554. std::thread reader([&]() {
  20555. std::string msg;
  20556. while (ws.read(msg)) {
  20557. std::lock_guard<std::mutex> guard(received_mutex);
  20558. received.push_back(msg);
  20559. }
  20560. });
  20561. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20562. // inside read_websocket_frame() when close() runs.
  20563. wait_for(peer_stalled);
  20564. ws.close();
  20565. reader.join();
  20566. handler_done = true;
  20567. });
  20568. auto port = svr.bind_to_any_port("127.0.0.1");
  20569. std::thread t([&]() { svr.listen_after_bind(); });
  20570. auto se = detail::scope_exit([&] {
  20571. svr.stop();
  20572. t.join();
  20573. });
  20574. svr.wait_until_ready();
  20575. auto send_bytes = [](socket_t s, const std::string &data) {
  20576. #ifdef _WIN32
  20577. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20578. #else
  20579. auto n = ::send(s, data.data(), data.size(), 0);
  20580. #endif
  20581. return n == static_cast<decltype(n)>(data.size());
  20582. };
  20583. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20584. // Every length used here fits the 7-bit length field.
  20585. auto masked_header = [](uint8_t first_byte, size_t len) {
  20586. std::string h;
  20587. h += static_cast<char>(first_byte);
  20588. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20589. h.append(4, '\0'); // mask key
  20590. return h;
  20591. };
  20592. for (int attempt = 0; attempt < attempts; attempt++) {
  20593. peer_stalled = false;
  20594. handler_done = false;
  20595. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20596. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20597. auto se_sock = detail::scope_exit([&] {
  20598. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20599. });
  20600. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20601. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20602. sockaddr_in addr{};
  20603. addr.sin_family = AF_INET;
  20604. addr.sin_port = htons(static_cast<uint16_t>(port));
  20605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20606. ASSERT_EQ(
  20607. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20608. << "attempt " << attempt;
  20609. ASSERT_TRUE(send_bytes(sock,
  20610. "GET /ws HTTP/1.1\r\n"
  20611. "Host: 127.0.0.1\r\n"
  20612. "Upgrade: websocket\r\n"
  20613. "Connection: Upgrade\r\n"
  20614. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20615. "Sec-WebSocket-Version: 13\r\n"
  20616. "\r\n"))
  20617. << "attempt " << attempt;
  20618. std::string response;
  20619. while (response.find("\r\n\r\n") == std::string::npos) {
  20620. char buf[512];
  20621. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20622. if (n <= 0) { break; }
  20623. response.append(buf, static_cast<size_t>(n));
  20624. }
  20625. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20626. << "attempt " << attempt;
  20627. // Send the header of a Binary message but only the first prefix_len bytes
  20628. // of its payload, leaving the reader thread stalled inside the payload.
  20629. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20630. expected.substr(0, prefix_len)))
  20631. << "attempt " << attempt;
  20632. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20633. peer_stalled = true;
  20634. // Let close() send its Close frame and park in its own read before the
  20635. // rest of the payload arrives, so both threads are waiting for it.
  20636. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20637. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20638. close_frame += static_cast<char>(0x03); // status 1000
  20639. close_frame += static_cast<char>(0xE8);
  20640. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20641. << "attempt " << attempt;
  20642. // Closing the peer releases the reader thread even on the buggy path,
  20643. // where it waits for bytes another thread already consumed.
  20644. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20645. detail::close_socket(sock);
  20646. sock = INVALID_SOCKET;
  20647. wait_for(handler_done);
  20648. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20649. }
  20650. std::lock_guard<std::mutex> guard(received_mutex);
  20651. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20652. << "a message in flight when close() ran was dropped";
  20653. for (size_t i = 0; i < received.size(); i++) {
  20654. EXPECT_EQ(expected, received[i]) << "message " << i;
  20655. }
  20656. }
  20657. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20658. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20659. protected:
  20660. void SetUp() override {
  20661. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20662. SERVER_PRIVATE_KEY_FILE);
  20663. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20664. std::string msg;
  20665. ws::ReadResult ret;
  20666. while ((ret = ws.read(msg))) {
  20667. if (ret == ws::Binary) {
  20668. ws.send(msg.data(), msg.size());
  20669. } else {
  20670. ws.send(msg);
  20671. }
  20672. }
  20673. });
  20674. port_ = server_->bind_to_any_port(HOST);
  20675. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20676. server_->wait_until_ready();
  20677. }
  20678. void TearDown() override {
  20679. server_->stop();
  20680. if (server_thread_.joinable()) { server_thread_.join(); }
  20681. }
  20682. std::unique_ptr<SSLServer> server_;
  20683. std::thread server_thread_;
  20684. int port_ = 0;
  20685. };
  20686. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20687. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20688. "/ws-echo");
  20689. client.enable_server_certificate_verification(false);
  20690. ASSERT_TRUE(client.connect());
  20691. ASSERT_TRUE(client.is_open());
  20692. ASSERT_TRUE(client.send("Hello WSS"));
  20693. std::string msg;
  20694. EXPECT_EQ(ws::Text, client.read(msg));
  20695. EXPECT_EQ("Hello WSS", msg);
  20696. client.close();
  20697. }
  20698. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20699. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20700. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20701. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20702. // client (without calling close() first) is the only path that runs
  20703. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20704. // bug exactly.
  20705. //
  20706. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20707. // when linked against an instrumented libssl; run under Valgrind to catch it
  20708. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20709. // suite (the freed session otherwise stalls on the close handshake) — this test
  20710. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20711. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20712. {
  20713. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20714. "/ws-echo");
  20715. client.enable_server_certificate_verification(false);
  20716. client.set_read_timeout(2, 0);
  20717. client.set_write_timeout(2, 0);
  20718. ASSERT_TRUE(client.connect());
  20719. ASSERT_TRUE(client.is_open());
  20720. ASSERT_TRUE(client.send("still open"));
  20721. // Intentionally do NOT call client.close(): leaving scope runs
  20722. // shutdown_and_close() with the WebSocket still open, which must send the
  20723. // close frame while the TLS session is still alive.
  20724. }
  20725. }
  20726. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20727. // shutdown_and_close() at the start of connect(), reproducing the same
  20728. // use-after-free within the test body rather than at scope exit. The second
  20729. // connect must succeed and echo, proving the close handshake ran over a live
  20730. // session. See the note above about memory-tool requirements.
  20731. TEST_F(WebSocketSSLIntegrationTest,
  20732. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20733. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20734. "/ws-echo");
  20735. client.enable_server_certificate_verification(false);
  20736. client.set_read_timeout(2, 0);
  20737. client.set_write_timeout(2, 0);
  20738. ASSERT_TRUE(client.connect());
  20739. ASSERT_TRUE(client.is_open());
  20740. ASSERT_TRUE(client.send("still open"));
  20741. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20742. // the still-open connection, which must not touch a freed TLS session.
  20743. ASSERT_TRUE(client.connect());
  20744. ASSERT_TRUE(client.is_open());
  20745. ASSERT_TRUE(client.send("after reconnect"));
  20746. std::string msg;
  20747. EXPECT_EQ(ws::Text, client.read(msg));
  20748. EXPECT_EQ("after reconnect", msg);
  20749. client.close();
  20750. }
  20751. #endif
  20752. #ifdef CPPHTTPLIB_SSL_ENABLED
  20753. class WebSocketSSLCATest : public ::testing::Test {
  20754. protected:
  20755. void SetUp() override {
  20756. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20757. SERVER_PRIVATE_KEY_FILE);
  20758. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20759. std::string msg;
  20760. while (ws.read(msg)) {
  20761. ws.send(msg);
  20762. }
  20763. });
  20764. port_ = server_->bind_to_any_port("127.0.0.1");
  20765. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20766. server_->wait_until_ready();
  20767. }
  20768. void TearDown() override {
  20769. server_->stop();
  20770. if (server_thread_.joinable()) { server_thread_.join(); }
  20771. }
  20772. std::string url() const {
  20773. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20774. }
  20775. std::unique_ptr<SSLServer> server_;
  20776. std::thread server_thread_;
  20777. int port_ = 0;
  20778. };
  20779. // A custom CA loaded as PEM verifies the server with full certificate
  20780. // verification enabled
  20781. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20782. ws::WebSocketClient client(url());
  20783. std::string cert;
  20784. read_file(SERVER_CERT2_FILE, cert);
  20785. client.load_ca_cert_store(cert.c_str(), cert.size());
  20786. ASSERT_TRUE(client.connect());
  20787. ASSERT_TRUE(client.send("hello"));
  20788. std::string msg;
  20789. EXPECT_EQ(ws::Text, client.read(msg));
  20790. EXPECT_EQ("hello", msg);
  20791. client.close();
  20792. }
  20793. // A custom CA that does not cover the server must fail verification (the
  20794. // custom CA is exclusive; system certs are not loaded alongside it)
  20795. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20796. ws::WebSocketClient client(url());
  20797. std::string cert;
  20798. read_file(CLIENT_CA_CERT_FILE, cert);
  20799. client.load_ca_cert_store(cert.c_str(), cert.size());
  20800. auto res = client.connect();
  20801. ASSERT_FALSE(res);
  20802. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20803. EXPECT_EQ(-1, res.status());
  20804. EXPECT_NE(0u, res.ssl_backend_error());
  20805. }
  20806. // The same CA as a file path rather than PEM in memory
  20807. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20808. ws::WebSocketClient client(url());
  20809. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20810. ASSERT_TRUE(client.connect());
  20811. ASSERT_TRUE(client.send("hello"));
  20812. std::string msg;
  20813. EXPECT_EQ(ws::Text, client.read(msg));
  20814. EXPECT_EQ("hello", msg);
  20815. client.close();
  20816. }
  20817. // ...and a CA file that does not cover the server still fails, so it is the
  20818. // path above that decides the outcome
  20819. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20820. ws::WebSocketClient client(url());
  20821. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20822. ASSERT_FALSE(client.connect());
  20823. }
  20824. // Regression test: reconnecting with a native custom CA store used to reuse
  20825. // a store handle the previous TLS context had already freed (use-after-free
  20826. // under the OpenSSL backend). The context now lives as long as the client.
  20827. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20828. ws::WebSocketClient client(url());
  20829. std::string cert;
  20830. read_file(SERVER_CERT2_FILE, cert);
  20831. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20832. ASSERT_TRUE(client.connect());
  20833. client.close();
  20834. ASSERT_TRUE(client.connect());
  20835. ASSERT_TRUE(client.send("again"));
  20836. std::string msg;
  20837. EXPECT_EQ(ws::Text, client.read(msg));
  20838. EXPECT_EQ("again", msg);
  20839. client.close();
  20840. }
  20841. // Regression test: a certificate with a trusted chain but no identity match
  20842. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20843. // verification entirely for IP hosts, so this connection succeeded there.
  20844. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20845. // chain verification while the identity check must still fail.
  20846. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20848. ASSERT_TRUE(svr.is_valid());
  20849. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20850. std::string msg;
  20851. while (ws.read(msg)) {
  20852. ws.send(msg);
  20853. }
  20854. });
  20855. auto port = svr.bind_to_any_port("127.0.0.1");
  20856. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20857. auto se = detail::scope_exit([&] {
  20858. svr.stop();
  20859. t.join();
  20860. });
  20861. svr.wait_until_ready();
  20862. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20863. "/echo");
  20864. std::string cert;
  20865. read_file(SERVER_CERT_FILE, cert);
  20866. client.load_ca_cert_store(cert.c_str(), cert.size());
  20867. ASSERT_FALSE(client.connect());
  20868. }
  20869. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20870. // SNI, so nothing binds the host name to the TLS session. These bind the
  20871. // server to "localhost" instead, the only shape that exercises the SNI and
  20872. // hostname-verification path with certificate verification left enabled.
  20873. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20874. protected:
  20875. void Start(const char *cert_file) {
  20876. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20877. SERVER_PRIVATE_KEY_FILE);
  20878. ASSERT_TRUE(server_->is_valid());
  20879. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20880. std::string msg;
  20881. while (ws.read(msg)) {
  20882. ws.send(msg);
  20883. }
  20884. });
  20885. port_ = server_->bind_to_any_port("localhost");
  20886. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20887. server_->wait_until_ready();
  20888. }
  20889. void TearDown() override {
  20890. if (server_) { server_->stop(); }
  20891. if (server_thread_.joinable()) { server_thread_.join(); }
  20892. }
  20893. std::string url() const {
  20894. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20895. }
  20896. std::unique_ptr<SSLServer> server_;
  20897. std::thread server_thread_;
  20898. int port_ = 0;
  20899. };
  20900. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20901. // out and the connection is usable
  20902. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20903. Start(SERVER_CERT2_FILE);
  20904. ws::WebSocketClient client(url());
  20905. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20906. ASSERT_TRUE(client.connect());
  20907. ASSERT_TRUE(client.send("hello"));
  20908. std::string msg;
  20909. EXPECT_EQ(ws::Text, client.read(msg));
  20910. EXPECT_EQ("hello", msg);
  20911. client.close();
  20912. }
  20913. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20914. // while the identity check must still reject "localhost"
  20915. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20916. Start(SERVER_CERT_FILE);
  20917. ws::WebSocketClient client(url());
  20918. client.set_ca_cert_path(SERVER_CERT_FILE);
  20919. auto res = client.connect();
  20920. ASSERT_FALSE(res);
  20921. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20922. EXPECT_EQ(-1, res.status());
  20923. }
  20924. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20925. // disabled: the chain is still checked, only the identity check is skipped
  20926. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20927. Start(SERVER_CERT_FILE);
  20928. ws::WebSocketClient client(url());
  20929. client.set_ca_cert_path(SERVER_CERT_FILE);
  20930. client.enable_server_hostname_verification(false);
  20931. ASSERT_TRUE(client.connect());
  20932. ASSERT_TRUE(client.send("hello"));
  20933. std::string msg;
  20934. EXPECT_EQ(ws::Text, client.read(msg));
  20935. EXPECT_EQ("hello", msg);
  20936. client.close();
  20937. }
  20938. // A CA that did not sign the server certificate fails the chain, even though
  20939. // the name would match
  20940. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20941. Start(SERVER_CERT2_FILE);
  20942. ws::WebSocketClient client(url());
  20943. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20944. ASSERT_FALSE(client.connect());
  20945. }
  20946. // With verification disabled, neither the chain nor the name is checked
  20947. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20948. Start(SERVER_CERT_FILE);
  20949. ws::WebSocketClient client(url());
  20950. client.enable_server_certificate_verification(false);
  20951. ASSERT_TRUE(client.connect());
  20952. ASSERT_TRUE(client.send("hello"));
  20953. std::string msg;
  20954. EXPECT_EQ(ws::Text, client.read(msg));
  20955. EXPECT_EQ("hello", msg);
  20956. client.close();
  20957. }
  20958. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20959. protected:
  20960. void SetUp() override {
  20961. server_ = httplib::detail::make_unique<SSLServer>(
  20962. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20963. ASSERT_TRUE(server_->is_valid());
  20964. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20965. std::string msg;
  20966. while (ws.read(msg)) {
  20967. ws.send(msg);
  20968. }
  20969. });
  20970. port_ = server_->bind_to_any_port("localhost");
  20971. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20972. server_->wait_until_ready();
  20973. }
  20974. void TearDown() override {
  20975. server_->stop();
  20976. if (server_thread_.joinable()) { server_thread_.join(); }
  20977. }
  20978. std::string url() const {
  20979. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20980. }
  20981. void ConnectWithClientCert(const std::string &client_cert_file,
  20982. const std::string &client_private_key_file,
  20983. const char *private_key_password) {
  20984. std::string cert_pem, key_pem;
  20985. read_file(client_cert_file, cert_pem);
  20986. read_file(client_private_key_file, key_pem);
  20987. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20988. key_pem.c_str(), key_pem.size(),
  20989. private_key_password};
  20990. ws::WebSocketClient client(url(), pem);
  20991. ASSERT_TRUE(client.is_valid());
  20992. client.enable_server_certificate_verification(false);
  20993. ASSERT_TRUE(client.connect());
  20994. ASSERT_TRUE(client.send("hello"));
  20995. std::string msg;
  20996. EXPECT_EQ(ws::Text, client.read(msg));
  20997. EXPECT_EQ("hello", msg);
  20998. client.close();
  20999. }
  21000. std::unique_ptr<SSLServer> server_;
  21001. std::thread server_thread_;
  21002. int port_ = 0;
  21003. };
  21004. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21005. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21006. }
  21007. // Control for the tests above: the fixture's server really does require a
  21008. // client certificate, so it is the PEM the constructor installed that decides
  21009. // the outcome.
  21010. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21011. ws::WebSocketClient client(url());
  21012. ASSERT_TRUE(client.is_valid());
  21013. client.enable_server_certificate_verification(false);
  21014. EXPECT_FALSE(client.connect());
  21015. }
  21016. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21017. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21018. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21019. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21020. }
  21021. #endif
  21022. #if !defined(_WIN32)
  21023. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21024. auto secret_dir = std::string("./symlink_test_secret");
  21025. auto served_dir = std::string("./symlink_test_served");
  21026. auto secret_file = secret_dir + "/secret.txt";
  21027. auto symlink_path = served_dir + "/escape";
  21028. // Setup: create directories and files
  21029. mkdir(secret_dir.c_str(), 0755);
  21030. mkdir(served_dir.c_str(), 0755);
  21031. {
  21032. std::ofstream ofs(secret_file);
  21033. ofs << "SECRET_DATA";
  21034. }
  21035. // Create symlink using absolute path so it resolves correctly
  21036. #ifdef PATH_MAX
  21037. char abs_secret[PATH_MAX];
  21038. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21039. #else
  21040. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21041. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21042. ASSERT_NE(nullptr, abs_secret);
  21043. #endif
  21044. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21045. auto se = detail::scope_exit([&] {
  21046. unlink(symlink_path.c_str());
  21047. unlink(secret_file.c_str());
  21048. rmdir(served_dir.c_str());
  21049. rmdir(secret_dir.c_str());
  21050. });
  21051. Server svr;
  21052. svr.set_mount_point("/", served_dir);
  21053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21054. auto se2 = detail::scope_exit([&] {
  21055. svr.stop();
  21056. listen_thread.join();
  21057. });
  21058. svr.wait_until_ready();
  21059. Client cli("localhost", PORT);
  21060. // Symlink pointing outside base dir should be blocked
  21061. auto res = cli.Get("/escape/secret.txt");
  21062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21063. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21064. }
  21065. #endif
  21066. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21067. // A GET request with Content-Length to a static file handler must have its
  21068. // body drained before the keep-alive connection is reused. Otherwise the
  21069. // unread body bytes are interpreted as the next HTTP request.
  21070. //
  21071. // The body is sent AFTER receiving the first response (as in the original
  21072. // PoC) so that the stream_line_reader cannot buffer it together with the
  21073. // headers of the first request.
  21074. Server svr;
  21075. svr.set_mount_point("/", "./www");
  21076. std::atomic<int> smuggled_count(0);
  21077. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21078. smuggled_count++;
  21079. res.set_content("oops", "text/plain");
  21080. });
  21081. auto port = svr.bind_to_any_port("localhost");
  21082. thread t = thread([&] { svr.listen_after_bind(); });
  21083. auto se = detail::scope_exit([&] {
  21084. svr.stop();
  21085. t.join();
  21086. });
  21087. svr.wait_until_ready();
  21088. auto error = Error::Success;
  21089. auto sock = detail::create_client_socket(
  21090. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21091. /*connection_timeout_sec=*/2, 0,
  21092. /*read_timeout_sec=*/2, 0,
  21093. /*write_timeout_sec=*/2, 0, std::string(), error);
  21094. ASSERT_NE(INVALID_SOCKET, sock);
  21095. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21096. // The "smuggled" request will be sent as the body of the outer GET
  21097. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21098. "Host: localhost\r\n"
  21099. "Connection: close\r\n"
  21100. "\r\n";
  21101. // Step 1: Send only the outer request headers (no body yet)
  21102. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  21103. "Host: localhost\r\n"
  21104. "Content-Length: " +
  21105. std::to_string(smuggled.size()) +
  21106. "\r\n"
  21107. "\r\n";
  21108. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  21109. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  21110. // Step 2: Read the first response (server serves file without reading body)
  21111. std::string first_response;
  21112. char buf[4096];
  21113. for (;;) {
  21114. auto n = recv(sock, buf, sizeof(buf), 0);
  21115. if (n <= 0) break;
  21116. first_response.append(buf, static_cast<size_t>(n));
  21117. // Stop once we have a complete response (headers + body)
  21118. auto hdr_end = first_response.find("\r\n\r\n");
  21119. if (hdr_end != std::string::npos) {
  21120. // Check for Content-Length to know when the body is complete
  21121. auto cl_pos = first_response.find("Content-Length:");
  21122. if (cl_pos != std::string::npos) {
  21123. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21124. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21125. auto cl = std::stoul(
  21126. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21127. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21128. } else {
  21129. break; // No Content-Length, assume headers-only response
  21130. }
  21131. }
  21132. }
  21133. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  21134. // Step 3: Now send the body, which looks like a new HTTP request.
  21135. // On a vulnerable server the keep-alive loop reads this as a second request.
  21136. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  21137. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  21138. // Step 4: Try to read a second response (should NOT exist after fix)
  21139. std::string second_response;
  21140. for (;;) {
  21141. auto n = recv(sock, buf, sizeof(buf), 0);
  21142. if (n <= 0) break;
  21143. second_response.append(buf, static_cast<size_t>(n));
  21144. }
  21145. // The smuggled request must NOT have been processed
  21146. EXPECT_EQ(0, smuggled_count.load());
  21147. }
  21148. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21149. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21150. // must be rejected with 400 Bad Request.
  21151. Server svr;
  21152. svr.Post("/test", [&](const Request &, Response &res) {
  21153. res.set_content("ok", "text/plain");
  21154. });
  21155. thread t = thread([&] { svr.listen(HOST, PORT); });
  21156. auto se = detail::scope_exit([&] {
  21157. svr.stop();
  21158. t.join();
  21159. ASSERT_FALSE(svr.is_running());
  21160. });
  21161. svr.wait_until_ready();
  21162. // Exact "chunked"
  21163. {
  21164. auto req = "POST /test HTTP/1.1\r\n"
  21165. "Host: localhost\r\n"
  21166. "Content-Length: 5\r\n"
  21167. "Transfer-Encoding: chunked\r\n"
  21168. "Connection: close\r\n"
  21169. "\r\n"
  21170. "hello";
  21171. std::string response;
  21172. ASSERT_TRUE(send_request(1, req, &response));
  21173. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21174. response.substr(0, response.find("\r\n")));
  21175. }
  21176. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21177. {
  21178. auto req = "POST /test HTTP/1.1\r\n"
  21179. "Host: localhost\r\n"
  21180. "Content-Length: 5\r\n"
  21181. "Transfer-Encoding: gzip, chunked\r\n"
  21182. "Connection: close\r\n"
  21183. "\r\n"
  21184. "hello";
  21185. std::string response;
  21186. ASSERT_TRUE(send_request(1, req, &response));
  21187. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21188. response.substr(0, response.find("\r\n")));
  21189. }
  21190. }
  21191. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21192. Server svr;
  21193. svr.Post("/test", [&](const Request &, Response &res) {
  21194. res.set_content("ok", "text/plain");
  21195. });
  21196. thread t = thread([&] { svr.listen(HOST, PORT); });
  21197. auto se = detail::scope_exit([&] {
  21198. svr.stop();
  21199. t.join();
  21200. ASSERT_FALSE(svr.is_running());
  21201. });
  21202. svr.wait_until_ready();
  21203. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21204. // length cannot be determined, so the server must answer 400 and close
  21205. // rather than treat the request as bodyless and leave the body in the
  21206. // socket for the next request to pick up.
  21207. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21208. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21209. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21210. std::string response;
  21211. ASSERT_TRUE(send_request(1, req, &response));
  21212. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21213. response.substr(0, response.find("\r\n")))
  21214. << transfer_encoding;
  21215. }
  21216. // RFC 9110 5.3: the codings may also be split across several
  21217. // Transfer-Encoding lines, which combine in the order they were received.
  21218. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21219. // just like the single-line "chunked, gzip" above.
  21220. {
  21221. auto req = "POST /test HTTP/1.1\r\n"
  21222. "Host: localhost\r\n"
  21223. "Transfer-Encoding: chunked\r\n"
  21224. "Transfer-Encoding: gzip\r\n"
  21225. "\r\n"
  21226. "0\r\n\r\n";
  21227. std::string response;
  21228. ASSERT_TRUE(send_request(1, req, &response));
  21229. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21230. response.substr(0, response.find("\r\n")));
  21231. }
  21232. // A sequence ending in chunked stays valid.
  21233. auto req = "POST /test HTTP/1.1\r\n"
  21234. "Host: localhost\r\n"
  21235. "Transfer-Encoding: gzip, chunked\r\n"
  21236. "Connection: close\r\n"
  21237. "\r\n"
  21238. "0\r\n\r\n";
  21239. std::string response;
  21240. ASSERT_TRUE(send_request(1, req, &response));
  21241. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21242. // ...including when it is spread over several lines.
  21243. auto split_req = "POST /test HTTP/1.1\r\n"
  21244. "Host: localhost\r\n"
  21245. "Transfer-Encoding: gzip\r\n"
  21246. "Transfer-Encoding: chunked\r\n"
  21247. "Connection: close\r\n"
  21248. "\r\n"
  21249. "0\r\n\r\n";
  21250. std::string split_response;
  21251. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21252. EXPECT_EQ("HTTP/1.1 200 OK",
  21253. split_response.substr(0, split_response.find("\r\n")));
  21254. }
  21255. // Regression for issue #2450: a DELETE without Content-Length on a
  21256. // keep-alive connection must not let the post-response drain consume the
  21257. // next request's bytes.
  21258. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21259. Server svr;
  21260. std::atomic<int> delete_count(0);
  21261. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21262. delete_count++;
  21263. res.status = StatusCode::NoContent_204;
  21264. });
  21265. auto port = svr.bind_to_any_port(HOST);
  21266. thread t = thread([&] { svr.listen_after_bind(); });
  21267. auto se = detail::scope_exit([&] {
  21268. svr.stop();
  21269. t.join();
  21270. });
  21271. svr.wait_until_ready();
  21272. auto error = Error::Success;
  21273. auto sock = detail::create_client_socket(
  21274. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21275. /*connection_timeout_sec=*/2, 0,
  21276. /*read_timeout_sec=*/2, 0,
  21277. /*write_timeout_sec=*/2, 0, std::string(), error);
  21278. ASSERT_NE(INVALID_SOCKET, sock);
  21279. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21280. auto send_request_and_read_response = [&](const std::string &req,
  21281. std::string &out) -> bool {
  21282. auto sent = send(sock, req.data(), req.size(), 0);
  21283. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21284. char buf[4096];
  21285. for (;;) {
  21286. auto n = recv(sock, buf, sizeof(buf), 0);
  21287. if (n <= 0) { return !out.empty(); }
  21288. out.append(buf, static_cast<size_t>(n));
  21289. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21290. }
  21291. };
  21292. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21293. "Host: localhost\r\n"
  21294. "\r\n";
  21295. std::string resp1;
  21296. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21297. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21298. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21299. "Host: localhost\r\n"
  21300. "Connection: close\r\n"
  21301. "\r\n";
  21302. std::string resp2;
  21303. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21304. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21305. EXPECT_EQ(2, delete_count.load());
  21306. }
  21307. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21308. Server svr;
  21309. svr.Post("/ingest", [&](const Request &, Response &res,
  21310. const ContentReader &content_reader) {
  21311. auto consumed = content_reader([](const char *, size_t) { return false; });
  21312. EXPECT_FALSE(consumed);
  21313. res.status = StatusCode::Conflict_409;
  21314. res.set_header("Connection", "close");
  21315. });
  21316. auto port = svr.bind_to_any_port(HOST);
  21317. thread t = thread([&] { svr.listen_after_bind(); });
  21318. auto se = detail::scope_exit([&] {
  21319. svr.stop();
  21320. t.join();
  21321. });
  21322. svr.wait_until_ready();
  21323. auto error = Error::Success;
  21324. auto sock = detail::create_client_socket(
  21325. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21326. /*connection_timeout_sec=*/2, 0,
  21327. /*read_timeout_sec=*/1, 0,
  21328. /*write_timeout_sec=*/2, 0, std::string(), error);
  21329. ASSERT_NE(INVALID_SOCKET, sock);
  21330. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21331. std::string request = "POST /ingest HTTP/1.1\r\n"
  21332. "Host: localhost\r\n"
  21333. "Transfer-Encoding: chunked\r\n"
  21334. "\r\n"
  21335. "4\r\n"
  21336. "data\r\n";
  21337. auto sent = send(sock, request.data(), request.size(), 0);
  21338. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21339. std::string response;
  21340. ssize_t received = 0;
  21341. do {
  21342. char buf[4096];
  21343. received = recv(sock, buf, sizeof(buf), 0);
  21344. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21345. } while (received > 0);
  21346. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21347. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21348. EXPECT_EQ(0, received);
  21349. }
  21350. namespace no_proxy_test {
  21351. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21352. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21353. // calling listen().
  21354. class ScopedServer {
  21355. public:
  21356. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21357. ~ScopedServer() {
  21358. svr_.stop();
  21359. if (th_.joinable()) { th_.join(); }
  21360. }
  21361. Server &svr() { return svr_; }
  21362. int port() const { return port_; }
  21363. void listen() {
  21364. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21365. svr_.wait_until_ready();
  21366. }
  21367. private:
  21368. Server svr_;
  21369. std::thread th_;
  21370. int port_ = 0;
  21371. };
  21372. class ProxyAndTargetServers {
  21373. public:
  21374. ProxyAndTargetServers() {
  21375. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21376. proxy_hits_++;
  21377. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21378. res.set_content("via-proxy", "text/plain");
  21379. });
  21380. target_.Get(".*", [this](const Request &req, Response &res) {
  21381. target_hits_++;
  21382. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21383. res.set_content("direct", "text/plain");
  21384. });
  21385. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21386. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21387. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21388. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21389. proxy_mock_.wait_until_ready();
  21390. target_.wait_until_ready();
  21391. }
  21392. ~ProxyAndTargetServers() {
  21393. proxy_mock_.stop();
  21394. target_.stop();
  21395. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21396. if (target_thread_.joinable()) { target_thread_.join(); }
  21397. }
  21398. Server &proxy_mock() { return proxy_mock_; }
  21399. Server &target() { return target_; }
  21400. int proxy_port() const { return proxy_port_; }
  21401. int target_port() const { return target_port_; }
  21402. int proxy_hits() const { return proxy_hits_.load(); }
  21403. int target_hits() const { return target_hits_.load(); }
  21404. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21405. void reset_counters() {
  21406. proxy_hits_ = 0;
  21407. target_hits_ = 0;
  21408. last_had_proxy_authz_ = false;
  21409. }
  21410. private:
  21411. Server proxy_mock_;
  21412. Server target_;
  21413. std::thread proxy_thread_;
  21414. std::thread target_thread_;
  21415. int proxy_port_ = 0;
  21416. int target_port_ = 0;
  21417. std::atomic<int> proxy_hits_{0};
  21418. std::atomic<int> target_hits_{0};
  21419. std::atomic<bool> last_had_proxy_authz_{false};
  21420. };
  21421. inline std::unique_ptr<Client> make_client(const std::string &host,
  21422. ProxyAndTargetServers &s) {
  21423. auto cli = detail::make_unique<Client>(host, s.target_port());
  21424. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21425. cli->set_proxy("127.0.0.1", s.proxy_port());
  21426. return cli;
  21427. }
  21428. } // namespace no_proxy_test
  21429. using no_proxy_test::make_client;
  21430. using no_proxy_test::ProxyAndTargetServers;
  21431. TEST(NoProxyTest, ExactHostnameBypasses) {
  21432. ProxyAndTargetServers s;
  21433. auto cli = make_client("example.com", s);
  21434. cli->set_no_proxy({"example.com"});
  21435. auto res = cli->Get("/");
  21436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21437. EXPECT_EQ(0, s.proxy_hits());
  21438. EXPECT_EQ(1, s.target_hits());
  21439. }
  21440. TEST(NoProxyTest, SubdomainBypasses) {
  21441. ProxyAndTargetServers s;
  21442. auto cli = make_client("foo.example.com", s);
  21443. cli->set_no_proxy({"example.com"});
  21444. auto res = cli->Get("/");
  21445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21446. EXPECT_EQ(0, s.proxy_hits());
  21447. EXPECT_EQ(1, s.target_hits());
  21448. }
  21449. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21450. // Regression guard: "evilexample.com" must not be considered a subdomain
  21451. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21452. // check would let traffic bypass the proxy and leak credentials direct
  21453. // to the attacker host.
  21454. ProxyAndTargetServers s;
  21455. auto cli = make_client("evilexample.com", s);
  21456. cli->set_no_proxy({"example.com"});
  21457. auto res = cli->Get("/");
  21458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21459. EXPECT_GE(s.proxy_hits(), 1);
  21460. EXPECT_EQ(0, s.target_hits());
  21461. }
  21462. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21463. ProxyAndTargetServers s;
  21464. auto cli = make_client("example.com.evil.com", s);
  21465. cli->set_no_proxy({"example.com"});
  21466. auto res = cli->Get("/");
  21467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21468. EXPECT_GE(s.proxy_hits(), 1);
  21469. EXPECT_EQ(0, s.target_hits());
  21470. }
  21471. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21472. ProxyAndTargetServers s;
  21473. auto cli = make_client("example.com", s);
  21474. cli->set_no_proxy({".example.com"});
  21475. auto res = cli->Get("/");
  21476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21477. EXPECT_EQ(0, s.proxy_hits());
  21478. EXPECT_EQ(1, s.target_hits());
  21479. }
  21480. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21481. ProxyAndTargetServers s;
  21482. auto cli = make_client("Example.COM", s);
  21483. cli->set_no_proxy({"EXAMPLE.com"});
  21484. auto res = cli->Get("/");
  21485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21486. EXPECT_EQ(0, s.proxy_hits());
  21487. EXPECT_EQ(1, s.target_hits());
  21488. }
  21489. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21490. ProxyAndTargetServers s;
  21491. auto cli = make_client("example.com.", s);
  21492. cli->set_no_proxy({"example.com"});
  21493. auto res = cli->Get("/");
  21494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21495. EXPECT_EQ(0, s.proxy_hits());
  21496. EXPECT_EQ(1, s.target_hits());
  21497. }
  21498. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21499. // Trailing dots must be normalized on BOTH sides — host and entry.
  21500. // An implementation that only strips the host-side trailing dot would
  21501. // fail to match host "example.com" against entry "example.com." because
  21502. // a literal substring search would compare 11 chars against 12.
  21503. ProxyAndTargetServers s;
  21504. auto cli = make_client("example.com", s);
  21505. cli->set_no_proxy({"example.com."});
  21506. auto res = cli->Get("/");
  21507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21508. EXPECT_EQ(0, s.proxy_hits());
  21509. EXPECT_EQ(1, s.target_hits());
  21510. }
  21511. TEST(NoProxyTest, WildcardBypassesEverything) {
  21512. ProxyAndTargetServers s;
  21513. auto cli = make_client("anything.invalid.test", s);
  21514. cli->set_no_proxy({"*"});
  21515. auto res = cli->Get("/");
  21516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21517. EXPECT_EQ(0, s.proxy_hits());
  21518. EXPECT_EQ(1, s.target_hits());
  21519. }
  21520. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21521. ProxyAndTargetServers s;
  21522. Client cli("127.0.0.1", s.target_port());
  21523. cli.set_proxy("127.0.0.1", s.proxy_port());
  21524. cli.set_no_proxy({"127.0.0.1"});
  21525. auto res = cli.Get("/");
  21526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21527. EXPECT_EQ(0, s.proxy_hits());
  21528. EXPECT_EQ(1, s.target_hits());
  21529. }
  21530. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21531. ProxyAndTargetServers s;
  21532. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21533. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21534. cli.set_proxy("127.0.0.1", s.proxy_port());
  21535. cli.set_no_proxy({"::1"});
  21536. auto res = cli.Get("/");
  21537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21538. EXPECT_EQ(0, s.proxy_hits());
  21539. EXPECT_EQ(1, s.target_hits());
  21540. }
  21541. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21542. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21543. // must still be recognized as IPv6 for CIDR matching. Implementations
  21544. // that detect IPv6 only when the host begins with '[' would parse the
  21545. // host as a hostname and miss the match.
  21546. ProxyAndTargetServers s;
  21547. Client cli("fe80::1", s.target_port());
  21548. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21549. cli.set_proxy("127.0.0.1", s.proxy_port());
  21550. cli.set_no_proxy({"fe80::/10"});
  21551. auto res = cli.Get("/");
  21552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21553. EXPECT_EQ(0, s.proxy_hits());
  21554. EXPECT_EQ(1, s.target_hits());
  21555. }
  21556. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21557. ProxyAndTargetServers s;
  21558. Client cli("::1", s.target_port());
  21559. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21560. cli.set_proxy("127.0.0.1", s.proxy_port());
  21561. cli.set_no_proxy({"[::1]"});
  21562. auto res = cli.Get("/");
  21563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21564. EXPECT_EQ(0, s.proxy_hits());
  21565. EXPECT_EQ(1, s.target_hits());
  21566. }
  21567. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21568. ProxyAndTargetServers s;
  21569. Client cli("fe80::1", s.target_port());
  21570. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21571. cli.set_proxy("127.0.0.1", s.proxy_port());
  21572. cli.set_no_proxy({"[fe80::]/10"});
  21573. auto res = cli.Get("/");
  21574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21575. EXPECT_EQ(0, s.proxy_hits());
  21576. EXPECT_EQ(1, s.target_hits());
  21577. }
  21578. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21579. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21580. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21581. // tricks via address-family conversion.
  21582. ProxyAndTargetServers s;
  21583. Client cli("::ffff:127.0.0.1", s.target_port());
  21584. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21585. cli.set_proxy("127.0.0.1", s.proxy_port());
  21586. cli.set_no_proxy({"127.0.0.1"});
  21587. auto res = cli.Get("/");
  21588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21589. EXPECT_GE(s.proxy_hits(), 1);
  21590. EXPECT_EQ(0, s.target_hits());
  21591. }
  21592. TEST(NoProxyTest, IPv4CidrMatch) {
  21593. ProxyAndTargetServers s;
  21594. Client cli("127.0.0.1", s.target_port());
  21595. cli.set_proxy("127.0.0.1", s.proxy_port());
  21596. cli.set_no_proxy({"127.0.0.0/8"});
  21597. auto res = cli.Get("/");
  21598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21599. EXPECT_EQ(0, s.proxy_hits());
  21600. EXPECT_EQ(1, s.target_hits());
  21601. }
  21602. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21603. ProxyAndTargetServers s;
  21604. Client cli("127.0.0.1", s.target_port());
  21605. cli.set_proxy("127.0.0.1", s.proxy_port());
  21606. cli.set_no_proxy({"10.0.0.0/8"});
  21607. auto res = cli.Get("/");
  21608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21609. EXPECT_GE(s.proxy_hits(), 1);
  21610. EXPECT_EQ(0, s.target_hits());
  21611. }
  21612. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21613. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21614. // IPv4 target matches.
  21615. ProxyAndTargetServers s;
  21616. Client cli("127.0.0.1", s.target_port());
  21617. cli.set_proxy("127.0.0.1", s.proxy_port());
  21618. cli.set_no_proxy({"0.0.0.0/0"});
  21619. auto res = cli.Get("/");
  21620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21621. EXPECT_EQ(0, s.proxy_hits());
  21622. EXPECT_EQ(1, s.target_hits());
  21623. }
  21624. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21625. ProxyAndTargetServers s;
  21626. Client cli("127.0.0.1", s.target_port());
  21627. cli.set_proxy("127.0.0.1", s.proxy_port());
  21628. cli.set_no_proxy({"127.0.0.1"});
  21629. auto res = cli.Get("/");
  21630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21631. EXPECT_EQ(0, s.proxy_hits());
  21632. EXPECT_EQ(1, s.target_hits());
  21633. }
  21634. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21635. ProxyAndTargetServers s;
  21636. Client cli("127.0.0.1", s.target_port());
  21637. cli.set_proxy("127.0.0.1", s.proxy_port());
  21638. cli.set_no_proxy({"127.0.0.0/33"});
  21639. auto res = cli.Get("/");
  21640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21641. EXPECT_GE(s.proxy_hits(), 1);
  21642. EXPECT_EQ(0, s.target_hits());
  21643. }
  21644. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21645. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21646. ProxyAndTargetServers s;
  21647. Client cli("127.0.0.1", s.target_port());
  21648. cli.set_proxy("127.0.0.1", s.proxy_port());
  21649. cli.set_no_proxy({"127.0.0.1/"});
  21650. auto res = cli.Get("/");
  21651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21652. EXPECT_GE(s.proxy_hits(), 1);
  21653. EXPECT_EQ(0, s.target_hits());
  21654. }
  21655. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21656. ProxyAndTargetServers s;
  21657. auto cli = make_client("internal.corp", s);
  21658. cli->set_proxy_basic_auth("u", "p");
  21659. cli->set_no_proxy({"internal.corp"});
  21660. auto res = cli->Get("/");
  21661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21662. EXPECT_EQ(1, s.target_hits());
  21663. EXPECT_EQ(0, s.proxy_hits());
  21664. EXPECT_FALSE(s.last_had_proxy_authz())
  21665. << "Proxy-Authorization must not be sent direct to the target";
  21666. }
  21667. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21668. ProxyAndTargetServers s;
  21669. auto cli = make_client("public.example", s);
  21670. cli->set_proxy_basic_auth("u", "p");
  21671. cli->set_no_proxy({"internal.corp"}); // does not match
  21672. auto res = cli->Get("/");
  21673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21674. EXPECT_GE(s.proxy_hits(), 1);
  21675. EXPECT_TRUE(s.last_had_proxy_authz());
  21676. }
  21677. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21678. ProxyAndTargetServers s;
  21679. auto cli = make_client("anything.test", s);
  21680. auto res = cli->Get("/");
  21681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21682. EXPECT_GE(s.proxy_hits(), 1);
  21683. EXPECT_EQ(0, s.target_hits());
  21684. }
  21685. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21686. ProxyAndTargetServers s;
  21687. auto cli = make_client("example.com", s);
  21688. cli->set_no_proxy({"example.com:8080"});
  21689. auto res = cli->Get("/");
  21690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21691. EXPECT_GE(s.proxy_hits(), 1);
  21692. EXPECT_EQ(0, s.target_hits());
  21693. }
  21694. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21695. ProxyAndTargetServers s;
  21696. auto cli = make_client("anything.test", s);
  21697. cli->set_no_proxy({"", " ", "\t"});
  21698. auto res = cli->Get("/");
  21699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21700. EXPECT_GE(s.proxy_hits(), 1);
  21701. EXPECT_EQ(0, s.target_hits());
  21702. }
  21703. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21704. // An entry with leading/trailing whitespace must still match — env-style
  21705. // values are commonly pasted with stray spaces and an implementation
  21706. // that feeds the raw token directly to inet_pton would fail to match
  21707. // valid CIDRs because of the spaces.
  21708. ProxyAndTargetServers s;
  21709. Client cli("127.0.0.1", s.target_port());
  21710. cli.set_proxy("127.0.0.1", s.proxy_port());
  21711. cli.set_no_proxy({" 127.0.0.0/8 "});
  21712. auto res = cli.Get("/");
  21713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21714. EXPECT_EQ(0, s.proxy_hits());
  21715. EXPECT_EQ(1, s.target_hits());
  21716. }
  21717. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21718. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21719. // go direct and must NOT carry Proxy-Authorization.
  21720. std::atomic<int> proxy_hits{0};
  21721. std::atomic<int> target_hits{0};
  21722. std::atomic<bool> target_saw_authz{false};
  21723. no_proxy_test::ScopedServer proxy_mock, target;
  21724. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21725. proxy_hits++;
  21726. res.status = 302;
  21727. res.set_header("Location", "http://127.0.0.1:" +
  21728. std::to_string(target.port()) + "/landed");
  21729. });
  21730. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21731. target_hits++;
  21732. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21733. res.set_content("direct", "text/plain");
  21734. });
  21735. proxy_mock.listen();
  21736. target.listen();
  21737. Client cli("public.example", target.port());
  21738. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21739. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21740. cli.set_proxy_basic_auth("u", "p");
  21741. cli.set_no_proxy({"127.0.0.1"});
  21742. cli.set_follow_location(true);
  21743. auto res = cli.Get("/redir");
  21744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21745. EXPECT_GE(proxy_hits.load(), 1);
  21746. EXPECT_GE(target_hits.load(), 1);
  21747. EXPECT_FALSE(target_saw_authz.load());
  21748. }
  21749. #ifdef CPPHTTPLIB_SSL_ENABLED
  21750. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21751. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21752. // proxy creds would be sent to the (possibly hostile) origin.
  21753. std::atomic<int> target_hits{0};
  21754. std::atomic<bool> target_saw_proxy_authz{false};
  21755. no_proxy_test::ScopedServer target;
  21756. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21757. target_hits++;
  21758. if (req.has_header("Proxy-Authorization")) {
  21759. target_saw_proxy_authz = true;
  21760. }
  21761. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21762. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21763. "nonce=\"abc\", algorithm=MD5");
  21764. });
  21765. target.listen();
  21766. // The proxy address is set to the target's port: the bypass MUST kick in;
  21767. // if it doesn't, the test still routes "via proxy" to the same server and
  21768. // the Proxy-Authorization assertion below catches the leak.
  21769. Client cli("evil.example", target.port());
  21770. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21771. cli.set_proxy("127.0.0.1", target.port());
  21772. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21773. cli.set_no_proxy({"evil.example"});
  21774. auto res = cli.Get("/x");
  21775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21776. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21777. EXPECT_EQ(1, target_hits.load());
  21778. EXPECT_FALSE(target_saw_proxy_authz.load());
  21779. }
  21780. #endif
  21781. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21782. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21783. std::atomic<int> proxy_hits{0};
  21784. std::atomic<int> bypass_hits{0};
  21785. std::atomic<bool> proxy_saw_c_url{false};
  21786. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21787. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21788. proxy_hits++;
  21789. if (req.path.find("/start") != std::string::npos) {
  21790. res.status = 302;
  21791. res.set_header("Location", "http://127.0.0.1:" +
  21792. std::to_string(bypass_server.port()) +
  21793. "/middle");
  21794. return;
  21795. }
  21796. if (req.path.find("/end") != std::string::npos) {
  21797. proxy_saw_c_url = true;
  21798. res.set_content("c-via-proxy", "text/plain");
  21799. return;
  21800. }
  21801. res.set_content("unexpected", "text/plain");
  21802. });
  21803. // public.example's "advertised" port is arbitrary (the request never lands
  21804. // there — it goes through the proxy), but use a dynamic value to stay
  21805. // friendly with sharded parallel runs.
  21806. int public_port = bypass_server.port();
  21807. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21808. bypass_hits++;
  21809. res.status = 302;
  21810. res.set_header("Location", "http://public.example:" +
  21811. std::to_string(public_port) + "/end");
  21812. });
  21813. proxy_mock.listen();
  21814. bypass_server.listen();
  21815. Client cli("public.example", public_port);
  21816. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21817. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21818. cli.set_no_proxy({"127.0.0.1"});
  21819. cli.set_follow_location(true);
  21820. auto res = cli.Get("/start");
  21821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21822. EXPECT_EQ(StatusCode::OK_200, res->status);
  21823. EXPECT_EQ("c-via-proxy", res->body);
  21824. EXPECT_GE(proxy_hits.load(), 2);
  21825. EXPECT_GE(bypass_hits.load(), 1);
  21826. EXPECT_TRUE(proxy_saw_c_url.load());
  21827. }
  21828. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21829. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21830. // request reconnects to the correct endpoint.
  21831. std::atomic<int> proxy_hits{0};
  21832. std::atomic<int> target_hits{0};
  21833. no_proxy_test::ScopedServer proxy_mock, target;
  21834. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21835. proxy_hits++;
  21836. res.set_content("via-proxy", "text/plain");
  21837. });
  21838. target.svr().Get(".*", [&](const Request &, Response &res) {
  21839. target_hits++;
  21840. res.set_content("direct", "text/plain");
  21841. });
  21842. proxy_mock.listen();
  21843. target.listen();
  21844. Client cli("public.example", target.port());
  21845. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21846. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21847. cli.set_keep_alive(true);
  21848. auto res1 = cli.Get("/a");
  21849. ASSERT_TRUE(res1);
  21850. EXPECT_EQ("via-proxy", res1->body);
  21851. EXPECT_EQ(1, proxy_hits.load());
  21852. EXPECT_EQ(0, target_hits.load());
  21853. cli.set_no_proxy({"public.example"});
  21854. auto res2 = cli.Get("/b");
  21855. ASSERT_TRUE(res2);
  21856. EXPECT_EQ("direct", res2->body);
  21857. EXPECT_EQ(1, proxy_hits.load());
  21858. EXPECT_EQ(1, target_hits.load());
  21859. }
  21860. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21861. namespace proxy_tunnel_test {
  21862. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21863. class ScopedSSLServer {
  21864. public:
  21865. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21866. port_ = svr_.bind_to_any_port("127.0.0.1");
  21867. }
  21868. ~ScopedSSLServer() {
  21869. svr_.stop();
  21870. if (th_.joinable()) { th_.join(); }
  21871. }
  21872. SSLServer &svr() { return svr_; }
  21873. int port() const { return port_; }
  21874. void listen() {
  21875. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21876. svr_.wait_until_ready();
  21877. }
  21878. private:
  21879. SSLServer svr_;
  21880. std::thread th_;
  21881. int port_ = 0;
  21882. };
  21883. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21884. class ScopedConnectProxy {
  21885. public:
  21886. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21887. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21888. if (listen_fd_ < 0) { return; }
  21889. int yes = 1;
  21890. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21891. sockaddr_in a{};
  21892. a.sin_family = AF_INET;
  21893. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21894. a.sin_port = 0;
  21895. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21896. return;
  21897. }
  21898. socklen_t alen = sizeof(a);
  21899. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21900. 0) {
  21901. return;
  21902. }
  21903. port_ = ntohs(a.sin_port);
  21904. if (::listen(listen_fd_, 1) != 0) { return; }
  21905. th_ = std::thread([this] { run(); });
  21906. }
  21907. ~ScopedConnectProxy() {
  21908. stop_ = true;
  21909. if (listen_fd_ >= 0) {
  21910. ::shutdown(listen_fd_, SHUT_RDWR);
  21911. ::close(listen_fd_);
  21912. }
  21913. if (th_.joinable()) { th_.join(); }
  21914. }
  21915. int port() const { return port_; }
  21916. int connect_hits() const { return connect_hits_.load(); }
  21917. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21918. std::string connect_request() const {
  21919. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21920. return connect_request_;
  21921. }
  21922. private:
  21923. void run() {
  21924. while (!stop_.load()) {
  21925. fd_set rfds;
  21926. FD_ZERO(&rfds);
  21927. FD_SET(listen_fd_, &rfds);
  21928. timeval tv{0, 100 * 1000};
  21929. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21930. if (sel <= 0) { continue; }
  21931. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21932. if (client_fd < 0) { continue; }
  21933. std::string req;
  21934. char buf[2048];
  21935. while (req.find("\r\n\r\n") == std::string::npos) {
  21936. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21937. if (n <= 0) { break; }
  21938. req.append(buf, static_cast<size_t>(n));
  21939. }
  21940. if (req.compare(0, 7, "CONNECT") != 0) {
  21941. ::close(client_fd);
  21942. continue;
  21943. }
  21944. connect_hits_++;
  21945. {
  21946. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21947. connect_request_ = req;
  21948. }
  21949. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21950. ::send(client_fd, ok, std::strlen(ok), 0);
  21951. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21952. sockaddr_in o{};
  21953. o.sin_family = AF_INET;
  21954. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21955. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21956. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21957. 0) {
  21958. ::close(client_fd);
  21959. ::close(origin_fd);
  21960. continue;
  21961. }
  21962. auto forward = [](int from, int to) {
  21963. char b[8192];
  21964. for (;;) {
  21965. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21966. if (n <= 0) { break; }
  21967. ssize_t off = 0;
  21968. while (off < n) {
  21969. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21970. if (s <= 0) {
  21971. off = n;
  21972. break;
  21973. }
  21974. off += s;
  21975. }
  21976. }
  21977. ::shutdown(to, SHUT_WR);
  21978. };
  21979. std::thread t1([&] { forward(client_fd, origin_fd); });
  21980. std::thread t2([&] { forward(origin_fd, client_fd); });
  21981. t1.join();
  21982. t2.join();
  21983. ::close(client_fd);
  21984. ::close(origin_fd);
  21985. }
  21986. }
  21987. int forward_port_ = -1;
  21988. int listen_fd_ = -1;
  21989. int port_ = 0;
  21990. std::thread th_;
  21991. std::atomic<bool> stop_{false};
  21992. std::atomic<int> connect_hits_{0};
  21993. mutable std::mutex connect_request_mutex_;
  21994. std::string connect_request_;
  21995. };
  21996. // Sends one request through the CONNECT proxy to the TLS origin with a
  21997. // credential configured for each hop, and checks that each credential reaches
  21998. // only the hop it was configured for: the proxy's on the CONNECT request, the
  21999. // origin's (every header in origin_headers) on the tunnelled request.
  22000. void CredentialsStayWithTheirHop(
  22001. const std::function<void(SSLClient &)> &set_credentials,
  22002. const std::string &scheme,
  22003. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22004. std::atomic<int> origin_hits{0};
  22005. std::atomic<bool> origin_saw_proxy_authz{false};
  22006. std::atomic<bool> origin_saw_headers{false};
  22007. ScopedSSLServer origin;
  22008. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22009. origin_hits++;
  22010. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22011. origin_saw_headers =
  22012. std::all_of(origin_headers.begin(), origin_headers.end(),
  22013. [&](const std::string &h) { return req.has_header(h); });
  22014. res.set_content("ok", "text/plain");
  22015. });
  22016. origin.listen();
  22017. ScopedConnectProxy proxy(origin.port());
  22018. ASSERT_NE(0, proxy.port());
  22019. // Pinned to 127.0.0.1 for the same reason as the test below.
  22020. SSLClient cli("127.0.0.1", origin.port());
  22021. cli.enable_server_certificate_verification(false);
  22022. cli.set_proxy("127.0.0.1", proxy.port());
  22023. set_credentials(cli);
  22024. auto res = cli.Get("/x");
  22025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22026. EXPECT_EQ(StatusCode::OK_200, res->status);
  22027. EXPECT_EQ(1, origin_hits.load());
  22028. EXPECT_EQ(1, proxy.connect_hits());
  22029. EXPECT_TRUE(origin_saw_headers.load());
  22030. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22031. << "Proxy-Authorization must not be sent inside the tunnel";
  22032. auto connect_req = proxy.connect_request();
  22033. EXPECT_NE(std::string::npos,
  22034. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22035. for (const auto &h : origin_headers) {
  22036. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22037. << h << " must not be sent to the proxy on CONNECT";
  22038. }
  22039. }
  22040. } // namespace proxy_tunnel_test
  22041. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22042. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22043. [](SSLClient &cli) {
  22044. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22045. cli.set_basic_auth("origin-user", "origin-pass");
  22046. },
  22047. "Basic");
  22048. }
  22049. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22050. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22051. [](SSLClient &cli) {
  22052. cli.set_proxy_bearer_token_auth("proxy-token");
  22053. cli.set_bearer_token_auth("origin-token");
  22054. },
  22055. "Bearer");
  22056. }
  22057. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22058. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22059. [](SSLClient &cli) {
  22060. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22061. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22062. {"Cookie", "sid=origin-session"},
  22063. {"X-Api-Key", "origin-key"}});
  22064. },
  22065. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22066. }
  22067. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22068. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22069. // retry; otherwise proxy creds would be sent to the origin.
  22070. std::atomic<int> origin_hits{0};
  22071. std::atomic<bool> origin_saw_proxy_authz{false};
  22072. proxy_tunnel_test::ScopedSSLServer origin;
  22073. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22074. origin_hits++;
  22075. if (req.has_header("Proxy-Authorization")) {
  22076. origin_saw_proxy_authz = true;
  22077. }
  22078. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22079. res.set_header("Proxy-Authenticate",
  22080. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22081. "algorithm=MD5");
  22082. });
  22083. origin.listen();
  22084. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22085. ASSERT_NE(0, proxy.port());
  22086. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22087. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22088. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22089. // and answer with its own status, making this test flaky.
  22090. SSLClient cli("127.0.0.1", origin.port());
  22091. cli.enable_server_certificate_verification(false);
  22092. cli.set_proxy("127.0.0.1", proxy.port());
  22093. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22094. auto res = cli.Get("/x");
  22095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22096. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22097. EXPECT_EQ(1, origin_hits.load());
  22098. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22099. EXPECT_EQ(1, proxy.connect_hits());
  22100. }
  22101. #endif