1
0

test.cc 779 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255
  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. // Empty media type
  898. result.clear();
  899. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  900. // Only commas
  901. result.clear();
  902. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  903. // Valid cases should still work
  904. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*/*");
  907. EXPECT_TRUE(detail::parse_accept_header("*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "*");
  910. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  911. EXPECT_EQ(result.size(), 1U);
  912. EXPECT_EQ(result[0], "text/*");
  913. }
  914. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  915. Server svr;
  916. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  917. EXPECT_EQ(req.accept_content_types.size(), 3U);
  918. EXPECT_EQ(req.accept_content_types[0], "application/json");
  919. EXPECT_EQ(req.accept_content_types[1], "text/html");
  920. EXPECT_EQ(req.accept_content_types[2], "*/*");
  921. res.set_content("ok", "text/plain");
  922. });
  923. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  924. EXPECT_TRUE(false);
  925. res.set_content("bad request", "text/plain");
  926. });
  927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  928. auto se = detail::scope_exit([&] {
  929. svr.stop();
  930. listen_thread.join();
  931. ASSERT_FALSE(svr.is_running());
  932. });
  933. svr.wait_until_ready();
  934. Client cli("localhost", PORT);
  935. {
  936. auto res = cli.Get(
  937. "/accept_ok",
  938. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  940. EXPECT_EQ(StatusCode::OK_200, res->status);
  941. }
  942. {
  943. auto res = cli.Get("/accept_bad_request",
  944. Headers{{"Accept", "text/html;q=abc,application/json"}});
  945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  946. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  947. }
  948. }
  949. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  950. Server svr;
  951. svr.Get("/", [](const Request & /*req*/, Response &res) {
  952. res.set_content("ok", "text/plain");
  953. });
  954. std::atomic<int> start_count{0};
  955. std::atomic<bool> running_when_called{false};
  956. svr.set_start_handler([&]() {
  957. running_when_called = svr.is_running();
  958. start_count++;
  959. });
  960. auto port = svr.bind_to_any_port(HOST);
  961. std::thread t([&]() { svr.listen_after_bind(); });
  962. auto se = detail::scope_exit([&] {
  963. svr.stop();
  964. t.join();
  965. ASSERT_FALSE(svr.is_running());
  966. });
  967. svr.wait_until_ready();
  968. // A successful request proves the accept loop is running, which the start
  969. // handler precedes; so by now the handler must have run exactly once.
  970. Client cli(HOST, port);
  971. cli.set_connection_timeout(std::chrono::seconds(5));
  972. auto res = cli.Get("/");
  973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  974. EXPECT_EQ(StatusCode::OK_200, res->status);
  975. EXPECT_EQ(1, start_count.load());
  976. EXPECT_TRUE(running_when_called.load());
  977. }
  978. TEST(DivideTest, DivideStringTests) {
  979. auto divide = [](const std::string &str, char d) {
  980. std::string lhs;
  981. std::string rhs;
  982. detail::divide(str, d,
  983. [&](const char *lhs_data, std::size_t lhs_size,
  984. const char *rhs_data, std::size_t rhs_size) {
  985. lhs.assign(lhs_data, lhs_size);
  986. rhs.assign(rhs_data, rhs_size);
  987. });
  988. return std::make_pair(std::move(lhs), std::move(rhs));
  989. };
  990. {
  991. const auto res = divide("", '=');
  992. EXPECT_EQ(res.first, "");
  993. EXPECT_EQ(res.second, "");
  994. }
  995. {
  996. const auto res = divide("=", '=');
  997. EXPECT_EQ(res.first, "");
  998. EXPECT_EQ(res.second, "");
  999. }
  1000. {
  1001. const auto res = divide(" ", '=');
  1002. EXPECT_EQ(res.first, " ");
  1003. EXPECT_EQ(res.second, "");
  1004. }
  1005. {
  1006. const auto res = divide("a", '=');
  1007. EXPECT_EQ(res.first, "a");
  1008. EXPECT_EQ(res.second, "");
  1009. }
  1010. {
  1011. const auto res = divide("a=", '=');
  1012. EXPECT_EQ(res.first, "a");
  1013. EXPECT_EQ(res.second, "");
  1014. }
  1015. {
  1016. const auto res = divide("=b", '=');
  1017. EXPECT_EQ(res.first, "");
  1018. EXPECT_EQ(res.second, "b");
  1019. }
  1020. {
  1021. const auto res = divide("a=b", '=');
  1022. EXPECT_EQ(res.first, "a");
  1023. EXPECT_EQ(res.second, "b");
  1024. }
  1025. {
  1026. const auto res = divide("a=b=", '=');
  1027. EXPECT_EQ(res.first, "a");
  1028. EXPECT_EQ(res.second, "b=");
  1029. }
  1030. {
  1031. const auto res = divide("a=b=c", '=');
  1032. EXPECT_EQ(res.first, "a");
  1033. EXPECT_EQ(res.second, "b=c");
  1034. }
  1035. }
  1036. TEST(SplitTest, ParseQueryString) {
  1037. string s = "key1=val1&key2=val2&key3=val3";
  1038. Params dic;
  1039. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1040. [&](const char *b, const char *e) {
  1041. string key, val;
  1042. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1043. if (key.empty()) {
  1044. key.assign(b2, e2);
  1045. } else {
  1046. val.assign(b2, e2);
  1047. }
  1048. });
  1049. dic.emplace(key, val);
  1050. });
  1051. EXPECT_EQ("val1", dic.find("key1")->second);
  1052. EXPECT_EQ("val2", dic.find("key2")->second);
  1053. EXPECT_EQ("val3", dic.find("key3")->second);
  1054. }
  1055. TEST(SplitTest, ParseInvalidQueryTests) {
  1056. {
  1057. string s = " ";
  1058. Params dict;
  1059. detail::parse_query_text(s, dict);
  1060. EXPECT_TRUE(dict.empty());
  1061. }
  1062. {
  1063. string s = " = =";
  1064. Params dict;
  1065. detail::parse_query_text(s, dict);
  1066. EXPECT_TRUE(dict.empty());
  1067. }
  1068. }
  1069. TEST(ParseQueryTest, ParseQueryString) {
  1070. {
  1071. std::string s = "key1=val1&key2=val2&key3=val3";
  1072. Params dic;
  1073. detail::parse_query_text(s, dic);
  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. {
  1079. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1080. Params dic;
  1081. detail::parse_query_text(s, dic);
  1082. EXPECT_EQ("", dic.find("key1")->second);
  1083. EXPECT_EQ("val1", dic.find("key2")->second);
  1084. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1085. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1086. }
  1087. }
  1088. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1089. Params dic;
  1090. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1091. dic.emplace("key1", "val1");
  1092. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1093. dic.emplace("key2", "val2");
  1094. dic.emplace("key3", "val3");
  1095. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1096. }
  1097. // Joins every entry of a Headers or Params into "key=value " so a whole
  1098. // traversal can be compared in one assertion. Both are instantiations of the
  1099. // same insertion-ordered container, so one helper serves both.
  1100. template <typename Map> static std::string entries_to_string(const Map &m) {
  1101. std::string s;
  1102. for (const auto &entry : m) {
  1103. s += entry.first + "=" + entry.second + " ";
  1104. }
  1105. return s;
  1106. }
  1107. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1108. // Params used to be a std::multimap, which sorted by name and handed the
  1109. // caller's query back alphabetised. A client signing its query string could
  1110. // not reproduce the order it asked for.
  1111. Params dic;
  1112. dic.emplace("zulu", "1");
  1113. dic.emplace("alpha", "2");
  1114. dic.emplace("mike", "3");
  1115. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1116. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1117. }
  1118. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1119. Params dic;
  1120. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1121. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1122. }
  1123. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1124. Request req;
  1125. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1126. req.params);
  1127. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1128. EXPECT_EQ("first", req.get_param_value("tag"));
  1129. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1130. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1131. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1132. EXPECT_EQ("", req.get_param_value("tag", 3));
  1133. }
  1134. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1135. // Params shares its container with Headers, which matches field names
  1136. // case-insensitively. Parameter names must not pick that up.
  1137. Params dic;
  1138. dic.emplace("Key", "upper");
  1139. dic.emplace("key", "lower");
  1140. EXPECT_EQ(2U, dic.size());
  1141. EXPECT_EQ(1U, dic.count("Key"));
  1142. EXPECT_EQ(1U, dic.count("key"));
  1143. EXPECT_EQ("upper", dic.find("Key")->second);
  1144. EXPECT_EQ("lower", dic.find("key")->second);
  1145. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1146. }
  1147. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1148. Server svr;
  1149. std::string order;
  1150. svr.Get("/order", [&](const Request &req, Response &res) {
  1151. order = entries_to_string(req.params);
  1152. res.set_content("ok", "text/plain");
  1153. });
  1154. auto port = svr.bind_to_any_port(HOST);
  1155. thread t = thread([&] { svr.listen_after_bind(); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. t.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli(HOST, port);
  1163. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1166. }
  1167. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1168. Server svr;
  1169. std::string field_order, file_order;
  1170. svr.Post("/order", [&](const Request &req, Response &res) {
  1171. for (const auto &field : req.form.fields) {
  1172. field_order += field.first + "=" + field.second.content + " ";
  1173. }
  1174. for (const auto &file : req.form.files) {
  1175. file_order += file.first + "=" + file.second.filename + " ";
  1176. }
  1177. res.set_content("ok", "text/plain");
  1178. });
  1179. auto port = svr.bind_to_any_port(HOST);
  1180. thread t = thread([&] { svr.listen_after_bind(); });
  1181. auto se = detail::scope_exit([&] {
  1182. svr.stop();
  1183. t.join();
  1184. ASSERT_FALSE(svr.is_running());
  1185. });
  1186. svr.wait_until_ready();
  1187. UploadFormDataItems items = {
  1188. {"zulu", "1", "", ""},
  1189. {"alpha", "2", "", ""},
  1190. {"mike", "3", "", ""},
  1191. {"zebra", "z", "z.txt", "text/plain"},
  1192. {"apple", "a", "a.txt", "text/plain"},
  1193. };
  1194. Client cli(HOST, port);
  1195. auto res = cli.Post("/order", items);
  1196. ASSERT_TRUE(res);
  1197. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1198. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1199. }
  1200. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1201. Server svr;
  1202. std::vector<std::string> values;
  1203. std::string first, second, out_of_range, order;
  1204. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1205. values = req.form.get_fields("tag");
  1206. first = req.form.get_field("tag", 0);
  1207. second = req.form.get_field("tag", 1);
  1208. out_of_range = req.form.get_field("tag", 2);
  1209. for (const auto &field : req.form.fields) {
  1210. order += field.first + "=" + field.second.content + " ";
  1211. }
  1212. res.set_content("ok", "text/plain");
  1213. });
  1214. auto port = svr.bind_to_any_port(HOST);
  1215. thread t = thread([&] { svr.listen_after_bind(); });
  1216. auto se = detail::scope_exit([&] {
  1217. svr.stop();
  1218. t.join();
  1219. ASSERT_FALSE(svr.is_running());
  1220. });
  1221. svr.wait_until_ready();
  1222. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1223. // not adjacent in the container.
  1224. UploadFormDataItems items = {
  1225. {"tag", "first", "", ""},
  1226. {"other", "x", "", ""},
  1227. {"tag", "second", "", ""},
  1228. };
  1229. Client cli(HOST, port);
  1230. auto res = cli.Post("/repeated", items);
  1231. ASSERT_TRUE(res);
  1232. ASSERT_EQ(2U, values.size());
  1233. EXPECT_EQ("first", values[0]);
  1234. EXPECT_EQ("second", values[1]);
  1235. EXPECT_EQ("first", first);
  1236. EXPECT_EQ("second", second);
  1237. // std::multimap already kept entries sharing a name in insertion order, so
  1238. // everything above passes without this change too. The whole traversal is
  1239. // what tells the two apart: sorting by name would hoist "other" to the front
  1240. // and the two "tag" parts would end up adjacent.
  1241. EXPECT_EQ("tag=first other=x tag=second ", order);
  1242. // Advancing past the last entry of a name used to run off the container;
  1243. // the container's saturating increment makes it return the default instead.
  1244. EXPECT_EQ("", out_of_range);
  1245. }
  1246. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1247. // Server::read_content() keeps a FormFields::iterator alive across the
  1248. // content callbacks that fill the part it points at. The container is
  1249. // vector-backed, so a later emplace can reallocate and invalidate an older
  1250. // iterator; 64 parts grow the vector through seven reallocations, which
  1251. // checks that every part's content still lands in its own entry.
  1252. const size_t part_count = 64;
  1253. // One formula for both the parts sent and the values expected back, so the
  1254. // two cannot drift apart.
  1255. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1256. auto content_of = [](size_t i) {
  1257. return std::string(64, static_cast<char>('a' + (i % 26)));
  1258. };
  1259. Server svr;
  1260. std::vector<std::pair<std::string, std::string>> received;
  1261. svr.Post("/many", [&](const Request &req, Response &res) {
  1262. for (const auto &field : req.form.fields) {
  1263. received.emplace_back(field.first, field.second.content);
  1264. }
  1265. res.set_content("ok", "text/plain");
  1266. });
  1267. auto port = svr.bind_to_any_port(HOST);
  1268. thread t = thread([&] { svr.listen_after_bind(); });
  1269. auto se = detail::scope_exit([&] {
  1270. svr.stop();
  1271. t.join();
  1272. ASSERT_FALSE(svr.is_running());
  1273. });
  1274. svr.wait_until_ready();
  1275. UploadFormDataItems items;
  1276. for (size_t i = 0; i < part_count; i++) {
  1277. items.push_back({name_of(i), content_of(i), "", ""});
  1278. }
  1279. Client cli(HOST, port);
  1280. auto res = cli.Post("/many", items);
  1281. ASSERT_TRUE(res);
  1282. ASSERT_EQ(part_count, received.size());
  1283. for (size_t i = 0; i < part_count; i++) {
  1284. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1285. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1286. }
  1287. }
  1288. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1289. string content_type = "multipart/form-data; boundary=something";
  1290. string boundary;
  1291. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1292. EXPECT_TRUE(ret);
  1293. EXPECT_EQ(boundary, "something");
  1294. }
  1295. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1296. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1297. string boundary;
  1298. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1299. EXPECT_TRUE(ret);
  1300. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1301. }
  1302. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1303. string content_type =
  1304. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1305. string boundary;
  1306. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1307. EXPECT_TRUE(ret);
  1308. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1309. }
  1310. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1311. string content_type =
  1312. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1319. const string boundary(70, 'a');
  1320. string content_type = "multipart/form-data; boundary=" + boundary;
  1321. string parsed;
  1322. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1323. EXPECT_TRUE(ret);
  1324. EXPECT_EQ(parsed, boundary);
  1325. }
  1326. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1327. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1328. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1329. string parsed;
  1330. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1331. EXPECT_FALSE(ret);
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1334. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1335. // is 72 characters on the wire and still valid.
  1336. const string boundary(70, 'a');
  1337. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1338. string parsed;
  1339. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1340. EXPECT_EQ(parsed, boundary);
  1341. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1342. parsed.clear();
  1343. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1344. }
  1345. TEST(GetHeaderValueTest, DefaultValue) {
  1346. Headers headers = {{"Dummy", "Dummy"}};
  1347. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1348. EXPECT_STREQ("text/plain", val);
  1349. }
  1350. TEST(GetHeaderValueTest, DefaultValueInt) {
  1351. Headers headers = {{"Dummy", "Dummy"}};
  1352. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1353. EXPECT_EQ(100ull, val);
  1354. }
  1355. TEST(GetHeaderValueTest, RegularValue) {
  1356. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1357. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1358. EXPECT_STREQ("text/html", val);
  1359. }
  1360. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1361. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1362. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1363. EXPECT_STREQ("text/html", val);
  1364. }
  1365. TEST(GetHeaderValueTest, SetContent) {
  1366. Response res;
  1367. res.set_content("html", "text/html");
  1368. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1369. res.set_content("text", "text/plain");
  1370. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1371. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1372. }
  1373. TEST(GetHeaderValueTest, RegularValueInt) {
  1374. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1375. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1376. EXPECT_EQ(100ull, val);
  1377. }
  1378. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1379. Headers headers = {{"Content-Length", "x"}};
  1380. auto is_invalid_value = false;
  1381. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1382. is_invalid_value);
  1383. EXPECT_EQ(0ull, val);
  1384. EXPECT_TRUE(is_invalid_value);
  1385. }
  1386. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1387. // An all-digit value that overflows size_t must be reported as invalid, not
  1388. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1389. // a large length to a small one on 32-bit builds, leaving the framing length
  1390. // wrong while is_invalid_value stayed false.
  1391. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1392. auto is_invalid_value = false;
  1393. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1394. is_invalid_value);
  1395. EXPECT_TRUE(is_invalid_value);
  1396. // A well-formed length is unaffected.
  1397. Headers ok = {{"Content-Length", "1234"}};
  1398. is_invalid_value = false;
  1399. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1400. is_invalid_value);
  1401. EXPECT_EQ(1234ull, val);
  1402. EXPECT_FALSE(is_invalid_value);
  1403. }
  1404. TEST(GetHeaderValueTest, Range) {
  1405. {
  1406. Headers headers = {make_range_header({{1, -1}})};
  1407. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1408. EXPECT_STREQ("bytes=1-", val);
  1409. }
  1410. {
  1411. Headers headers = {make_range_header({{-1, 1}})};
  1412. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1413. EXPECT_STREQ("bytes=-1", val);
  1414. }
  1415. {
  1416. Headers headers = {make_range_header({{1, 10}})};
  1417. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1418. EXPECT_STREQ("bytes=1-10", val);
  1419. }
  1420. {
  1421. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1422. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1423. EXPECT_STREQ("bytes=1-10, 100-", val);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1427. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1428. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1429. }
  1430. {
  1431. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1432. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1433. EXPECT_STREQ("bytes=0-0, -1", val);
  1434. }
  1435. }
  1436. TEST(BearerTokenAuthTest, SchemeValidation) {
  1437. // A value shorter than "Bearer " must not throw from the fixed-length
  1438. // substr, and a non-Bearer scheme must not be reported as a token.
  1439. struct {
  1440. const char *value;
  1441. const char *expected;
  1442. } cases[] = {
  1443. {"x", ""},
  1444. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1445. {"Bearer abc123", "abc123"},
  1446. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1447. };
  1448. for (const auto &c : cases) {
  1449. Request req;
  1450. req.set_header("Authorization", c.value);
  1451. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1452. }
  1453. }
  1454. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1455. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1456. // to depend on the standard library (libstdc++ handed back duplicates in
  1457. // reverse insertion order, libc++ in insertion order).
  1458. Request req;
  1459. req.set_header("Accept-Encoding", "gzip");
  1460. req.set_header("Accept-Encoding", "deflate");
  1461. req.set_header("Accept-Encoding", "br");
  1462. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1463. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1464. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1465. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1466. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1467. }
  1468. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1469. Request req;
  1470. req.set_header("X-Test", "only");
  1471. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1472. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1473. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1474. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1475. }
  1476. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1477. Headers headers;
  1478. headers.emplace("Host", "example.com");
  1479. headers.emplace("Accept-Encoding", "gzip");
  1480. headers.emplace("User-Agent", "test");
  1481. headers.emplace("Accept-Encoding", "deflate");
  1482. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1483. "Accept-Encoding=deflate ",
  1484. entries_to_string(headers));
  1485. }
  1486. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1487. Headers headers = {{"Content-Type", "text/html"},
  1488. {"CONTENT-TYPE", "text/xml"}};
  1489. EXPECT_EQ(2U, headers.count("content-type"));
  1490. auto it = headers.find("content-type");
  1491. ASSERT_TRUE(it != headers.end());
  1492. EXPECT_EQ("text/html", it->second);
  1493. }
  1494. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1495. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1496. // drop only those fields and leave everything positioned between them.
  1497. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1498. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1499. auto rng = headers.equal_range("a");
  1500. headers.erase(rng.first, rng.second);
  1501. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1502. }
  1503. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1504. Headers headers = {
  1505. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1506. EXPECT_EQ(3U, headers.erase("A"));
  1507. EXPECT_EQ(0U, headers.count("A"));
  1508. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1509. }
  1510. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1511. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1512. headers.emplace_front("Host", "example.com");
  1513. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1514. entries_to_string(headers));
  1515. }
  1516. TEST(ParseHeaderValueTest, Range) {
  1517. {
  1518. Ranges ranges;
  1519. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1520. EXPECT_TRUE(ret);
  1521. EXPECT_EQ(1u, ranges.size());
  1522. EXPECT_EQ(1u, ranges[0].first);
  1523. EXPECT_EQ(-1, ranges[0].second);
  1524. }
  1525. {
  1526. Ranges ranges;
  1527. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1528. EXPECT_TRUE(ret);
  1529. EXPECT_EQ(1u, ranges.size());
  1530. EXPECT_EQ(-1, ranges[0].first);
  1531. EXPECT_EQ(1u, ranges[0].second);
  1532. }
  1533. {
  1534. Ranges ranges;
  1535. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1536. EXPECT_TRUE(ret);
  1537. EXPECT_EQ(1u, ranges.size());
  1538. EXPECT_EQ(1u, ranges[0].first);
  1539. EXPECT_EQ(10u, ranges[0].second);
  1540. }
  1541. {
  1542. Ranges ranges;
  1543. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1544. EXPECT_FALSE(ret);
  1545. }
  1546. {
  1547. Ranges ranges;
  1548. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(2u, ranges.size());
  1551. EXPECT_EQ(1u, ranges[0].first);
  1552. EXPECT_EQ(10u, ranges[0].second);
  1553. EXPECT_EQ(100u, ranges[1].first);
  1554. EXPECT_EQ(-1, ranges[1].second);
  1555. }
  1556. {
  1557. Ranges ranges;
  1558. auto ret =
  1559. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(3u, ranges.size());
  1562. EXPECT_EQ(1u, ranges[0].first);
  1563. EXPECT_EQ(10u, ranges[0].second);
  1564. EXPECT_EQ(100u, ranges[1].first);
  1565. EXPECT_EQ(200u, ranges[1].second);
  1566. EXPECT_EQ(300u, ranges[2].first);
  1567. EXPECT_EQ(400u, ranges[2].second);
  1568. }
  1569. {
  1570. Ranges ranges;
  1571. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1572. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1573. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1574. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1575. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1576. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1577. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1578. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1579. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1580. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1581. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1582. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1583. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1584. EXPECT_TRUE(ranges.empty());
  1585. }
  1586. }
  1587. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1588. Request req;
  1589. req.set_header("Accept-Encoding", "gzip");
  1590. Response res;
  1591. res.set_header("Content-Type", "text/plain");
  1592. auto ret = detail::encoding_type(req, res);
  1593. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1594. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1595. #else
  1596. EXPECT_TRUE(ret == detail::EncodingType::None);
  1597. #endif
  1598. }
  1599. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1600. Request req;
  1601. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1602. Response res;
  1603. res.set_header("Content-Type", "text/plain");
  1604. auto ret = detail::encoding_type(req, res);
  1605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1606. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1607. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1608. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1609. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1610. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1611. #else
  1612. EXPECT_TRUE(ret == detail::EncodingType::None);
  1613. #endif
  1614. }
  1615. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1616. Request req;
  1617. req.set_header("Accept-Encoding",
  1618. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1619. Response res;
  1620. res.set_header("Content-Type", "text/plain");
  1621. auto ret = detail::encoding_type(req, res);
  1622. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1623. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1624. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1625. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1626. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1627. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1628. #else
  1629. EXPECT_TRUE(ret == detail::EncodingType::None);
  1630. #endif
  1631. }
  1632. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1633. // All supported encodings rejected with q=0 should return None
  1634. Request req;
  1635. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1636. Response res;
  1637. res.set_header("Content-Type", "text/plain");
  1638. auto ret = detail::encoding_type(req, res);
  1639. EXPECT_TRUE(ret == detail::EncodingType::None);
  1640. }
  1641. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1642. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1643. Request req;
  1644. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1645. Response res;
  1646. res.set_header("Content-Type", "text/plain");
  1647. auto ret = detail::encoding_type(req, res);
  1648. EXPECT_TRUE(ret == detail::EncodingType::None);
  1649. }
  1650. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1651. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1652. Request req;
  1653. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1654. Response res;
  1655. res.set_header("Content-Type", "text/plain");
  1656. auto ret = detail::encoding_type(req, res);
  1657. EXPECT_TRUE(ret == detail::EncodingType::None);
  1658. }
  1659. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1660. // RFC 7231: Accept-Encoding values are case-insensitive
  1661. Request req;
  1662. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1663. Response res;
  1664. res.set_header("Content-Type", "text/plain");
  1665. auto ret = detail::encoding_type(req, res);
  1666. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1667. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1668. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1669. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1670. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1671. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1672. #else
  1673. EXPECT_TRUE(ret == detail::EncodingType::None);
  1674. #endif
  1675. }
  1676. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1677. // q value should determine priority, not hardcoded order
  1678. Request req;
  1679. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1680. Response res;
  1681. res.set_header("Content-Type", "text/plain");
  1682. auto ret = detail::encoding_type(req, res);
  1683. // gzip has highest q=1.0, so it should be selected even though
  1684. // br and zstd are also supported
  1685. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1686. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1687. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1688. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1689. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1690. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1691. #else
  1692. EXPECT_TRUE(ret == detail::EncodingType::None);
  1693. #endif
  1694. }
  1695. TEST(BufferStreamTest, read) {
  1696. detail::BufferStream strm1;
  1697. Stream &strm = strm1;
  1698. EXPECT_EQ(5, strm.write("hello"));
  1699. char buf[512];
  1700. EXPECT_EQ(2, strm.read(buf, 2));
  1701. EXPECT_EQ('h', buf[0]);
  1702. EXPECT_EQ('e', buf[1]);
  1703. EXPECT_EQ(2, strm.read(buf, 2));
  1704. EXPECT_EQ('l', buf[0]);
  1705. EXPECT_EQ('l', buf[1]);
  1706. EXPECT_EQ(1, strm.read(buf, 1));
  1707. EXPECT_EQ('o', buf[0]);
  1708. EXPECT_EQ(0, strm.read(buf, 1));
  1709. }
  1710. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1711. auto host = "www.httpwatch.com";
  1712. auto ip = hosted_at(host);
  1713. EXPECT_EQ("23.96.13.243", ip);
  1714. std::vector<std::string> addrs;
  1715. hosted_at(host, addrs);
  1716. EXPECT_EQ(1u, addrs.size());
  1717. }
  1718. #if 0 // It depends on each test environment...
  1719. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1720. auto host = "www.youtube.com";
  1721. std::vector<std::string> addrs;
  1722. hosted_at(host, addrs);
  1723. EXPECT_EQ(20u, addrs.size());
  1724. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1725. EXPECT_TRUE(it != addrs.end());
  1726. }
  1727. #endif
  1728. class ChunkedEncodingTest : public ::testing::Test {
  1729. protected:
  1730. ChunkedEncodingTest()
  1731. : cli_(HOST, PORT)
  1732. #ifdef CPPHTTPLIB_SSL_ENABLED
  1733. ,
  1734. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1735. #endif
  1736. {
  1737. cli_.set_connection_timeout(2);
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. cli_.enable_server_certificate_verification(false);
  1740. #endif
  1741. }
  1742. virtual void SetUp() {
  1743. read_file("./image.jpg", image_data_);
  1744. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!", "text/plain");
  1746. });
  1747. svr_.Get(
  1748. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1749. res.set_chunked_content_provider(
  1750. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1751. size_t remaining = image_data_.size() - offset;
  1752. if (remaining == 0) {
  1753. sink.done();
  1754. } else {
  1755. constexpr size_t CHUNK_SIZE = 1024;
  1756. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1757. sink.write(&image_data_[offset], send_size);
  1758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1759. }
  1760. return true;
  1761. });
  1762. });
  1763. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1764. svr_.wait_until_ready();
  1765. }
  1766. virtual void TearDown() {
  1767. svr_.stop();
  1768. if (!request_threads_.empty()) {
  1769. std::this_thread::sleep_for(std::chrono::seconds(1));
  1770. for (auto &t : request_threads_) {
  1771. t.join();
  1772. }
  1773. }
  1774. t_.join();
  1775. }
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli_;
  1778. SSLServer svr_;
  1779. #else
  1780. Client cli_;
  1781. Server svr_;
  1782. #endif
  1783. thread t_;
  1784. std::vector<thread> request_threads_;
  1785. std::string image_data_;
  1786. };
  1787. TEST_F(ChunkedEncodingTest, NormalGet) {
  1788. auto res = cli_.Get("/chunked");
  1789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1790. std::string out;
  1791. read_file("./image.jpg", out);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ(out, res->body);
  1794. }
  1795. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1796. std::string body;
  1797. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1798. body.append(data, data_length);
  1799. return true;
  1800. });
  1801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1802. std::string out;
  1803. read_file("./image.jpg", out);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. EXPECT_EQ(out, body);
  1806. }
  1807. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1808. std::string body;
  1809. auto res = cli_.Get(
  1810. "/chunked",
  1811. [&](const Response &response) {
  1812. EXPECT_EQ(StatusCode::OK_200, response.status);
  1813. return true;
  1814. },
  1815. [&](const char *data, size_t data_length) {
  1816. body.append(data, data_length);
  1817. return true;
  1818. });
  1819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1820. std::string out;
  1821. read_file("./image.jpg", out);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ(out, body);
  1824. }
  1825. TEST(RangeTest, FromHTTPBin_Online) {
  1826. auto host = "httpbingo.org";
  1827. auto path = std::string{"/range/32"};
  1828. #ifdef CPPHTTPLIB_SSL_ENABLED
  1829. auto port = 443;
  1830. SSLClient cli(host, port);
  1831. #else
  1832. auto port = 80;
  1833. Client cli(host, port);
  1834. #endif
  1835. cli.set_connection_timeout(5);
  1836. {
  1837. auto res = cli.Get(path);
  1838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1839. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1840. EXPECT_EQ(StatusCode::OK_200, res->status);
  1841. }
  1842. {
  1843. Headers headers = {make_range_header({{1, -1}})};
  1844. auto res = cli.Get(path, headers);
  1845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1846. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1848. }
  1849. {
  1850. Headers headers = {make_range_header({{1, 10}})};
  1851. auto res = cli.Get(path, headers);
  1852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1853. EXPECT_EQ("bcdefghijk", res->body);
  1854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1855. }
  1856. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1857. // entire resource, while the original httpbin returned 200. Both are
  1858. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1859. {
  1860. Headers headers = {make_range_header({{0, 31}})};
  1861. auto res = cli.Get(path, headers);
  1862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1863. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1864. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1865. res->status == StatusCode::PartialContent_206);
  1866. }
  1867. {
  1868. Headers headers = {make_range_header({{0, -1}})};
  1869. auto res = cli.Get(path, headers);
  1870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1871. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1872. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1873. res->status == StatusCode::PartialContent_206);
  1874. }
  1875. // go-httpbin returns 206 with clamped range for over-range requests,
  1876. // while the original httpbin returned 416. Both behaviors are observed
  1877. // in real servers, so we only verify the request succeeds.
  1878. {
  1879. Headers headers = {make_range_header({{0, 32}})};
  1880. auto res = cli.Get(path, headers);
  1881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1882. }
  1883. }
  1884. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1885. auto host = "unresolvableaddress.local";
  1886. auto path = std::string{"/"};
  1887. #ifdef CPPHTTPLIB_SSL_ENABLED
  1888. auto port = 443;
  1889. SSLClient cli(host, port);
  1890. #else
  1891. auto port = 80;
  1892. Client cli(host, port);
  1893. #endif
  1894. cli.set_connection_timeout(1);
  1895. {
  1896. auto res = cli.Get(path);
  1897. ASSERT_FALSE(res);
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. }
  1901. #if defined(__linux__) && defined(__GLIBC__) && \
  1902. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1903. // Forward declaration: in split builds split.py strips `inline` and moves the
  1904. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1905. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1906. // against the symbol in both header-only and split builds.
  1907. namespace httplib {
  1908. namespace detail {
  1909. int getaddrinfo_with_timeout(const char *node, const char *service,
  1910. const struct addrinfo *hints,
  1911. struct addrinfo **res, time_t timeout_sec);
  1912. } // namespace detail
  1913. } // namespace httplib
  1914. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1915. //
  1916. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1917. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1918. // gai_suspend() call hits the connection timeout the function calls
  1919. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1920. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1921. // still alive and still references the now-destroyed stack frame.
  1922. //
  1923. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1924. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1925. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1926. // and runs them in a container.
  1927. namespace {
  1928. bool should_run_issue_2431_tests() {
  1929. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1930. return v && *v && std::string(v) != "0";
  1931. }
  1932. std::string unique_unresolvable_host(int n) {
  1933. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1934. // glibc still asks the configured nameserver — which is exactly the path
  1935. // we want to exercise. A unique label per call avoids the resolver cache.
  1936. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1937. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1938. std::to_string(n) + ".invalid";
  1939. }
  1940. } // namespace
  1941. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1942. if (!should_run_issue_2431_tests()) {
  1943. GTEST_SKIP()
  1944. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1945. }
  1946. for (int i = 0; i < 8; ++i) {
  1947. struct addrinfo hints;
  1948. memset(&hints, 0, sizeof(hints));
  1949. hints.ai_family = AF_UNSPEC;
  1950. hints.ai_socktype = SOCK_STREAM;
  1951. auto host = unique_unresolvable_host(i);
  1952. struct addrinfo *result = nullptr;
  1953. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1954. &result, /*timeout_sec=*/1);
  1955. if (rc == 0 && result) { freeaddrinfo(result); }
  1956. }
  1957. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1958. // stack region they still believe holds their gaicb.
  1959. std::this_thread::sleep_for(std::chrono::seconds(3));
  1960. }
  1961. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1962. if (!should_run_issue_2431_tests()) {
  1963. GTEST_SKIP()
  1964. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1965. }
  1966. std::atomic<bool> stop{false};
  1967. std::vector<std::thread> threads;
  1968. for (int t = 0; t < 8; ++t) {
  1969. threads.emplace_back([t, &stop] {
  1970. int i = 0;
  1971. while (!stop.load(std::memory_order_relaxed)) {
  1972. struct addrinfo hints;
  1973. memset(&hints, 0, sizeof(hints));
  1974. hints.ai_family = AF_UNSPEC;
  1975. hints.ai_socktype = SOCK_STREAM;
  1976. auto host = unique_unresolvable_host(t * 100000 + i++);
  1977. struct addrinfo *result = nullptr;
  1978. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1979. &result, /*timeout_sec=*/1);
  1980. if (rc == 0 && result) { freeaddrinfo(result); }
  1981. }
  1982. });
  1983. }
  1984. std::this_thread::sleep_for(std::chrono::seconds(8));
  1985. stop.store(true, std::memory_order_relaxed);
  1986. for (auto &th : threads) {
  1987. th.join();
  1988. }
  1989. std::this_thread::sleep_for(std::chrono::seconds(3));
  1990. }
  1991. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1992. if (!should_run_issue_2431_tests()) {
  1993. GTEST_SKIP()
  1994. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1995. }
  1996. std::atomic<bool> stop{false};
  1997. std::vector<std::thread> threads;
  1998. for (int t = 0; t < 8; ++t) {
  1999. threads.emplace_back([t, &stop] {
  2000. int i = 0;
  2001. while (!stop.load(std::memory_order_relaxed)) {
  2002. auto host = unique_unresolvable_host(t * 100000 + i++);
  2003. Client cli(host, 80);
  2004. cli.set_connection_timeout(1, 0);
  2005. cli.set_read_timeout(1, 0);
  2006. cli.set_write_timeout(1, 0);
  2007. (void)cli.Get("/");
  2008. }
  2009. });
  2010. }
  2011. std::this_thread::sleep_for(std::chrono::seconds(8));
  2012. stop.store(true, std::memory_order_relaxed);
  2013. for (auto &th : threads) {
  2014. th.join();
  2015. }
  2016. std::this_thread::sleep_for(std::chrono::seconds(3));
  2017. }
  2018. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2019. TEST(ConnectionErrorTest, InvalidHost) {
  2020. auto host = "-abcde.com";
  2021. #ifdef CPPHTTPLIB_SSL_ENABLED
  2022. auto port = 443;
  2023. SSLClient cli(host, port);
  2024. #else
  2025. auto port = 80;
  2026. Client cli(host, port);
  2027. #endif
  2028. cli.set_connection_timeout(std::chrono::seconds(2));
  2029. auto res = cli.Get("/");
  2030. ASSERT_TRUE(!res);
  2031. EXPECT_EQ(Error::Connection, res.error());
  2032. }
  2033. TEST(ConnectionErrorTest, InvalidHost2) {
  2034. auto host = "httpcan.org/";
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. SSLClient cli(host);
  2037. #else
  2038. Client cli(host);
  2039. #endif
  2040. cli.set_connection_timeout(std::chrono::seconds(2));
  2041. auto res = cli.Get("/");
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Connection, res.error());
  2044. }
  2045. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2046. auto host = "httpcan.org/";
  2047. #ifdef CPPHTTPLIB_SSL_ENABLED
  2048. SSLClient cli(host);
  2049. #else
  2050. Client cli(host);
  2051. #endif
  2052. cli.set_connection_timeout(std::chrono::seconds(2));
  2053. auto res = cli.Get("/");
  2054. ASSERT_TRUE(!res);
  2055. stringstream s;
  2056. s << "error code: " << res.error();
  2057. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2058. }
  2059. TEST(ConnectionErrorTest, InvalidPort) {
  2060. auto host = "localhost";
  2061. auto port = 44380;
  2062. #ifdef CPPHTTPLIB_SSL_ENABLED
  2063. SSLClient cli(host, port);
  2064. #else
  2065. Client cli(host, port);
  2066. #endif
  2067. cli.set_connection_timeout(std::chrono::seconds(2));
  2068. auto res = cli.Get("/");
  2069. ASSERT_TRUE(!res);
  2070. EXPECT_TRUE(Error::Connection == res.error() ||
  2071. Error::ConnectionTimeout == res.error());
  2072. }
  2073. TEST(ConnectionErrorTest, Timeout_Online) {
  2074. auto host = "google.com";
  2075. #ifdef CPPHTTPLIB_SSL_ENABLED
  2076. auto port = 44380;
  2077. SSLClient cli(host, port);
  2078. #else
  2079. auto port = 8080;
  2080. Client cli(host, port);
  2081. #endif
  2082. cli.set_connection_timeout(std::chrono::seconds(2));
  2083. // only probe one address type so that the error reason
  2084. // correlates to the timed-out IPv4, not the unsupported
  2085. // IPv6 connection attempt
  2086. cli.set_address_family(AF_INET);
  2087. auto res = cli.Get("/");
  2088. ASSERT_TRUE(!res);
  2089. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2090. }
  2091. TEST(CancelTest, NoCancel_Online) {
  2092. auto host = "httpbingo.org";
  2093. auto path = std::string{"/range/32"};
  2094. #ifdef CPPHTTPLIB_SSL_ENABLED
  2095. auto port = 443;
  2096. SSLClient cli(host, port);
  2097. #else
  2098. auto port = 80;
  2099. Client cli(host, port);
  2100. #endif
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2104. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. }
  2107. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2108. // Use /bytes with a large payload so that the DownloadProgress callback
  2109. // (which only fires for Content-Length responses) is invoked before the
  2110. // entire body is received, giving cancellation a chance to fire.
  2111. auto host = "httpbingo.org";
  2112. auto path = std::string{"/bytes/524288"};
  2113. #ifdef CPPHTTPLIB_SSL_ENABLED
  2114. auto port = 443;
  2115. SSLClient cli(host, port);
  2116. #else
  2117. auto port = 80;
  2118. Client cli(host, port);
  2119. #endif
  2120. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. ASSERT_TRUE(!res);
  2123. EXPECT_EQ(Error::Canceled, res.error());
  2124. }
  2125. TEST(CancelTest, WithCancelLargePayload_Online) {
  2126. auto host = "httpbingo.org";
  2127. auto path = std::string{"/bytes/524288"};
  2128. #ifdef CPPHTTPLIB_SSL_ENABLED
  2129. auto port = 443;
  2130. SSLClient cli(host, port);
  2131. #else
  2132. auto port = 80;
  2133. Client cli(host, port);
  2134. #endif
  2135. cli.set_connection_timeout(std::chrono::seconds(5));
  2136. uint32_t count = 0;
  2137. auto res =
  2138. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2139. ASSERT_TRUE(!res);
  2140. EXPECT_EQ(Error::Canceled, res.error());
  2141. }
  2142. TEST(CancelTest, NoCancelPost) {
  2143. Server svr;
  2144. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2145. res.set_content("Hello World!", "text/plain");
  2146. });
  2147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2148. auto se = detail::scope_exit([&] {
  2149. svr.stop();
  2150. thread.join();
  2151. ASSERT_FALSE(svr.is_running());
  2152. });
  2153. svr.wait_until_ready();
  2154. Client cli(HOST, PORT);
  2155. cli.set_connection_timeout(std::chrono::seconds(5));
  2156. auto res =
  2157. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2158. "application/json", [](uint64_t, uint64_t) { return true; });
  2159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2160. EXPECT_EQ("Hello World!", res->body);
  2161. EXPECT_EQ(StatusCode::OK_200, res->status);
  2162. }
  2163. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2164. Server svr;
  2165. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2166. res.set_content("Hello World!", "text/plain");
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. Client cli(HOST, PORT);
  2176. cli.set_connection_timeout(std::chrono::seconds(5));
  2177. auto res =
  2178. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2179. "application/json", [](uint64_t, uint64_t) { return false; });
  2180. ASSERT_TRUE(!res);
  2181. EXPECT_EQ(Error::Canceled, res.error());
  2182. }
  2183. TEST(CancelTest, WithCancelLargePayloadPost) {
  2184. Server svr;
  2185. svr.set_payload_max_length(200 * 1024 * 1024);
  2186. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2187. res.set_content(LARGE_DATA, "text/plain");
  2188. });
  2189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. Client cli(HOST, PORT);
  2197. cli.set_payload_max_length(200 * 1024 * 1024);
  2198. cli.set_connection_timeout(std::chrono::seconds(5));
  2199. auto res =
  2200. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2201. "application/json", [](uint64_t, uint64_t) { return false; });
  2202. ASSERT_TRUE(!res);
  2203. EXPECT_EQ(Error::Canceled, res.error());
  2204. }
  2205. TEST(CancelTest, NoCancelPut) {
  2206. Server svr;
  2207. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2208. res.set_content("Hello World!", "text/plain");
  2209. });
  2210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2211. auto se = detail::scope_exit([&] {
  2212. svr.stop();
  2213. thread.join();
  2214. ASSERT_FALSE(svr.is_running());
  2215. });
  2216. svr.wait_until_ready();
  2217. Client cli(HOST, PORT);
  2218. cli.set_connection_timeout(std::chrono::seconds(5));
  2219. auto res =
  2220. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2221. "application/json", [](uint64_t, uint64_t) { return true; });
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. EXPECT_EQ("Hello World!", res->body);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. }
  2226. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2227. Server svr;
  2228. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!", "text/plain");
  2230. });
  2231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2232. auto se = detail::scope_exit([&] {
  2233. svr.stop();
  2234. thread.join();
  2235. ASSERT_FALSE(svr.is_running());
  2236. });
  2237. svr.wait_until_ready();
  2238. Client cli(HOST, PORT);
  2239. cli.set_connection_timeout(std::chrono::seconds(5));
  2240. auto res =
  2241. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2242. "application/json", [](uint64_t, uint64_t) { return false; });
  2243. ASSERT_TRUE(!res);
  2244. EXPECT_EQ(Error::Canceled, res.error());
  2245. }
  2246. TEST(CancelTest, WithCancelLargePayloadPut) {
  2247. Server svr;
  2248. svr.set_payload_max_length(200 * 1024 * 1024);
  2249. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2250. res.set_content(LARGE_DATA, "text/plain");
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. Client cli(HOST, PORT);
  2260. cli.set_payload_max_length(200 * 1024 * 1024);
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. auto res =
  2263. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2264. "application/json", [](uint64_t, uint64_t) { return false; });
  2265. ASSERT_TRUE(!res);
  2266. EXPECT_EQ(Error::Canceled, res.error());
  2267. }
  2268. TEST(CancelTest, NoCancelPatch) {
  2269. Server svr;
  2270. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2271. res.set_content("Hello World!", "text/plain");
  2272. });
  2273. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2274. auto se = detail::scope_exit([&] {
  2275. svr.stop();
  2276. thread.join();
  2277. ASSERT_FALSE(svr.is_running());
  2278. });
  2279. svr.wait_until_ready();
  2280. Client cli(HOST, PORT);
  2281. cli.set_connection_timeout(std::chrono::seconds(5));
  2282. auto res =
  2283. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2284. "application/json", [](uint64_t, uint64_t) { return true; });
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("Hello World!", res->body);
  2287. EXPECT_EQ(StatusCode::OK_200, res->status);
  2288. }
  2289. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2290. Server svr;
  2291. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2295. auto se = detail::scope_exit([&] {
  2296. svr.stop();
  2297. thread.join();
  2298. ASSERT_FALSE(svr.is_running());
  2299. });
  2300. svr.wait_until_ready();
  2301. Client cli(HOST, PORT);
  2302. cli.set_connection_timeout(std::chrono::seconds(5));
  2303. auto res =
  2304. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2305. "application/json", [](uint64_t, uint64_t) { return false; });
  2306. ASSERT_TRUE(!res);
  2307. EXPECT_EQ(Error::Canceled, res.error());
  2308. }
  2309. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2310. Server svr;
  2311. svr.set_payload_max_length(200 * 1024 * 1024);
  2312. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2313. res.set_content(LARGE_DATA, "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. Client cli(HOST, PORT);
  2323. cli.set_payload_max_length(200 * 1024 * 1024);
  2324. cli.set_connection_timeout(std::chrono::seconds(5));
  2325. auto res =
  2326. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2327. "application/json", [](uint64_t, uint64_t) { return false; });
  2328. ASSERT_TRUE(!res);
  2329. EXPECT_EQ(Error::Canceled, res.error());
  2330. }
  2331. TEST(CancelTest, NoCancelDelete) {
  2332. Server svr;
  2333. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2334. res.set_content("Hello World!", "text/plain");
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. Client cli(HOST, PORT);
  2344. cli.set_connection_timeout(std::chrono::seconds(5));
  2345. auto res =
  2346. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2347. "application/json", [](uint64_t, uint64_t) { return true; });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. EXPECT_EQ("Hello World!", res->body);
  2350. EXPECT_EQ(StatusCode::OK_200, res->status);
  2351. }
  2352. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2353. Server svr;
  2354. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. Client cli(HOST, PORT);
  2365. cli.set_connection_timeout(std::chrono::seconds(5));
  2366. auto res =
  2367. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2368. "application/json", [](uint64_t, uint64_t) { return false; });
  2369. ASSERT_TRUE(!res);
  2370. EXPECT_EQ(Error::Canceled, res.error());
  2371. }
  2372. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2373. Server svr;
  2374. svr.set_payload_max_length(200 * 1024 * 1024);
  2375. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2376. res.set_content(LARGE_DATA, "text/plain");
  2377. });
  2378. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2379. auto se = detail::scope_exit([&] {
  2380. svr.stop();
  2381. thread.join();
  2382. ASSERT_FALSE(svr.is_running());
  2383. });
  2384. svr.wait_until_ready();
  2385. Client cli(HOST, PORT);
  2386. cli.set_payload_max_length(200 * 1024 * 1024);
  2387. cli.set_connection_timeout(std::chrono::seconds(5));
  2388. auto res =
  2389. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2390. "application/json", [](uint64_t, uint64_t) { return false; });
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::Canceled, res.error());
  2393. }
  2394. static std::string remove_whitespace(const std::string &input) {
  2395. std::string output;
  2396. output.reserve(input.size());
  2397. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2398. [](unsigned char c) { return !std::isspace(c); });
  2399. return output;
  2400. }
  2401. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/basic-auth/hello/world"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. {
  2412. auto res = cli.Get(path);
  2413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2414. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2415. }
  2416. {
  2417. auto res = cli.Get(
  2418. path, Headers{make_basic_authentication_header("hello", "world")});
  2419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2420. auto body = remove_whitespace(res->body);
  2421. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2422. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. }
  2425. {
  2426. cli.set_basic_auth("hello", "world");
  2427. auto res = cli.Get(path);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. auto body = remove_whitespace(res->body);
  2430. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2431. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2432. EXPECT_EQ(StatusCode::OK_200, res->status);
  2433. }
  2434. {
  2435. cli.set_basic_auth("hello", "bad");
  2436. auto res = cli.Get(path);
  2437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2438. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2439. }
  2440. {
  2441. cli.set_basic_auth("bad", "world");
  2442. auto res = cli.Get(path);
  2443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2444. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2445. }
  2446. }
  2447. #ifdef CPPHTTPLIB_SSL_ENABLED
  2448. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2449. auto host = "httpbingo.org";
  2450. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2451. auto paths = std::vector<std::string>{
  2452. "/digest-auth/auth/hello/world/MD5",
  2453. "/digest-auth/auth/hello/world/SHA-256",
  2454. };
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. {
  2458. auto res = cli.Get(unauth_path);
  2459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2460. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2461. }
  2462. {
  2463. cli.set_digest_auth("hello", "world");
  2464. for (const auto &path : paths) {
  2465. auto res = cli.Get(path.c_str());
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. auto body = remove_whitespace(res->body);
  2468. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2469. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. }
  2472. cli.set_digest_auth("hello", "bad");
  2473. for (const auto &path : paths) {
  2474. auto res = cli.Get(path.c_str());
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2477. }
  2478. }
  2479. }
  2480. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2481. // comma-separated list of challenges, and each challenge may itself carry a
  2482. // comma-separated auth-param list, so a server can legally offer Basic
  2483. // before Digest, either as two field lines or packed into one. Runs one 401
  2484. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2485. // value() joins them in receipt order) and checks that the retry carries a
  2486. // well-formed Digest Authorization header naming expected_realm.
  2487. static void
  2488. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2489. const std::string &expected_realm) {
  2490. std::atomic<int> hits{0};
  2491. Server svr;
  2492. svr.Get("/x", [&](const Request &req, Response &res) {
  2493. if (++hits == 1) {
  2494. res.status = StatusCode::Unauthorized_401;
  2495. for (const auto &challenge : challenges) {
  2496. res.set_header("WWW-Authenticate", challenge);
  2497. }
  2498. } else {
  2499. auto authorization = req.get_header_value("Authorization");
  2500. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2501. EXPECT_NE(std::string::npos,
  2502. authorization.find("realm=\"" + expected_realm + "\""));
  2503. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2504. res.set_content("ok", "text/plain");
  2505. }
  2506. });
  2507. auto port = svr.bind_to_any_port(HOST);
  2508. std::thread t([&]() { svr.listen_after_bind(); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. t.join();
  2512. });
  2513. svr.wait_until_ready();
  2514. Client cli(HOST, port);
  2515. cli.set_digest_auth("hello", "world");
  2516. auto res = cli.Get("/x");
  2517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2518. EXPECT_EQ(2, hits.load());
  2519. }
  2520. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2521. static const char *kDigestChallenge =
  2522. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2523. "algorithm=MD5";
  2524. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2525. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2526. "testrealm");
  2527. }
  2528. // Same challenge list with the schemes in the opposite order, to make sure
  2529. // the fix above didn't just special-case "Basic first".
  2530. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2531. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2532. "testrealm");
  2533. }
  2534. // A comma inside a quoted auth-param value must not be mistaken for the
  2535. // separator between two challenges (or two auth-params).
  2536. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2537. run_digest_challenge_list_test(
  2538. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2539. "algorithm=MD5"},
  2540. "test,realm");
  2541. }
  2542. #endif
  2543. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2544. auto host = "google.com";
  2545. auto another_host = "example.com";
  2546. auto wrong_ip = "0.0.0.0";
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLClient cli(host);
  2549. #else
  2550. Client cli(host);
  2551. #endif
  2552. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2553. auto res = cli.Get("/");
  2554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2555. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2556. }
  2557. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2558. auto host = "google.com";
  2559. auto wrong_ip = "0.0.0.0";
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. SSLClient cli(host);
  2562. #else
  2563. Client cli(host);
  2564. #endif
  2565. cli.set_hostname_addr_map({{host, wrong_ip}});
  2566. auto res = cli.Get("/");
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Connection, res.error());
  2569. }
  2570. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2571. // A mapped value that is not an IP literal must be resolved. "localhost"
  2572. // resolves from the hosts file, so this test needs no external DNS.
  2573. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2574. auto host = "target.invalid";
  2575. Server svr;
  2576. std::string received_host;
  2577. svr.Get("/hi", [&](const Request &req, Response &res) {
  2578. received_host = req.get_header_value("Host");
  2579. res.set_content("Hello World!", "text/plain");
  2580. });
  2581. auto port = svr.bind_to_any_port(HOST);
  2582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2583. auto se = detail::scope_exit([&] {
  2584. svr.stop();
  2585. thread.join();
  2586. ASSERT_FALSE(svr.is_running());
  2587. });
  2588. svr.wait_until_ready();
  2589. Client cli(host, port);
  2590. cli.set_hostname_addr_map({{host, HOST}});
  2591. auto res = cli.Get("/hi");
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. // The mapping only redirects the connection; the identity stays host_.
  2595. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2596. }
  2597. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2598. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2599. auto host = "target.invalid";
  2600. Server svr;
  2601. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2602. res.set_content("Hello World!", "text/plain");
  2603. });
  2604. auto port = svr.bind_to_any_port("127.0.0.1");
  2605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(host, port);
  2613. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2614. auto res = cli.Get("/hi");
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2619. // An empty mapped value must leave host_ as the connection target. Without
  2620. // that guard the empty value would become the host argument, getaddrinfo
  2621. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2622. // loopback - silently connecting somewhere the caller never asked for.
  2623. // The server listens on loopback, so such a fallback would succeed and is
  2624. // therefore observable as a failure of this test.
  2625. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. auto port = svr.bind_to_any_port(HOST);
  2631. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2632. auto se = detail::scope_exit([&] {
  2633. svr.stop();
  2634. thread.join();
  2635. ASSERT_FALSE(svr.is_running());
  2636. });
  2637. svr.wait_until_ready();
  2638. Client cli(blackhole, port);
  2639. cli.set_hostname_addr_map({{blackhole, ""}});
  2640. cli.set_connection_timeout(1);
  2641. auto res = cli.Get("/hi");
  2642. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2643. }
  2644. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2645. auto host = "httpbingo.org";
  2646. auto path = std::string{"/absolute-redirect/3"};
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. SSLClient cli(host);
  2649. #else
  2650. Client cli(host);
  2651. #endif
  2652. cli.set_follow_location(true);
  2653. auto res = cli.Get(path);
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. }
  2657. TEST(RedirectTest, Redirect_Online) {
  2658. auto host = "httpbingo.org";
  2659. auto path = std::string{"/redirect/3"};
  2660. #ifdef CPPHTTPLIB_SSL_ENABLED
  2661. SSLClient cli(host);
  2662. #else
  2663. Client cli(host);
  2664. #endif
  2665. cli.set_follow_location(true);
  2666. auto res = cli.Get(path);
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ(StatusCode::OK_200, res->status);
  2669. }
  2670. TEST(RelativeRedirectTest, Redirect_Online) {
  2671. auto host = "httpbingo.org";
  2672. auto path = std::string{"/relative-redirect/3"};
  2673. #ifdef CPPHTTPLIB_SSL_ENABLED
  2674. SSLClient cli(host);
  2675. #else
  2676. Client cli(host);
  2677. #endif
  2678. cli.set_follow_location(true);
  2679. auto res = cli.Get(path);
  2680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2681. EXPECT_EQ(StatusCode::OK_200, res->status);
  2682. }
  2683. TEST(TooManyRedirectTest, Redirect_Online) {
  2684. auto host = "httpbingo.org";
  2685. auto path = std::string{"/redirect/21"};
  2686. #ifdef CPPHTTPLIB_SSL_ENABLED
  2687. SSLClient cli(host);
  2688. #else
  2689. Client cli(host);
  2690. #endif
  2691. cli.set_follow_location(true);
  2692. auto res = cli.Get(path);
  2693. ASSERT_TRUE(!res);
  2694. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2695. }
  2696. #ifdef CPPHTTPLIB_SSL_ENABLED
  2697. TEST(YahooRedirectTest, Redirect_Online) {
  2698. Client cli("yahoo.com");
  2699. auto res = cli.Get("/");
  2700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2702. cli.set_follow_location(true);
  2703. res = cli.Get("/");
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::OK_200, res->status);
  2706. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2707. }
  2708. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2709. #define REDIR_HOST "httpbingo.org"
  2710. #define REDIR_PATH "/redirect-to"
  2711. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2712. SSLClient cli(REDIR_HOST);
  2713. cli.set_follow_location(true);
  2714. auto res =
  2715. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ(StatusCode::OK_200, res->status);
  2718. }
  2719. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2720. SSLClient cli(REDIR_HOST);
  2721. cli.set_follow_location(true);
  2722. Params params;
  2723. params.emplace("url", "http://example.com");
  2724. params.emplace("status_code", "302");
  2725. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2730. SSLClient cli(REDIR_HOST);
  2731. cli.set_follow_location(true);
  2732. Params params;
  2733. params.emplace("url", "http://example.com");
  2734. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2736. EXPECT_EQ(StatusCode::OK_200, res->status);
  2737. }
  2738. TEST(UrlWithSpace, Redirect_Online) {
  2739. SSLClient cli("edge.forgecdn.net");
  2740. cli.set_follow_location(true);
  2741. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2743. EXPECT_EQ(StatusCode::OK_200, res->status);
  2744. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2745. }
  2746. #endif
  2747. #if !defined(_WIN32) && !defined(_WIN64)
  2748. TEST(ReceiveSignals, Signal) {
  2749. auto setupSignalHandlers = []() {
  2750. struct sigaction act;
  2751. sigemptyset(&act.sa_mask);
  2752. act.sa_flags = SA_SIGINFO;
  2753. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2754. switch (sig) {
  2755. case SIGINT:
  2756. default: break;
  2757. }
  2758. };
  2759. ::sigaction(SIGINT, &act, nullptr);
  2760. };
  2761. Server svr;
  2762. int port = 0;
  2763. auto thread = std::thread([&]() {
  2764. setupSignalHandlers();
  2765. port = svr.bind_to_any_port(HOST);
  2766. svr.listen_after_bind();
  2767. });
  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. ASSERT_TRUE(svr.is_running());
  2775. pthread_kill(thread.native_handle(), SIGINT);
  2776. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2777. ASSERT_TRUE(svr.is_running());
  2778. }
  2779. #endif
  2780. TEST(RedirectToDifferentPort, Redirect) {
  2781. Server svr1;
  2782. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2783. res.set_content("Hello World!", "text/plain");
  2784. });
  2785. int svr1_port = 0;
  2786. auto thread1 = std::thread([&]() {
  2787. svr1_port = svr1.bind_to_any_port(HOST);
  2788. svr1.listen_after_bind();
  2789. });
  2790. Server svr2;
  2791. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2792. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2793. });
  2794. int svr2_port = 0;
  2795. auto thread2 = std::thread([&]() {
  2796. svr2_port = svr2.bind_to_any_port(HOST);
  2797. svr2.listen_after_bind();
  2798. });
  2799. auto se = detail::scope_exit([&] {
  2800. svr2.stop();
  2801. thread2.join();
  2802. svr1.stop();
  2803. thread1.join();
  2804. ASSERT_FALSE(svr2.is_running());
  2805. ASSERT_FALSE(svr1.is_running());
  2806. });
  2807. svr1.wait_until_ready();
  2808. svr2.wait_until_ready();
  2809. Client cli("localhost", svr2_port);
  2810. cli.set_follow_location(true);
  2811. auto res = cli.Get("/2");
  2812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2813. EXPECT_EQ(StatusCode::OK_200, res->status);
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. }
  2816. static void
  2817. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2818. Server svr1;
  2819. std::string captured_authorization;
  2820. svr1.Get("/target", [&](const Request &req, Response &res) {
  2821. captured_authorization = req.get_header_value("Authorization");
  2822. res.set_content("OK", "text/plain");
  2823. });
  2824. int svr1_port = 0;
  2825. auto thread1 = std::thread([&]() {
  2826. svr1_port = svr1.bind_to_any_port(HOST);
  2827. svr1.listen_after_bind();
  2828. });
  2829. Server svr2;
  2830. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2831. res.set_redirect(
  2832. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2833. });
  2834. int svr2_port = 0;
  2835. auto thread2 = std::thread([&]() {
  2836. svr2_port = svr2.bind_to_any_port(HOST);
  2837. svr2.listen_after_bind();
  2838. });
  2839. auto se = detail::scope_exit([&] {
  2840. svr2.stop();
  2841. thread2.join();
  2842. svr1.stop();
  2843. thread1.join();
  2844. ASSERT_FALSE(svr2.is_running());
  2845. ASSERT_FALSE(svr1.is_running());
  2846. });
  2847. svr1.wait_until_ready();
  2848. svr2.wait_until_ready();
  2849. Client cli("localhost", svr2_port);
  2850. cli.set_follow_location(true);
  2851. set_auth(cli);
  2852. auto res = cli.Get("/redir");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2856. EXPECT_TRUE(captured_authorization.empty());
  2857. }
  2858. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2859. TestDoNotForwardCredentialsOnRedirect(
  2860. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2861. }
  2862. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2863. TestDoNotForwardCredentialsOnRedirect(
  2864. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2865. }
  2866. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2867. Server svr1;
  2868. std::string captured_cookie;
  2869. bool target_hit = false;
  2870. svr1.Get("/target", [&](const Request &req, Response &res) {
  2871. captured_cookie = req.get_header_value("Cookie");
  2872. target_hit = true;
  2873. res.set_content("OK", "text/plain");
  2874. });
  2875. int svr1_port = 0;
  2876. auto thread1 = std::thread([&]() {
  2877. svr1_port = svr1.bind_to_any_port(HOST);
  2878. svr1.listen_after_bind();
  2879. });
  2880. Server svr2;
  2881. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2882. res.set_redirect(
  2883. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2884. });
  2885. int svr2_port = 0;
  2886. auto thread2 = std::thread([&]() {
  2887. svr2_port = svr2.bind_to_any_port(HOST);
  2888. svr2.listen_after_bind();
  2889. });
  2890. auto se = detail::scope_exit([&] {
  2891. svr2.stop();
  2892. thread2.join();
  2893. svr1.stop();
  2894. thread1.join();
  2895. ASSERT_FALSE(svr2.is_running());
  2896. ASSERT_FALSE(svr1.is_running());
  2897. });
  2898. svr1.wait_until_ready();
  2899. svr2.wait_until_ready();
  2900. Client cli("localhost", svr2_port);
  2901. cli.set_follow_location(true);
  2902. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2903. auto res = cli.Get("/redir", headers);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_TRUE(target_hit);
  2907. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2908. EXPECT_TRUE(captured_cookie.empty());
  2909. }
  2910. TEST(RedirectToSamePort, ForwardCookie) {
  2911. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2912. // header so that ordinary session flows keep working.
  2913. Server svr;
  2914. std::string captured_cookie;
  2915. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2916. res.set_redirect("/target", 302);
  2917. });
  2918. svr.Get("/target", [&](const Request &req, Response &res) {
  2919. captured_cookie = req.get_header_value("Cookie");
  2920. res.set_content("OK", "text/plain");
  2921. });
  2922. auto port = svr.bind_to_any_port(HOST);
  2923. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli(HOST, port);
  2931. cli.set_follow_location(true);
  2932. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2933. auto res = cli.Get("/redir", headers);
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2937. }
  2938. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2939. Server svr;
  2940. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2941. // Port number that overflows int — should not crash
  2942. res.set_redirect("http://localhost:99999999999999999999/target");
  2943. });
  2944. auto port = svr.bind_to_any_port(HOST);
  2945. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2946. auto se = detail::scope_exit([&] {
  2947. svr.stop();
  2948. thread.join();
  2949. ASSERT_FALSE(svr.is_running());
  2950. });
  2951. svr.wait_until_ready();
  2952. Client cli(HOST, port);
  2953. cli.set_follow_location(true);
  2954. auto res = cli.Get("/redir");
  2955. // Should fail gracefully, not crash (no valid response due to bad port)
  2956. EXPECT_FALSE(res);
  2957. }
  2958. TEST(RedirectFromPageWithContent, Redirect) {
  2959. Server svr;
  2960. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("___", "text/plain");
  2962. res.set_redirect("/2");
  2963. });
  2964. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2965. res.set_content("Hello World!", "text/plain");
  2966. });
  2967. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2968. auto se = detail::scope_exit([&] {
  2969. svr.stop();
  2970. th.join();
  2971. ASSERT_FALSE(svr.is_running());
  2972. });
  2973. svr.wait_until_ready();
  2974. {
  2975. Client cli("localhost", PORT);
  2976. cli.set_follow_location(true);
  2977. std::string body;
  2978. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2979. body.append(data, data_length);
  2980. return true;
  2981. });
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("Hello World!", body);
  2985. }
  2986. {
  2987. Client cli("localhost", PORT);
  2988. std::string body;
  2989. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2990. body.append(data, data_length);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2994. EXPECT_EQ(StatusCode::Found_302, res->status);
  2995. EXPECT_EQ("___", body);
  2996. }
  2997. }
  2998. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2999. Server svr;
  3000. auto port_str = std::to_string(PORT);
  3001. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3002. auto expected_host = "[::1]:" + port_str;
  3003. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3004. res.set_content("___", "text/plain");
  3005. // res.set_redirect("/2");
  3006. res.set_redirect(redirect_url);
  3007. });
  3008. svr.Get("/2", [&](const Request &req, Response &res) {
  3009. auto host_header = req.headers.find("Host");
  3010. ASSERT_TRUE(host_header != req.headers.end());
  3011. EXPECT_EQ(expected_host, host_header->second);
  3012. res.set_content("Hello World!", "text/plain");
  3013. });
  3014. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3015. auto se = detail::scope_exit([&] {
  3016. svr.stop();
  3017. th.join();
  3018. ASSERT_FALSE(svr.is_running());
  3019. });
  3020. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3021. // actually starts anything, so the condition !svr.is_running() will
  3022. // always remain true, and the loop never stops.
  3023. // This basically counts how many milliseconds have passed since the
  3024. // call to svr.listen(), and if after 5 seconds nothing started yet
  3025. // aborts the test.
  3026. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3027. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3028. ASSERT_LT(milliseconds, 5000U);
  3029. }
  3030. {
  3031. Client cli("::1", PORT);
  3032. cli.set_follow_location(true);
  3033. std::string body;
  3034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3035. body.append(data, data_length);
  3036. return true;
  3037. });
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::OK_200, res->status);
  3040. EXPECT_EQ("Hello World!", body);
  3041. }
  3042. {
  3043. Client cli("::1", PORT);
  3044. std::string body;
  3045. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3046. body.append(data, data_length);
  3047. return true;
  3048. });
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::Found_302, res->status);
  3051. EXPECT_EQ("___", body);
  3052. }
  3053. }
  3054. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3055. Server svr;
  3056. svr.Get("/foo", [](const Request &req, Response &res) {
  3057. auto a = req.params.find("a");
  3058. if (a != req.params.end()) {
  3059. res.set_content((*a).second, "text/plain");
  3060. res.status = StatusCode::OK_200;
  3061. } else {
  3062. res.status = StatusCode::BadRequest_400;
  3063. }
  3064. });
  3065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. {
  3073. Client cli(HOST, PORT);
  3074. cli.set_path_encode(false);
  3075. auto res = cli.Get("/foo?a=explicitly+encoded");
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. // This expects it back with a space, as the `+` won't have been
  3079. // url-encoded, and server-side the params get decoded turning `+`
  3080. // into spaces.
  3081. EXPECT_EQ("explicitly encoded", res->body);
  3082. }
  3083. }
  3084. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3085. // When path encoding is disabled the client must transmit the supplied
  3086. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3087. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3088. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3089. // than a space (0x20). Assert on the raw wire target to catch this.
  3090. Server svr;
  3091. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3092. svr.Get("/foo", [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(expected_target, req.target);
  3094. res.status = StatusCode::OK_200;
  3095. });
  3096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. thread.join();
  3100. ASSERT_FALSE(svr.is_running());
  3101. });
  3102. svr.wait_until_ready();
  3103. {
  3104. Client cli(HOST, PORT);
  3105. cli.set_path_encode(false);
  3106. auto res = cli.Get(expected_target.c_str());
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. }
  3110. }
  3111. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3112. // `open_stream()` used to skip the path encoding that the buffered send
  3113. // path applies, so the same `path` produced different bytes in the request
  3114. // line depending on which API was used. Assert the two agree.
  3115. Server svr;
  3116. std::string target;
  3117. svr.Get(".*", [&](const Request &req, Response &res) {
  3118. target = req.target;
  3119. res.status = StatusCode::OK_200;
  3120. });
  3121. auto port = svr.bind_to_any_port(HOST);
  3122. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. struct {
  3130. const char *path;
  3131. const char *expected;
  3132. } cases[] = {
  3133. {"/a b?x=1", "/a%20b?x=1"},
  3134. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3135. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3136. };
  3137. for (const auto &c : cases) {
  3138. Client cli(HOST, port);
  3139. target.clear();
  3140. auto res = cli.Get(c.path);
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3143. auto buffered_target = target;
  3144. target.clear();
  3145. auto handle = cli.open_stream("GET", c.path);
  3146. EXPECT_TRUE(handle.is_valid())
  3147. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3148. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3149. }
  3150. }
  3151. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3152. // The `set_path_encode(false)` contract — transmit the supplied target
  3153. // verbatim — must hold for the streaming API too.
  3154. Server svr;
  3155. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3156. std::string target;
  3157. svr.Get("/foo", [&](const Request &req, Response &res) {
  3158. target = req.target;
  3159. res.status = StatusCode::OK_200;
  3160. });
  3161. auto port = svr.bind_to_any_port(HOST);
  3162. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. thread.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. {
  3170. Client cli(HOST, port);
  3171. cli.set_path_encode(false);
  3172. auto handle = cli.open_stream("GET", expected_target);
  3173. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3174. EXPECT_EQ(expected_target, target);
  3175. }
  3176. }
  3177. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3178. // With path encoding enabled a CR/LF in the target is percent-encoded
  3179. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3180. // write_request_line still backstops `set_path_encode(false)`, which is
  3181. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3182. Server svr;
  3183. // Captured before routing: the decoded path contains a newline, which a
  3184. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3185. std::string target;
  3186. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3187. target = req.target;
  3188. res.status = StatusCode::OK_200;
  3189. return Server::HandlerResponse::Handled;
  3190. });
  3191. auto port = svr.bind_to_any_port(HOST);
  3192. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3193. auto se = detail::scope_exit([&] {
  3194. svr.stop();
  3195. thread.join();
  3196. ASSERT_FALSE(svr.is_running());
  3197. });
  3198. svr.wait_until_ready();
  3199. {
  3200. Client cli(HOST, port);
  3201. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3202. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3203. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3204. }
  3205. }
  3206. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3207. // Nothing may reach the wire: a raw CR/LF target would split the request
  3208. // line and inject headers.
  3209. Server svr;
  3210. // Pre-routing so that "not called" means nothing reached the server at all,
  3211. // rather than merely failing to match a handler pattern.
  3212. auto handler_called = false;
  3213. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3214. handler_called = true;
  3215. res.status = StatusCode::OK_200;
  3216. return Server::HandlerResponse::Handled;
  3217. });
  3218. auto port = svr.bind_to_any_port(HOST);
  3219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3220. auto se = detail::scope_exit([&] {
  3221. svr.stop();
  3222. thread.join();
  3223. ASSERT_FALSE(svr.is_running());
  3224. });
  3225. svr.wait_until_ready();
  3226. {
  3227. Client cli(HOST, port);
  3228. cli.set_path_encode(false);
  3229. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3230. EXPECT_FALSE(handle.is_valid());
  3231. EXPECT_EQ(Error::Write, handle.error);
  3232. EXPECT_FALSE(handler_called);
  3233. }
  3234. }
  3235. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3236. // Which of the two branches runs is decided by whether the query component
  3237. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3238. // an empty query and must still fall back to building one from
  3239. // `req.params`, while a non-empty query must win over `req.params`.
  3240. Server svr;
  3241. std::string target;
  3242. svr.Get("/foo", [&](const Request &req, Response &res) {
  3243. target = req.target;
  3244. res.status = StatusCode::OK_200;
  3245. });
  3246. auto port = svr.bind_to_any_port(HOST);
  3247. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3248. auto se = detail::scope_exit([&] {
  3249. svr.stop();
  3250. thread.join();
  3251. ASSERT_FALSE(svr.is_running());
  3252. });
  3253. svr.wait_until_ready();
  3254. {
  3255. // Trailing `?` -> empty query component -> `req.params` is used.
  3256. Client cli(HOST, port);
  3257. Request req;
  3258. req.method = "GET";
  3259. req.path = "/foo?";
  3260. req.params.emplace("a", "1");
  3261. target.clear();
  3262. auto res = cli.send(req);
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ("/foo?a=1", target);
  3265. }
  3266. {
  3267. // Non-empty query in `req.path` -> `req.params` is not appended.
  3268. Client cli(HOST, port);
  3269. Request req;
  3270. req.method = "GET";
  3271. req.path = "/foo?b=2";
  3272. req.params.emplace("a", "1");
  3273. target.clear();
  3274. auto res = cli.send(req);
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ("/foo?b=2", target);
  3277. }
  3278. }
  3279. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3280. Server svr;
  3281. svr.Get("/", [](const Request &req, Response &) {
  3282. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3283. });
  3284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. {
  3292. Client cli(HOST, PORT);
  3293. cli.set_path_encode(false);
  3294. auto res = cli.Get("/?something=%0A");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. }
  3299. TEST(BindServerTest, BindDualStack) {
  3300. Server svr;
  3301. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content("Hello World!", "text/plain");
  3303. });
  3304. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. {
  3312. Client cli("127.0.0.1", PORT);
  3313. auto res = cli.Get("/1");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ("Hello World!", res->body);
  3317. }
  3318. {
  3319. Client cli("::1", PORT);
  3320. auto res = cli.Get("/1");
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. EXPECT_EQ(StatusCode::OK_200, res->status);
  3323. EXPECT_EQ("Hello World!", res->body);
  3324. }
  3325. }
  3326. TEST(BindServerTest, BindAndListenSeparately) {
  3327. Server svr;
  3328. int port = svr.bind_to_any_port("0.0.0.0");
  3329. ASSERT_TRUE(svr.is_valid());
  3330. ASSERT_TRUE(port > 0);
  3331. svr.stop();
  3332. }
  3333. // Reports whether anything is still listening on a loopback port. A plain
  3334. // connect() is used instead of a Client request because a socket left bound by
  3335. // mistake accepts the connection into its backlog and never answers, which
  3336. // would hang the test instead of failing it.
  3337. static bool is_loopback_port_accepting(int port) {
  3338. sockaddr_in addr{};
  3339. addr.sin_family = AF_INET;
  3340. addr.sin_port = htons(static_cast<uint16_t>(port));
  3341. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3342. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3343. EXPECT_NE(sock, INVALID_SOCKET);
  3344. if (sock == INVALID_SOCKET) { return false; }
  3345. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3346. static_cast<socklen_t>(sizeof(addr)));
  3347. detail::close_socket(sock);
  3348. return ret == 0;
  3349. }
  3350. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3351. Server svr;
  3352. auto port = svr.bind_to_any_port("127.0.0.1");
  3353. ASSERT_TRUE(port > 0);
  3354. svr.stop();
  3355. // bind_to_any_port() already called listen(2), so until stop() closed the
  3356. // descriptor the port kept accepting connections into the backlog. ASSERT
  3357. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3358. // below blocks forever in the accept loop.
  3359. ASSERT_FALSE(is_loopback_port_accepting(port));
  3360. // Nothing is left to accept on, so listen_after_bind() must report failure
  3361. // instead of returning success without ever serving.
  3362. EXPECT_FALSE(svr.listen_after_bind());
  3363. // The failed listen marks the server decommissioned, so a waiter returns
  3364. // instead of spinning forever.
  3365. svr.wait_until_ready();
  3366. }
  3367. #ifdef CPPHTTPLIB_SSL_ENABLED
  3368. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3370. CLIENT_CA_CERT_DIR);
  3371. int port = svr.bind_to_any_port("0.0.0.0");
  3372. ASSERT_TRUE(svr.is_valid());
  3373. ASSERT_TRUE(port > 0);
  3374. svr.stop();
  3375. }
  3376. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3377. // or a rejected CustomRoute() registration would not stop the server binding.
  3378. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3380. CLIENT_CA_CERT_DIR);
  3381. ASSERT_TRUE(svr.is_valid());
  3382. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3383. EXPECT_FALSE(svr.is_valid());
  3384. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3385. }
  3386. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3387. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3388. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3389. int port = svr.bind_to_any_port("0.0.0.0");
  3390. ASSERT_TRUE(svr.is_valid());
  3391. ASSERT_TRUE(port > 0);
  3392. svr.stop();
  3393. }
  3394. TEST(BindServerTest, UpdateCertsPem) {
  3395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3396. int port = svr.bind_to_any_port("0.0.0.0");
  3397. ASSERT_TRUE(svr.is_valid());
  3398. ASSERT_TRUE(port > 0);
  3399. // Read PEM files
  3400. std::string cert_pem, key_pem, ca_pem;
  3401. read_file(SERVER_CERT_FILE, cert_pem);
  3402. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3403. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3404. // Update server certificates using PEM API
  3405. ASSERT_TRUE(
  3406. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3407. ASSERT_TRUE(svr.is_valid());
  3408. svr.stop();
  3409. }
  3410. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3411. // Start server with client CA (enables client auth)
  3412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3413. ASSERT_TRUE(svr.is_valid());
  3414. bool handler_called = false;
  3415. svr.Get("/test", [&](const Request &req, Response &res) {
  3416. handler_called = true;
  3417. // Verify client certificate is present
  3418. auto cert = req.peer_cert();
  3419. EXPECT_TRUE(static_cast<bool>(cert));
  3420. res.set_content("ok", "text/plain");
  3421. });
  3422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3423. auto se = detail::scope_exit([&] {
  3424. svr.stop();
  3425. t.join();
  3426. ASSERT_FALSE(svr.is_running());
  3427. });
  3428. svr.wait_until_ready();
  3429. // Read PEM files
  3430. std::string cert_pem, key_pem, ca_pem;
  3431. read_file(SERVER_CERT_FILE, cert_pem);
  3432. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3433. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3434. // Update server certificates and client CA using PEM API while server running
  3435. ASSERT_TRUE(
  3436. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3437. // Connect with client certificate
  3438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3439. cli.enable_server_certificate_verification(false);
  3440. cli.set_connection_timeout(30);
  3441. auto res = cli.Get("/test");
  3442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3443. ASSERT_EQ(StatusCode::OK_200, res->status);
  3444. ASSERT_TRUE(handler_called);
  3445. EXPECT_EQ("ok", res->body);
  3446. }
  3447. #endif
  3448. TEST(ErrorHandlerTest, ContentLength) {
  3449. Server svr;
  3450. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3451. res.status = StatusCode::OK_200;
  3452. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3453. "text/html"); // <= Content-Length still 13
  3454. });
  3455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3456. res.set_content("Hello World!\n", "text/plain");
  3457. res.status = 524;
  3458. });
  3459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. {
  3467. Client cli(HOST, PORT);
  3468. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3472. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3473. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3474. }
  3475. }
  3476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3477. TEST(ExceptionTest, WithoutExceptionHandler) {
  3478. Server svr;
  3479. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3480. throw std::runtime_error("exception...");
  3481. });
  3482. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3483. throw std::runtime_error("exception\r\n...");
  3484. });
  3485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. listen_thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. svr.wait_until_ready();
  3492. Client cli("localhost", PORT);
  3493. {
  3494. auto res = cli.Get("/exception");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3497. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3498. }
  3499. {
  3500. auto res = cli.Get("/unknown");
  3501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3503. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3504. }
  3505. }
  3506. TEST(ExceptionTest, WithExceptionHandler) {
  3507. Server svr;
  3508. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3509. std::exception_ptr ep) {
  3510. EXPECT_FALSE(ep == nullptr);
  3511. try {
  3512. std::rethrow_exception(ep);
  3513. } catch (std::exception &e) {
  3514. EXPECT_EQ("abc", std::string(e.what()));
  3515. } catch (...) {}
  3516. res.status = StatusCode::InternalServerError_500;
  3517. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3518. "text/html"); // <= Content-Length still 13 at this point
  3519. });
  3520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3521. res.set_content("Hello World!\n", "text/plain");
  3522. throw std::runtime_error("abc");
  3523. });
  3524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3525. auto se = detail::scope_exit([&] {
  3526. svr.stop();
  3527. thread.join();
  3528. ASSERT_FALSE(svr.is_running());
  3529. });
  3530. svr.wait_until_ready();
  3531. for (size_t i = 0; i < 10; i++) {
  3532. Client cli(HOST, PORT);
  3533. for (size_t j = 0; j < 100; j++) {
  3534. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3539. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3540. }
  3541. cli.set_keep_alive(true);
  3542. for (size_t j = 0; j < 100; j++) {
  3543. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3545. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3546. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3547. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3548. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3549. }
  3550. }
  3551. }
  3552. TEST(ExceptionTest, AndErrorHandler) {
  3553. Server svr;
  3554. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3555. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3556. });
  3557. svr.set_exception_handler(
  3558. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3559. EXPECT_FALSE(ep == nullptr);
  3560. try {
  3561. std::rethrow_exception(ep);
  3562. } catch (std::exception &e) {
  3563. res.set_content(e.what(), "text/html");
  3564. } catch (...) {}
  3565. res.status = StatusCode::InternalServerError_500;
  3566. });
  3567. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3568. throw std::runtime_error("EXCEPTION");
  3569. });
  3570. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3571. res.set_content("ERROR", "text/html");
  3572. res.status = StatusCode::InternalServerError_500;
  3573. });
  3574. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. thread.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. Client cli(HOST, PORT);
  3582. {
  3583. auto res = cli.Get("/exception");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3586. EXPECT_EQ("EXCEPTION", res->body);
  3587. }
  3588. {
  3589. auto res = cli.Get("/error");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3592. EXPECT_EQ("ERROR", res->body);
  3593. }
  3594. {
  3595. auto res = cli.Get("/invalid");
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3598. EXPECT_EQ("NOT_FOUND", res->body);
  3599. }
  3600. }
  3601. #endif
  3602. TEST(NoContentTest, ContentLength) {
  3603. Server svr;
  3604. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3605. res.status = StatusCode::NoContent_204;
  3606. });
  3607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3608. auto se = detail::scope_exit([&] {
  3609. svr.stop();
  3610. thread.join();
  3611. ASSERT_FALSE(svr.is_running());
  3612. });
  3613. svr.wait_until_ready();
  3614. {
  3615. Client cli(HOST, PORT);
  3616. auto res = cli.Get("/hi");
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3620. }
  3621. }
  3622. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3623. #ifdef CPPHTTPLIB_SSL_ENABLED
  3624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3625. ASSERT_TRUE(svr.is_valid());
  3626. #else
  3627. Server svr;
  3628. #endif
  3629. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3630. if (req.path == "/routing_handler") {
  3631. res.set_header("PRE_ROUTING", "on");
  3632. res.set_content("Routing Handler", "text/plain");
  3633. return httplib::Server::HandlerResponse::Handled;
  3634. }
  3635. return httplib::Server::HandlerResponse::Unhandled;
  3636. });
  3637. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3638. res.set_content("Error", "text/html");
  3639. });
  3640. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3641. if (req.path == "/routing_handler") {
  3642. res.set_header("POST_ROUTING", "on");
  3643. }
  3644. });
  3645. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3646. res.set_content("Hello World!\n", "text/plain");
  3647. });
  3648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. {
  3656. #ifdef CPPHTTPLIB_SSL_ENABLED
  3657. SSLClient cli(HOST, PORT);
  3658. cli.enable_server_certificate_verification(false);
  3659. #else
  3660. Client cli(HOST, PORT);
  3661. #endif
  3662. auto res = cli.Get("/routing_handler");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("Routing Handler", res->body);
  3666. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3667. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3668. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3669. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3670. }
  3671. {
  3672. #ifdef CPPHTTPLIB_SSL_ENABLED
  3673. SSLClient cli(HOST, PORT);
  3674. cli.enable_server_certificate_verification(false);
  3675. #else
  3676. Client cli(HOST, PORT);
  3677. #endif
  3678. auto res = cli.Get("/hi");
  3679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3680. EXPECT_EQ(StatusCode::OK_200, res->status);
  3681. EXPECT_EQ("Hello World!\n", res->body);
  3682. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3683. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3684. }
  3685. {
  3686. #ifdef CPPHTTPLIB_SSL_ENABLED
  3687. SSLClient cli(HOST, PORT);
  3688. cli.enable_server_certificate_verification(false);
  3689. #else
  3690. Client cli(HOST, PORT);
  3691. #endif
  3692. auto res = cli.Get("/aaa");
  3693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3694. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3695. EXPECT_EQ("Error", res->body);
  3696. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3697. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3698. }
  3699. }
  3700. TEST(RequestHandlerTest, PreRequestHandler) {
  3701. auto route_path = "/user/:user";
  3702. Server svr;
  3703. svr.Get("/hi", [](const Request &, Response &res) {
  3704. res.set_content("hi", "text/plain");
  3705. });
  3706. svr.Get(route_path, [](const Request &req, Response &res) {
  3707. res.set_content(req.path_params.at("user"), "text/plain");
  3708. });
  3709. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3710. if (req.matched_route == route_path) {
  3711. auto user = req.path_params.at("user");
  3712. if (user != "john") {
  3713. res.status = StatusCode::Forbidden_403;
  3714. res.set_content("error", "text/html");
  3715. return Server::HandlerResponse::Handled;
  3716. }
  3717. }
  3718. return Server::HandlerResponse::Unhandled;
  3719. });
  3720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3721. auto se = detail::scope_exit([&] {
  3722. svr.stop();
  3723. thread.join();
  3724. ASSERT_FALSE(svr.is_running());
  3725. });
  3726. svr.wait_until_ready();
  3727. Client cli(HOST, PORT);
  3728. {
  3729. auto res = cli.Get("/hi");
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. EXPECT_EQ("hi", res->body);
  3733. }
  3734. {
  3735. auto res = cli.Get("/user/john");
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. EXPECT_EQ("john", res->body);
  3739. }
  3740. {
  3741. auto res = cli.Get("/user/invalid-user");
  3742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3743. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3744. EXPECT_EQ("error", res->body);
  3745. }
  3746. }
  3747. // The pre-request handler must run before the request body is read, so a
  3748. // rejected request never forces the server to buffer a (potentially large)
  3749. // body. Here the posted body is larger than the payload limit: if the body
  3750. // were read first the server would answer 413, but because the pre-request
  3751. // handler runs first it answers 403 and the body is never read.
  3752. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3753. Server svr;
  3754. svr.set_payload_max_length(8);
  3755. auto handler_ran = false;
  3756. svr.Post("/reject", [&](const Request &req, Response &res) {
  3757. handler_ran = true;
  3758. res.set_content(req.body, "text/plain");
  3759. });
  3760. svr.Post("/accept", [](const Request &req, Response &res) {
  3761. res.set_content(req.body, "text/plain");
  3762. });
  3763. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3764. if (req.matched_route == "/reject") {
  3765. res.status = StatusCode::Forbidden_403;
  3766. res.set_content("denied", "text/plain");
  3767. return Server::HandlerResponse::Handled;
  3768. }
  3769. return Server::HandlerResponse::Unhandled;
  3770. });
  3771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3772. auto se = detail::scope_exit([&] {
  3773. svr.stop();
  3774. thread.join();
  3775. ASSERT_FALSE(svr.is_running());
  3776. });
  3777. svr.wait_until_ready();
  3778. Client cli(HOST, PORT);
  3779. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3780. // rejects with 403 before the body is read, so 413 is never reached.
  3781. {
  3782. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3784. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3785. EXPECT_EQ("denied", res->body);
  3786. EXPECT_FALSE(handler_ran);
  3787. }
  3788. // An approved route still reads the body and enforces the payload limit.
  3789. {
  3790. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3792. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3793. }
  3794. }
  3795. TEST(UserDataTest, BasicOperations) {
  3796. httplib::UserData ud;
  3797. // Initially empty
  3798. EXPECT_FALSE(ud.has("key"));
  3799. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3800. // set and get
  3801. ud.set("key", 42);
  3802. EXPECT_TRUE(ud.has("key"));
  3803. auto *p = ud.get<int>("key");
  3804. ASSERT_NE(nullptr, p);
  3805. EXPECT_EQ(42, *p);
  3806. // Type mismatch → nullptr
  3807. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3808. // Overwrite with different type
  3809. ud.set("key", std::string("hello"));
  3810. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3811. auto *s = ud.get<std::string>("key");
  3812. ASSERT_NE(nullptr, s);
  3813. EXPECT_EQ("hello", *s);
  3814. // erase
  3815. ud.erase("key");
  3816. EXPECT_FALSE(ud.has("key"));
  3817. // clear
  3818. ud.set("a", 1);
  3819. ud.set("b", 2);
  3820. ud.clear();
  3821. EXPECT_FALSE(ud.has("a"));
  3822. EXPECT_FALSE(ud.has("b"));
  3823. }
  3824. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3825. struct AuthCtx {
  3826. std::string user_id;
  3827. };
  3828. Server svr;
  3829. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3830. res.user_data.set("auth", AuthCtx{"alice"});
  3831. return Server::HandlerResponse::Unhandled;
  3832. });
  3833. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3834. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3835. ASSERT_NE(nullptr, ctx);
  3836. res.set_content("Hello " + ctx->user_id, "text/plain");
  3837. });
  3838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3839. auto se = detail::scope_exit([&] {
  3840. svr.stop();
  3841. thread.join();
  3842. ASSERT_FALSE(svr.is_running());
  3843. });
  3844. svr.wait_until_ready();
  3845. Client cli(HOST, PORT);
  3846. auto res = cli.Get("/me");
  3847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3848. EXPECT_EQ(StatusCode::OK_200, res->status);
  3849. EXPECT_EQ("Hello alice", res->body);
  3850. }
  3851. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3852. struct RoleCtx {
  3853. std::string role;
  3854. };
  3855. Server svr;
  3856. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3857. res.user_data.set("role", RoleCtx{"admin"});
  3858. return Server::HandlerResponse::Unhandled;
  3859. });
  3860. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3861. auto *ctx = res.user_data.get<RoleCtx>("role");
  3862. ASSERT_NE(nullptr, ctx);
  3863. res.set_content(ctx->role, "text/plain");
  3864. });
  3865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3866. auto se = detail::scope_exit([&] {
  3867. svr.stop();
  3868. thread.join();
  3869. ASSERT_FALSE(svr.is_running());
  3870. });
  3871. svr.wait_until_ready();
  3872. Client cli(HOST, PORT);
  3873. auto res = cli.Get("/role");
  3874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3875. EXPECT_EQ(StatusCode::OK_200, res->status);
  3876. EXPECT_EQ("admin", res->body);
  3877. }
  3878. TEST(InvalidFormatTest, StatusCode) {
  3879. Server svr;
  3880. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3881. res.set_content("Hello World!\n", "text/plain");
  3882. res.status = 9999; // Status should be a three-digit code...
  3883. });
  3884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3885. auto se = detail::scope_exit([&] {
  3886. svr.stop();
  3887. thread.join();
  3888. ASSERT_FALSE(svr.is_running());
  3889. });
  3890. svr.wait_until_ready();
  3891. {
  3892. Client cli(HOST, PORT);
  3893. auto res = cli.Get("/hi");
  3894. ASSERT_FALSE(res);
  3895. }
  3896. }
  3897. TEST(URLFragmentTest, WithFragment) {
  3898. Server svr;
  3899. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3900. EXPECT_TRUE(req.target == "/hi");
  3901. });
  3902. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3903. auto se = detail::scope_exit([&] {
  3904. svr.stop();
  3905. thread.join();
  3906. ASSERT_FALSE(svr.is_running());
  3907. });
  3908. svr.wait_until_ready();
  3909. {
  3910. Client cli(HOST, PORT);
  3911. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3912. EXPECT_TRUE(res);
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. res = cli.Get("/hi%23key1=val1=key2=val2");
  3915. EXPECT_TRUE(res);
  3916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3917. }
  3918. }
  3919. TEST(HeaderWriter, SetHeaderWriter) {
  3920. Server svr;
  3921. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3922. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3923. return detail::write_headers(strm, hdrs);
  3924. });
  3925. svr.Get("/hi", [](const Request &req, Response &res) {
  3926. auto it = req.headers.find("CustomClientHeader");
  3927. EXPECT_TRUE(it != req.headers.end());
  3928. EXPECT_EQ(it->second, "CustomClientValue");
  3929. res.set_content("Hello World!\n", "text/plain");
  3930. });
  3931. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3932. auto se = detail::scope_exit([&] {
  3933. svr.stop();
  3934. thread.join();
  3935. ASSERT_FALSE(svr.is_running());
  3936. });
  3937. svr.wait_until_ready();
  3938. {
  3939. Client cli(HOST, PORT);
  3940. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3941. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3942. return detail::write_headers(strm, hdrs);
  3943. });
  3944. auto res = cli.Get("/hi");
  3945. EXPECT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. auto it = res->headers.find("CustomServerHeader");
  3948. EXPECT_TRUE(it != res->headers.end());
  3949. EXPECT_EQ(it->second, "CustomServerValue");
  3950. }
  3951. }
  3952. class ServerTest : public ::testing::Test {
  3953. protected:
  3954. ServerTest()
  3955. : cli_(HOST, PORT)
  3956. #ifdef CPPHTTPLIB_SSL_ENABLED
  3957. ,
  3958. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3959. #endif
  3960. {
  3961. #ifdef CPPHTTPLIB_SSL_ENABLED
  3962. cli_.enable_server_certificate_verification(false);
  3963. #endif
  3964. // Allow LARGE_DATA (100MB) responses
  3965. cli_.set_payload_max_length(200 * 1024 * 1024);
  3966. }
  3967. virtual void SetUp() {
  3968. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3969. svr_.set_payload_max_length(200 * 1024 * 1024);
  3970. svr_.set_mount_point("/", "./www");
  3971. svr_.set_mount_point("/mount", "./www2");
  3972. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3973. svr_.Get("/hi",
  3974. [&](const Request & /*req*/, Response &res) {
  3975. res.set_content("Hello World!", "text/plain");
  3976. })
  3977. .Get("/file_content",
  3978. [&](const Request & /*req*/, Response &res) {
  3979. res.set_file_content("./www/dir/test.html");
  3980. })
  3981. .Get("/file_content_with_content_type",
  3982. [&](const Request & /*req*/, Response &res) {
  3983. res.set_file_content("./www/file", "text/plain");
  3984. })
  3985. .Get("/invalid_file_content",
  3986. [&](const Request & /*req*/, Response &res) {
  3987. res.set_file_content("./www/dir/invalid_file_path");
  3988. })
  3989. .Get("/http_response_splitting",
  3990. [&](const Request & /*req*/, Response &res) {
  3991. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3992. EXPECT_EQ(0U, res.headers.size());
  3993. EXPECT_FALSE(res.has_header("a"));
  3994. res.set_header("a", "1\nSet-Cookie: a=1");
  3995. EXPECT_EQ(0U, res.headers.size());
  3996. EXPECT_FALSE(res.has_header("a"));
  3997. res.set_header("a", "1\rSet-Cookie: a=1");
  3998. EXPECT_EQ(0U, res.headers.size());
  3999. EXPECT_FALSE(res.has_header("a"));
  4000. res.set_header("a\r\nb", "0");
  4001. EXPECT_EQ(0U, res.headers.size());
  4002. EXPECT_FALSE(res.has_header("a"));
  4003. res.set_header("a\rb", "0");
  4004. EXPECT_EQ(0U, res.headers.size());
  4005. EXPECT_FALSE(res.has_header("a"));
  4006. res.set_header("a\nb", "0");
  4007. EXPECT_EQ(0U, res.headers.size());
  4008. EXPECT_FALSE(res.has_header("a"));
  4009. res.set_redirect("1\r\nSet-Cookie: a=1");
  4010. EXPECT_EQ(0U, res.headers.size());
  4011. EXPECT_FALSE(res.has_header("Location"));
  4012. })
  4013. .Get("/slow",
  4014. [&](const Request & /*req*/, Response &res) {
  4015. std::this_thread::sleep_for(std::chrono::seconds(4));
  4016. res.set_content("slow", "text/plain");
  4017. })
  4018. #if 0
  4019. .Post("/slowpost",
  4020. [&](const Request & /*req*/, Response &res) {
  4021. std::this_thread::sleep_for(std::chrono::seconds(2));
  4022. res.set_content("slow", "text/plain");
  4023. })
  4024. #endif
  4025. .Get("/remote_addr",
  4026. [&](const Request &req, Response &res) {
  4027. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4028. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4029. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4030. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4031. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4032. #endif
  4033. res.set_content(req.remote_addr, "text/plain");
  4034. })
  4035. .Get("/local_addr",
  4036. [&](const Request &req, Response &res) {
  4037. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4038. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4039. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4040. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4041. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4042. #endif
  4043. auto local_addr = req.local_addr;
  4044. auto local_port = std::to_string(req.local_port);
  4045. res.set_content(local_addr.append(":").append(local_port),
  4046. "text/plain");
  4047. })
  4048. .Get("/endwith%",
  4049. [&](const Request & /*req*/, Response &res) {
  4050. res.set_content("Hello World!", "text/plain");
  4051. })
  4052. .Get("/a\\+\\+b",
  4053. [&](const Request &req, Response &res) {
  4054. ASSERT_TRUE(req.has_param("a +b"));
  4055. auto val = req.get_param_value("a +b");
  4056. res.set_content(val, "text/plain");
  4057. })
  4058. .Get("/", [&](const Request & /*req*/,
  4059. Response &res) { res.set_redirect("/hi"); })
  4060. .Post("/1",
  4061. [](const Request & /*req*/, Response &res) {
  4062. res.set_redirect("/2", StatusCode::SeeOther_303);
  4063. })
  4064. .Get("/2",
  4065. [](const Request & /*req*/, Response &res) {
  4066. res.set_content("redirected.", "text/plain");
  4067. res.status = StatusCode::OK_200;
  4068. })
  4069. .Post("/person",
  4070. [&](const Request &req, Response &res) {
  4071. if (req.has_param("name") && req.has_param("note")) {
  4072. persons_[req.get_param_value("name")] =
  4073. req.get_param_value("note");
  4074. } else {
  4075. res.status = StatusCode::BadRequest_400;
  4076. }
  4077. })
  4078. .Put("/person",
  4079. [&](const Request &req, Response &res) {
  4080. if (req.has_param("name") && req.has_param("note")) {
  4081. persons_[req.get_param_value("name")] =
  4082. req.get_param_value("note");
  4083. } else {
  4084. res.status = StatusCode::BadRequest_400;
  4085. }
  4086. })
  4087. .Get("/person/(.*)",
  4088. [&](const Request &req, Response &res) {
  4089. string name = req.matches[1];
  4090. if (persons_.find(name) != persons_.end()) {
  4091. auto note = persons_[name];
  4092. res.set_content(note, "text/plain");
  4093. } else {
  4094. res.status = StatusCode::NotFound_404;
  4095. }
  4096. })
  4097. .Delete("/person",
  4098. [&](const Request &req, Response &res) {
  4099. if (req.has_param("name")) {
  4100. string name = req.get_param_value("name");
  4101. if (persons_.find(name) != persons_.end()) {
  4102. persons_.erase(name);
  4103. res.set_content("DELETED", "text/plain");
  4104. } else {
  4105. res.status = StatusCode::NotFound_404;
  4106. }
  4107. } else {
  4108. res.status = StatusCode::BadRequest_400;
  4109. }
  4110. })
  4111. .Post("/x-www-form-urlencoded-json",
  4112. [&](const Request &req, Response &res) {
  4113. auto json = req.get_param_value("json");
  4114. ASSERT_EQ(JSON_DATA, json);
  4115. res.set_content(json, "appliation/json");
  4116. res.status = StatusCode::OK_200;
  4117. })
  4118. .Get("/streamed-chunked",
  4119. [&](const Request & /*req*/, Response &res) {
  4120. res.set_chunked_content_provider(
  4121. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4122. sink.os << "123";
  4123. sink.os << "456";
  4124. sink.os << "789";
  4125. sink.done();
  4126. return true;
  4127. });
  4128. })
  4129. .Get("/streamed-chunked-with-prohibited-trailer",
  4130. [&](const Request & /*req*/, Response &res) {
  4131. auto i = new int(0);
  4132. // Declare both a prohibited trailer (Content-Length) and an
  4133. // allowed one
  4134. res.set_header("Trailer", "Content-Length, X-Allowed");
  4135. res.set_chunked_content_provider(
  4136. "text/plain",
  4137. [i](size_t /*offset*/, DataSink &sink) {
  4138. switch (*i) {
  4139. case 0: sink.os << "123"; break;
  4140. case 1: sink.os << "456"; break;
  4141. case 2: sink.os << "789"; break;
  4142. case 3: {
  4143. sink.done_with_trailer(
  4144. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4145. } break;
  4146. }
  4147. (*i)++;
  4148. return true;
  4149. },
  4150. [i](bool success) {
  4151. EXPECT_TRUE(success);
  4152. delete i;
  4153. });
  4154. })
  4155. .Get("/streamed-chunked2",
  4156. [&](const Request & /*req*/, Response &res) {
  4157. auto i = new int(0);
  4158. res.set_chunked_content_provider(
  4159. "text/plain",
  4160. [i](size_t /*offset*/, DataSink &sink) {
  4161. switch (*i) {
  4162. case 0: sink.os << "123"; break;
  4163. case 1: sink.os << "456"; break;
  4164. case 2: sink.os << "789"; break;
  4165. case 3: sink.done(); break;
  4166. }
  4167. (*i)++;
  4168. return true;
  4169. },
  4170. [i](bool success) {
  4171. EXPECT_TRUE(success);
  4172. delete i;
  4173. });
  4174. })
  4175. .Get("/streamed-chunked-with-trailer",
  4176. [&](const Request & /*req*/, Response &res) {
  4177. auto i = new int(0);
  4178. res.set_header("Trailer", "Dummy1, Dummy2");
  4179. res.set_chunked_content_provider(
  4180. "text/plain",
  4181. [i](size_t /*offset*/, DataSink &sink) {
  4182. switch (*i) {
  4183. case 0: sink.os << "123"; break;
  4184. case 1: sink.os << "456"; break;
  4185. case 2: sink.os << "789"; break;
  4186. case 3: {
  4187. sink.done_with_trailer(
  4188. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4189. } break;
  4190. }
  4191. (*i)++;
  4192. return true;
  4193. },
  4194. [i](bool success) {
  4195. EXPECT_TRUE(success);
  4196. delete i;
  4197. });
  4198. })
  4199. .Get("/streamed",
  4200. [&](const Request & /*req*/, Response &res) {
  4201. res.set_content_provider(
  4202. 6, "text/plain",
  4203. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4204. sink.os << (offset < 3 ? "a" : "b");
  4205. return true;
  4206. });
  4207. })
  4208. .Get("/streamed-without-length",
  4209. [&](const Request & /*req*/, Response &res) {
  4210. auto data = new std::string("abcdefg");
  4211. res.set_content_provider(
  4212. "text/plain",
  4213. [data](size_t offset, DataSink &sink) {
  4214. if (offset < data->size()) {
  4215. sink.os << data->substr(offset);
  4216. }
  4217. sink.done();
  4218. return true;
  4219. },
  4220. [data](bool success) {
  4221. EXPECT_TRUE(success);
  4222. delete data;
  4223. });
  4224. })
  4225. .Get("/streamed-with-range",
  4226. [&](const Request &req, Response &res) {
  4227. auto data = new std::string("abcdefg");
  4228. // An explicit status keeps the server from picking the 206 it
  4229. // would otherwise choose for a ranged request, so the response
  4230. // is not a partial representation.
  4231. auto status = req.get_param_value("status");
  4232. if (status == "200") {
  4233. res.status = StatusCode::OK_200;
  4234. } else if (status == "403") {
  4235. res.status = StatusCode::Forbidden_403;
  4236. }
  4237. res.set_content_provider(
  4238. data->size(), "text/plain",
  4239. [data](size_t offset, size_t length, DataSink &sink) {
  4240. size_t DATA_CHUNK_SIZE = 4;
  4241. const auto &d = *data;
  4242. auto out_len =
  4243. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4244. auto ret =
  4245. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4246. EXPECT_TRUE(ret);
  4247. return true;
  4248. },
  4249. [data, &req](bool success) {
  4250. EXPECT_EQ(success, !req.has_param("error"));
  4251. delete data;
  4252. });
  4253. })
  4254. .Get("/streamed-cancel",
  4255. [&](const Request & /*req*/, Response &res) {
  4256. res.set_content_provider(
  4257. size_t(-1), "text/plain",
  4258. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4259. sink.os << "data_chunk";
  4260. return true;
  4261. });
  4262. })
  4263. .Get("/regex-with-delimiter",
  4264. [&](const Request &req, Response & /*res*/) {
  4265. ASSERT_TRUE(req.has_param("key"));
  4266. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4267. })
  4268. .Get("/with-range",
  4269. [&](const Request & /*req*/, Response &res) {
  4270. res.set_content("abcdefg", "text/plain");
  4271. })
  4272. .Get("/test-start-time",
  4273. [&](const Request &req, Response & /*res*/) {
  4274. EXPECT_NE(req.start_time_,
  4275. std::chrono::steady_clock::time_point::min());
  4276. })
  4277. .Get("/with-range-customized-response",
  4278. [&](const Request & /*req*/, Response &res) {
  4279. res.status = StatusCode::BadRequest_400;
  4280. res.set_content(JSON_DATA, "application/json");
  4281. })
  4282. .Post("/chunked",
  4283. [&](const Request &req, Response & /*res*/) {
  4284. EXPECT_EQ(req.body, "dechunked post body");
  4285. })
  4286. .Post("/large-chunked",
  4287. [&](const Request &req, Response & /*res*/) {
  4288. std::string expected(6 * 30 * 1024u, 'a');
  4289. EXPECT_EQ(req.body, expected);
  4290. })
  4291. .Post("/multipart",
  4292. [&](const Request &req, Response & /*res*/) {
  4293. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4294. req.form.get_field_count("text2") +
  4295. req.form.get_field_count("file3") +
  4296. req.form.get_field_count("file4"));
  4297. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4298. req.form.get_file_count("file2"));
  4299. ASSERT_TRUE(!req.form.has_file("???"));
  4300. ASSERT_TRUE(!req.form.has_field("???"));
  4301. ASSERT_TRUE(req.body.empty());
  4302. {
  4303. const auto &text = req.form.get_field("text1");
  4304. EXPECT_EQ("text default", text);
  4305. }
  4306. {
  4307. const auto &text = req.form.get_field("text2");
  4308. EXPECT_EQ("aωb", text);
  4309. }
  4310. {
  4311. const auto &file = req.form.get_file("file1");
  4312. EXPECT_EQ("hello.txt", file.filename);
  4313. EXPECT_EQ("text/plain", file.content_type);
  4314. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4315. }
  4316. {
  4317. const auto &file = req.form.get_file("file2");
  4318. EXPECT_EQ("world.json", file.filename);
  4319. EXPECT_EQ("application/json", file.content_type);
  4320. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4321. }
  4322. {
  4323. const auto &text = req.form.get_field("file3");
  4324. EXPECT_EQ(0u, text.size());
  4325. }
  4326. {
  4327. const auto &text = req.form.get_field("file4");
  4328. EXPECT_EQ(0u, text.size());
  4329. }
  4330. })
  4331. .Post("/multipart/multi_file_values",
  4332. [&](const Request &req, Response & /*res*/) {
  4333. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4334. req.form.get_field_count("multi_text1"));
  4335. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4336. ASSERT_TRUE(!req.form.has_file("???"));
  4337. ASSERT_TRUE(!req.form.has_field("???"));
  4338. ASSERT_TRUE(req.body.empty());
  4339. {
  4340. const auto &text = req.form.get_field("text");
  4341. EXPECT_EQ("default text", text);
  4342. }
  4343. {
  4344. const auto &text1_values = req.form.get_fields("multi_text1");
  4345. EXPECT_EQ(2u, text1_values.size());
  4346. EXPECT_EQ("aaaaa", text1_values[0]);
  4347. EXPECT_EQ("bbbbb", text1_values[1]);
  4348. }
  4349. {
  4350. const auto &file1_values = req.form.get_files("multi_file1");
  4351. EXPECT_EQ(2u, file1_values.size());
  4352. auto file1 = file1_values[0];
  4353. EXPECT_EQ(file1.filename, "hello.txt");
  4354. EXPECT_EQ(file1.content_type, "text/plain");
  4355. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4356. auto file2 = file1_values[1];
  4357. EXPECT_EQ(file2.filename, "world.json");
  4358. EXPECT_EQ(file2.content_type, "application/json");
  4359. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4360. }
  4361. })
  4362. .Post("/empty",
  4363. [&](const Request &req, Response &res) {
  4364. EXPECT_EQ(req.body, "");
  4365. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4366. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4367. res.set_content("empty", "text/plain");
  4368. })
  4369. .Post("/empty-no-content-type",
  4370. [&](const Request &req, Response &res) {
  4371. EXPECT_EQ(req.body, "");
  4372. EXPECT_FALSE(req.has_header("Content-Type"));
  4373. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4374. res.set_content("empty-no-content-type", "text/plain");
  4375. })
  4376. .Post("/path-only",
  4377. [&](const Request &req, Response &res) {
  4378. EXPECT_EQ(req.body, "");
  4379. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4380. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4381. res.set_content("path-only", "text/plain");
  4382. })
  4383. .Post("/path-headers-only",
  4384. [&](const Request &req, Response &res) {
  4385. EXPECT_EQ(req.body, "");
  4386. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4387. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4388. EXPECT_EQ("world", req.get_header_value("hello"));
  4389. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4390. res.set_content("path-headers-only", "text/plain");
  4391. })
  4392. .Post("/post-large",
  4393. [&](const Request &req, Response &res) {
  4394. EXPECT_EQ(req.body, LARGE_DATA);
  4395. res.set_content(req.body, "text/plain");
  4396. })
  4397. .Post("/post-loopback",
  4398. [&](const Request &, Response &res,
  4399. ContentReader const &content_reader) {
  4400. std::string body;
  4401. content_reader([&](const char *data, size_t data_length) {
  4402. body.append(data, data_length);
  4403. return true;
  4404. });
  4405. res.set_content(body, "text/plain");
  4406. })
  4407. .Put("/put-loopback",
  4408. [&](const Request &, Response &res,
  4409. ContentReader const &content_reader) {
  4410. std::string body;
  4411. content_reader([&](const char *data, size_t data_length) {
  4412. body.append(data, data_length);
  4413. return true;
  4414. });
  4415. res.set_content(body, "text/plain");
  4416. })
  4417. .Patch("/patch-loopback",
  4418. [&](const Request &, Response &res,
  4419. ContentReader const &content_reader) {
  4420. std::string body;
  4421. content_reader([&](const char *data, size_t data_length) {
  4422. body.append(data, data_length);
  4423. return true;
  4424. });
  4425. res.set_content(body, "text/plain");
  4426. })
  4427. .Put("/empty-no-content-type",
  4428. [&](const Request &req, Response &res) {
  4429. EXPECT_EQ(req.body, "");
  4430. EXPECT_FALSE(req.has_header("Content-Type"));
  4431. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4432. res.set_content("empty-no-content-type", "text/plain");
  4433. })
  4434. .Put("/put",
  4435. [&](const Request &req, Response &res) {
  4436. EXPECT_EQ(req.body, "PUT");
  4437. res.set_content(req.body, "text/plain");
  4438. })
  4439. .Put("/put-large",
  4440. [&](const Request &req, Response &res) {
  4441. EXPECT_EQ(req.body, LARGE_DATA);
  4442. res.set_content(req.body, "text/plain");
  4443. })
  4444. .Patch("/patch",
  4445. [&](const Request &req, Response &res) {
  4446. EXPECT_EQ(req.body, "PATCH");
  4447. res.set_content(req.body, "text/plain");
  4448. })
  4449. .Delete("/delete",
  4450. [&](const Request & /*req*/, Response &res) {
  4451. res.set_content("DELETE", "text/plain");
  4452. })
  4453. .Delete("/delete-body",
  4454. [&](const Request &req, Response &res) {
  4455. EXPECT_EQ(req.body, "content");
  4456. res.set_content(req.body, "text/plain");
  4457. })
  4458. .Options(R"(\*)",
  4459. [&](const Request & /*req*/, Response &res) {
  4460. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4461. })
  4462. .CustomRoute("PROPFIND", "/dav/:id",
  4463. [&](const Request &req, Response &res) {
  4464. res.set_header("x-body-size",
  4465. std::to_string(req.body.size()));
  4466. res.set_header("x-matched-route", req.matched_route);
  4467. res.set_header("x-dav-id", req.path_params.at("id"));
  4468. res.status = StatusCode::MultiStatus_207;
  4469. res.set_content(req.body, "application/xml");
  4470. })
  4471. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4472. [&](const Request &req, Response &res) {
  4473. res.set_header("x-dav-match", req.matches[1]);
  4474. res.status = StatusCode::MultiStatus_207;
  4475. })
  4476. .CustomRoute("MKCOL", "/dav-mkcol",
  4477. [&](const Request &req, Response &res) {
  4478. EXPECT_TRUE(req.body.empty());
  4479. res.status = StatusCode::Created_201;
  4480. })
  4481. .CustomRoute(
  4482. "REPORT", "/dav-report",
  4483. [&](const Request & /*req*/, Response &res,
  4484. const ContentReader &content_reader) {
  4485. std::string body;
  4486. content_reader([&](const char *data, size_t data_length) {
  4487. body.append(data, data_length);
  4488. return true;
  4489. });
  4490. res.set_header("x-body-size", std::to_string(body.size()));
  4491. res.status = StatusCode::MultiStatus_207;
  4492. res.set_content(body, "application/xml");
  4493. })
  4494. .Get("/request-target",
  4495. [&](const Request &req, Response & /*res*/) {
  4496. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4497. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4498. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4499. })
  4500. .Get("/long-query-value",
  4501. [&](const Request &req, Response & /*res*/) {
  4502. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4503. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4504. })
  4505. .Get("/too-long-query-value",
  4506. [&](const Request &req, Response & /*res*/) {
  4507. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4508. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4509. })
  4510. .Get("/array-param",
  4511. [&](const Request &req, Response & /*res*/) {
  4512. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4513. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4514. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4515. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4516. })
  4517. .Get("/array-param-values",
  4518. [&](const Request &req, Response & /*res*/) {
  4519. auto values = req.get_param_values("array");
  4520. EXPECT_EQ(3u, values.size());
  4521. EXPECT_EQ("value1", values[0]);
  4522. EXPECT_EQ("value2", values[1]);
  4523. EXPECT_EQ("value3", values[2]);
  4524. auto empty = req.get_param_values("nonexistent");
  4525. EXPECT_TRUE(empty.empty());
  4526. })
  4527. .Post("/validate-no-multiple-headers",
  4528. [&](const Request &req, Response & /*res*/) {
  4529. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4530. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4531. })
  4532. .Post("/content_receiver",
  4533. [&](const Request &req, Response &res,
  4534. const ContentReader &content_reader) {
  4535. if (req.is_multipart_form_data()) {
  4536. std::vector<FormData> items;
  4537. content_reader(
  4538. [&](const FormData &file) {
  4539. items.push_back(file);
  4540. return true;
  4541. },
  4542. [&](const char *data, size_t data_length) {
  4543. items.back().content.append(data, data_length);
  4544. return true;
  4545. });
  4546. EXPECT_EQ(5u, items.size());
  4547. {
  4548. const auto &file = get_file_value(items, "text1");
  4549. EXPECT_TRUE(file.filename.empty());
  4550. EXPECT_EQ("text default", file.content);
  4551. }
  4552. {
  4553. const auto &file = get_file_value(items, "text2");
  4554. EXPECT_TRUE(file.filename.empty());
  4555. EXPECT_EQ("aωb", file.content);
  4556. }
  4557. {
  4558. const auto &file = get_file_value(items, "file1");
  4559. EXPECT_EQ("hello.txt", file.filename);
  4560. EXPECT_EQ("text/plain", file.content_type);
  4561. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4562. }
  4563. {
  4564. const auto &file = get_file_value(items, "file2");
  4565. EXPECT_EQ("world.json", file.filename);
  4566. EXPECT_EQ("application/json", file.content_type);
  4567. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4568. }
  4569. {
  4570. const auto &file = get_file_value(items, "file3");
  4571. EXPECT_TRUE(file.filename.empty());
  4572. EXPECT_EQ("application/octet-stream", file.content_type);
  4573. EXPECT_EQ(0u, file.content.size());
  4574. }
  4575. } else {
  4576. std::string body;
  4577. content_reader([&](const char *data, size_t data_length) {
  4578. EXPECT_EQ(7U, data_length);
  4579. body.append(data, data_length);
  4580. return true;
  4581. });
  4582. EXPECT_EQ(body, "content");
  4583. res.set_content(body, "text/plain");
  4584. }
  4585. })
  4586. .Put("/content_receiver",
  4587. [&](const Request & /*req*/, Response &res,
  4588. const ContentReader &content_reader) {
  4589. std::string body;
  4590. content_reader([&](const char *data, size_t data_length) {
  4591. body.append(data, data_length);
  4592. return true;
  4593. });
  4594. EXPECT_EQ(body, "content");
  4595. res.set_content(body, "text/plain");
  4596. })
  4597. .Patch("/content_receiver",
  4598. [&](const Request & /*req*/, Response &res,
  4599. const ContentReader &content_reader) {
  4600. std::string body;
  4601. content_reader([&](const char *data, size_t data_length) {
  4602. body.append(data, data_length);
  4603. return true;
  4604. });
  4605. EXPECT_EQ(body, "content");
  4606. res.set_content(body, "text/plain");
  4607. })
  4608. .Post("/query-string-and-body",
  4609. [&](const Request &req, Response & /*res*/) {
  4610. ASSERT_TRUE(req.has_param("key"));
  4611. EXPECT_EQ(req.get_param_value("key"), "value");
  4612. EXPECT_EQ(req.body, "content");
  4613. })
  4614. .Get("/last-request",
  4615. [&](const Request &req, Response & /*res*/) {
  4616. EXPECT_EQ("close", req.get_header_value("Connection"));
  4617. })
  4618. .Get(R"(/redirect/(\d+))",
  4619. [&](const Request &req, Response &res) {
  4620. auto num = std::stoi(req.matches[1]) + 1;
  4621. std::string url = "/redirect/" + std::to_string(num);
  4622. res.set_redirect(url);
  4623. })
  4624. .Post("/binary",
  4625. [&](const Request &req, Response &res) {
  4626. EXPECT_EQ(4U, req.body.size());
  4627. EXPECT_EQ("application/octet-stream",
  4628. req.get_header_value("Content-Type"));
  4629. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4630. res.set_content(req.body, "application/octet-stream");
  4631. })
  4632. .Put("/binary",
  4633. [&](const Request &req, Response &res) {
  4634. EXPECT_EQ(4U, req.body.size());
  4635. EXPECT_EQ("application/octet-stream",
  4636. req.get_header_value("Content-Type"));
  4637. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4638. res.set_content(req.body, "application/octet-stream");
  4639. })
  4640. .Patch("/binary",
  4641. [&](const Request &req, Response &res) {
  4642. EXPECT_EQ(4U, req.body.size());
  4643. EXPECT_EQ("application/octet-stream",
  4644. req.get_header_value("Content-Type"));
  4645. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4646. res.set_content(req.body, "application/octet-stream");
  4647. })
  4648. .Delete("/binary",
  4649. [&](const Request &req, Response &res) {
  4650. EXPECT_EQ(4U, req.body.size());
  4651. EXPECT_EQ("application/octet-stream",
  4652. req.get_header_value("Content-Type"));
  4653. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4654. res.set_content(req.body, "application/octet-stream");
  4655. })
  4656. .Get("/issue1772",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. res.status = 401;
  4659. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4660. })
  4661. .Delete("/issue609",
  4662. [](const httplib::Request &, httplib::Response &res,
  4663. const httplib::ContentReader &) {
  4664. res.set_content("ok", "text/plain");
  4665. })
  4666. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4667. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4668. .Get("/compress",
  4669. [&](const Request & /*req*/, Response &res) {
  4670. res.set_content(
  4671. "12345678901234567890123456789012345678901234567890123456789"
  4672. "01234567890123456789012345678901234567890",
  4673. "text/plain");
  4674. })
  4675. .Get("/compress-with-charset",
  4676. [&](const Request & /*req*/, Response &res) {
  4677. res.set_content(
  4678. "12345678901234567890123456789012345678901234567890123456789"
  4679. "01234567890123456789012345678901234567890",
  4680. "application/json; charset=utf-8");
  4681. })
  4682. .Get("/nocompress",
  4683. [&](const Request & /*req*/, Response &res) {
  4684. res.set_content(
  4685. "12345678901234567890123456789012345678901234567890123456789"
  4686. "01234567890123456789012345678901234567890",
  4687. "application/octet-stream");
  4688. })
  4689. .Post("/compress-multipart",
  4690. [&](const Request &req, Response & /*res*/) {
  4691. EXPECT_EQ(2u, req.form.fields.size());
  4692. ASSERT_TRUE(!req.form.has_field("???"));
  4693. {
  4694. const auto &text = req.form.get_field("key1");
  4695. EXPECT_EQ("test", text);
  4696. }
  4697. {
  4698. const auto &text = req.form.get_field("key2");
  4699. EXPECT_EQ("--abcdefg123", text);
  4700. }
  4701. })
  4702. #endif
  4703. ;
  4704. persons_["john"] = "programmer";
  4705. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4706. svr_.wait_until_ready();
  4707. }
  4708. virtual void TearDown() {
  4709. svr_.stop();
  4710. if (!request_threads_.empty()) {
  4711. std::this_thread::sleep_for(std::chrono::seconds(1));
  4712. for (auto &t : request_threads_) {
  4713. t.join();
  4714. }
  4715. }
  4716. t_.join();
  4717. }
  4718. map<string, string> persons_;
  4719. #ifdef CPPHTTPLIB_SSL_ENABLED
  4720. SSLClient cli_;
  4721. SSLServer svr_;
  4722. #else
  4723. Client cli_;
  4724. Server svr_;
  4725. #endif
  4726. thread t_;
  4727. std::vector<thread> request_threads_;
  4728. };
  4729. TEST_F(ServerTest, GetMethod200) {
  4730. auto res = cli_.Get("/hi");
  4731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4732. EXPECT_EQ("HTTP/1.1", res->version);
  4733. EXPECT_EQ(StatusCode::OK_200, res->status);
  4734. EXPECT_EQ("OK", res->reason);
  4735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4736. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4737. EXPECT_EQ("Hello World!", res->body);
  4738. }
  4739. TEST_F(ServerTest, GetEmptyFile) {
  4740. auto res = cli_.Get("/empty_file");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4744. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4745. EXPECT_EQ("", res->body);
  4746. }
  4747. TEST_F(ServerTest, GetFileContent) {
  4748. auto res = cli_.Get("/file_content");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4752. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4753. EXPECT_EQ("test.html", res->body);
  4754. }
  4755. TEST_F(ServerTest, GetFileContentWithRange) {
  4756. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4758. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4759. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4760. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4761. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4762. EXPECT_EQ("est", res->body);
  4763. }
  4764. TEST_F(ServerTest, GetFileContentWithContentType) {
  4765. auto res = cli_.Get("/file_content_with_content_type");
  4766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4769. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4770. EXPECT_EQ("file\n", res->body);
  4771. }
  4772. TEST_F(ServerTest, GetInvalidFileContent) {
  4773. auto res = cli_.Get("/invalid_file_content");
  4774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4776. }
  4777. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4778. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. EXPECT_EQ("HTTP/1.1", res->version);
  4781. EXPECT_EQ(StatusCode::OK_200, res->status);
  4782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4783. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4784. EXPECT_EQ("Hello World!", res->body);
  4785. }
  4786. TEST_F(ServerTest, GetMethod302) {
  4787. auto res = cli_.Get("/");
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(StatusCode::Found_302, res->status);
  4790. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4791. }
  4792. TEST_F(ServerTest, GetMethod302Redirect) {
  4793. cli_.set_follow_location(true);
  4794. auto res = cli_.Get("/");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("Hello World!", res->body);
  4798. EXPECT_EQ("/hi", res->location);
  4799. }
  4800. TEST_F(ServerTest, GetMethod404) {
  4801. auto res = cli_.Get("/invalid");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4804. }
  4805. TEST_F(ServerTest, HeadMethod200) {
  4806. auto res = cli_.Head("/hi");
  4807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4810. EXPECT_TRUE(res->body.empty());
  4811. }
  4812. TEST_F(ServerTest, HeadMethod200Static) {
  4813. auto res = cli_.Head("/mount/dir/index.html");
  4814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4817. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4818. EXPECT_TRUE(res->body.empty());
  4819. }
  4820. TEST_F(ServerTest, HeadMethod404) {
  4821. auto res = cli_.Head("/invalid");
  4822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4823. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4824. EXPECT_TRUE(res->body.empty());
  4825. }
  4826. TEST_F(ServerTest, GetMethodPersonJohn) {
  4827. auto res = cli_.Get("/person/john");
  4828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4831. EXPECT_EQ("programmer", res->body);
  4832. }
  4833. TEST_F(ServerTest, PostMethod1) {
  4834. auto res = cli_.Get("/person/john1");
  4835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4836. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4837. res = cli_.Post("/person", "name=john1&note=coder",
  4838. "application/x-www-form-urlencoded");
  4839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4840. ASSERT_EQ(StatusCode::OK_200, res->status);
  4841. res = cli_.Get("/person/john1");
  4842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4843. ASSERT_EQ(StatusCode::OK_200, res->status);
  4844. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4845. ASSERT_EQ("coder", res->body);
  4846. }
  4847. TEST_F(ServerTest, PostMethod2) {
  4848. auto res = cli_.Get("/person/john2");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4851. Params params;
  4852. params.emplace("name", "john2");
  4853. params.emplace("note", "coder");
  4854. res = cli_.Post("/person", params);
  4855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4856. ASSERT_EQ(StatusCode::OK_200, res->status);
  4857. res = cli_.Get("/person/john2");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. ASSERT_EQ(StatusCode::OK_200, res->status);
  4860. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4861. ASSERT_EQ("coder", res->body);
  4862. }
  4863. TEST_F(ServerTest, PutMethod3) {
  4864. auto res = cli_.Get("/person/john3");
  4865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4866. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4867. Params params;
  4868. params.emplace("name", "john3");
  4869. params.emplace("note", "coder");
  4870. res = cli_.Put("/person", params);
  4871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4872. ASSERT_EQ(StatusCode::OK_200, res->status);
  4873. res = cli_.Get("/person/john3");
  4874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4875. ASSERT_EQ(StatusCode::OK_200, res->status);
  4876. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4877. ASSERT_EQ("coder", res->body);
  4878. }
  4879. TEST_F(ServerTest, DeleteMethod1) {
  4880. auto res = cli_.Get("/person/john4");
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4883. Params params;
  4884. params.emplace("name", "john4");
  4885. params.emplace("note", "coder");
  4886. res = cli_.Post("/person", params);
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. res = cli_.Get("/person/john4");
  4890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4891. ASSERT_EQ(StatusCode::OK_200, res->status);
  4892. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. ASSERT_EQ("coder", res->body);
  4894. Params delete_params;
  4895. delete_params.emplace("name", "john4");
  4896. res = cli_.Delete("/person", delete_params);
  4897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4898. ASSERT_EQ(StatusCode::OK_200, res->status);
  4899. ASSERT_EQ("DELETED", res->body);
  4900. res = cli_.Get("/person/john4");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4903. }
  4904. TEST_F(ServerTest, DeleteMethod2) {
  4905. auto res = cli_.Get("/person/john5");
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4908. Params params;
  4909. params.emplace("name", "john5");
  4910. params.emplace("note", "developer");
  4911. res = cli_.Post("/person", params);
  4912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4913. ASSERT_EQ(StatusCode::OK_200, res->status);
  4914. res = cli_.Get("/person/john5");
  4915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4916. ASSERT_EQ(StatusCode::OK_200, res->status);
  4917. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4918. ASSERT_EQ("developer", res->body);
  4919. Params delete_params;
  4920. delete_params.emplace("name", "john5");
  4921. Headers headers;
  4922. headers.emplace("Custom-Header", "test-value");
  4923. res = cli_.Delete("/person", headers, delete_params);
  4924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4925. ASSERT_EQ(StatusCode::OK_200, res->status);
  4926. ASSERT_EQ("DELETED", res->body);
  4927. res = cli_.Get("/person/john5");
  4928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4929. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4930. }
  4931. TEST_F(ServerTest, DeleteMethod3) {
  4932. auto res = cli_.Get("/person/john6");
  4933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4934. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4935. Params params;
  4936. params.emplace("name", "john6");
  4937. params.emplace("note", "tester");
  4938. res = cli_.Post("/person", params);
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. ASSERT_EQ(StatusCode::OK_200, res->status);
  4941. res = cli_.Get("/person/john6");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. ASSERT_EQ(StatusCode::OK_200, res->status);
  4944. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4945. ASSERT_EQ("tester", res->body);
  4946. Params delete_params;
  4947. delete_params.emplace("name", "john6");
  4948. Headers headers;
  4949. headers.emplace("Custom-Header", "test-value");
  4950. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. ASSERT_EQ("DELETED", res->body);
  4954. res = cli_.Get("/person/john6");
  4955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4956. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4957. }
  4958. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4959. Params params;
  4960. params.emplace("json", JSON_DATA);
  4961. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. ASSERT_EQ(StatusCode::OK_200, res->status);
  4964. ASSERT_EQ(JSON_DATA, res->body);
  4965. }
  4966. TEST_F(ServerTest, PostEmptyContent) {
  4967. auto res = cli_.Post("/empty", "", "text/plain");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. ASSERT_EQ(StatusCode::OK_200, res->status);
  4970. ASSERT_EQ("empty", res->body);
  4971. }
  4972. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4973. auto res = cli_.Post("/empty-no-content-type");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ("empty-no-content-type", res->body);
  4977. }
  4978. TEST_F(ServerTest, PostPathOnly) {
  4979. auto res = cli_.Post("/path-only");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. ASSERT_EQ(StatusCode::OK_200, res->status);
  4982. ASSERT_EQ("path-only", res->body);
  4983. }
  4984. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4985. auto res = cli_.Post("/path-headers-only",
  4986. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. ASSERT_EQ(StatusCode::OK_200, res->status);
  4989. ASSERT_EQ("path-headers-only", res->body);
  4990. }
  4991. TEST_F(ServerTest, PostLarge) {
  4992. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. ASSERT_EQ(StatusCode::OK_200, res->status);
  4995. EXPECT_EQ(LARGE_DATA, res->body);
  4996. }
  4997. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4998. auto res = cli_.Put("/empty-no-content-type");
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. ASSERT_EQ(StatusCode::OK_200, res->status);
  5001. ASSERT_EQ("empty-no-content-type", res->body);
  5002. }
  5003. TEST_F(ServerTest, GetMethodDir) {
  5004. auto res = cli_.Get("/dir/");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5008. auto body = R"(<html>
  5009. <head>
  5010. </head>
  5011. <body>
  5012. <a href="/dir/test.html">Test</a>
  5013. <a href="/hi">hi</a>
  5014. </body>
  5015. </html>
  5016. )";
  5017. EXPECT_EQ(body, res->body);
  5018. }
  5019. TEST_F(ServerTest, GetMethodDirTest) {
  5020. auto res = cli_.Get("/dir/test.html");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5024. EXPECT_EQ("test.html", res->body);
  5025. }
  5026. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5027. auto res = cli_.Get("/dir/../dir/test.html");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::OK_200, res->status);
  5030. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5031. EXPECT_EQ("test.html", res->body);
  5032. }
  5033. TEST_F(ServerTest, GetMethodInvalidPath) {
  5034. auto res = cli_.Get("/dir/../test.html");
  5035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5037. }
  5038. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5039. auto res = cli_.Get("/../www/dir/test.html");
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5042. }
  5043. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5044. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5047. }
  5048. TEST_F(ServerTest, GetMethodDirMountTest) {
  5049. auto res = cli_.Get("/mount/dir/test.html");
  5050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5051. EXPECT_EQ(StatusCode::OK_200, res->status);
  5052. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5053. EXPECT_EQ("test.html", res->body);
  5054. }
  5055. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5056. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5058. EXPECT_EQ(StatusCode::OK_200, res->status);
  5059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5060. EXPECT_EQ("test.html", res->body);
  5061. }
  5062. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5063. auto res = cli_.Get("/mount/dir/../test.html");
  5064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5066. }
  5067. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5068. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5071. }
  5072. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5073. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5076. }
  5077. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5078. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5081. }
  5082. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5083. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5086. }
  5087. TEST_F(ServerTest, PostMethod303) {
  5088. auto res = cli_.Post("/1", "body", "text/plain");
  5089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5090. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5091. EXPECT_EQ("/2", res->get_header_value("Location"));
  5092. }
  5093. TEST_F(ServerTest, PostMethod303Redirect) {
  5094. cli_.set_follow_location(true);
  5095. auto res = cli_.Post("/1", "body", "text/plain");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("redirected.", res->body);
  5099. EXPECT_EQ("/2", res->location);
  5100. }
  5101. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5102. auto res = cli_.Get("/dir/test.abcde");
  5103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5106. EXPECT_EQ("abcde", res->body);
  5107. }
  5108. TEST_F(ServerTest, StaticFileRange) {
  5109. auto res =
  5110. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5113. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5114. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5115. EXPECT_EQ(true, res->has_header("Content-Range"));
  5116. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5117. EXPECT_EQ(std::string("cd"), res->body);
  5118. }
  5119. TEST_F(ServerTest, StaticFileRanges) {
  5120. auto res = cli_.Get("/dir/test.abcde",
  5121. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5124. EXPECT_TRUE(
  5125. res->get_header_value("Content-Type")
  5126. .find(
  5127. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5128. 0);
  5129. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5130. }
  5131. TEST_F(ServerTest, StaticFileRangeHead) {
  5132. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5135. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5136. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5137. EXPECT_EQ(true, res->has_header("Content-Range"));
  5138. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5139. }
  5140. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5141. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5144. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5145. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5146. EXPECT_EQ(true, res->has_header("Content-Range"));
  5147. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5148. res->get_header_value("Content-Range"));
  5149. EXPECT_EQ("LAST\n", res->body);
  5150. }
  5151. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5152. auto res =
  5153. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5158. EXPECT_EQ(true, res->has_header("Content-Range"));
  5159. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5160. }
  5161. TEST_F(ServerTest, StaticFileBigFile) {
  5162. auto res = cli_.Get("/dir/1MB.txt");
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5166. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5167. }
  5168. TEST_F(ServerTest, InvalidBaseDirMount) {
  5169. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5170. }
  5171. TEST_F(ServerTest, Binary) {
  5172. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5173. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5174. "application/octet-stream");
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. ASSERT_EQ(StatusCode::OK_200, res->status);
  5177. ASSERT_EQ(4U, res->body.size());
  5178. res = cli_.Put("/binary", binary.data(), binary.size(),
  5179. "application/octet-stream");
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. ASSERT_EQ(StatusCode::OK_200, res->status);
  5182. ASSERT_EQ(4U, res->body.size());
  5183. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5184. "application/octet-stream");
  5185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5186. ASSERT_EQ(StatusCode::OK_200, res->status);
  5187. ASSERT_EQ(4U, res->body.size());
  5188. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5189. "application/octet-stream");
  5190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5191. ASSERT_EQ(StatusCode::OK_200, res->status);
  5192. ASSERT_EQ(4U, res->body.size());
  5193. }
  5194. TEST_F(ServerTest, BinaryString) {
  5195. auto binary = std::string("\x00\x01\x02\x03", 4);
  5196. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. ASSERT_EQ(StatusCode::OK_200, res->status);
  5199. ASSERT_EQ(4U, res->body.size());
  5200. res = cli_.Put("/binary", binary, "application/octet-stream");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. ASSERT_EQ(StatusCode::OK_200, res->status);
  5203. ASSERT_EQ(4U, res->body.size());
  5204. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5206. ASSERT_EQ(StatusCode::OK_200, res->status);
  5207. ASSERT_EQ(4U, res->body.size());
  5208. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5210. ASSERT_EQ(StatusCode::OK_200, res->status);
  5211. ASSERT_EQ(4U, res->body.size());
  5212. }
  5213. TEST_F(ServerTest, EmptyRequest) {
  5214. auto res = cli_.Get("");
  5215. ASSERT_TRUE(!res);
  5216. EXPECT_EQ(Error::Connection, res.error());
  5217. }
  5218. TEST_F(ServerTest, LongRequest) {
  5219. std::string request;
  5220. for (size_t i = 0; i < 545; i++) {
  5221. request += "/TooLongRequest";
  5222. }
  5223. request += "OK";
  5224. auto res = cli_.Get(request.c_str());
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5227. }
  5228. TEST_F(ServerTest, TooLongRequest) {
  5229. std::string request;
  5230. for (size_t i = 0; i < 546; i++) {
  5231. request += "/TooLongRequest";
  5232. }
  5233. request += "_NG";
  5234. auto start = std::chrono::high_resolution_clock::now();
  5235. cli_.set_keep_alive(true);
  5236. auto res = cli_.Get(request.c_str());
  5237. auto end = std::chrono::high_resolution_clock::now();
  5238. auto elapsed =
  5239. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5240. .count();
  5241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5242. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5243. EXPECT_LE(elapsed, 1000);
  5244. EXPECT_EQ("close", res->get_header_value("Connection"));
  5245. EXPECT_FALSE(cli_.is_socket_open());
  5246. }
  5247. TEST_F(ServerTest, AlmostTooLongRequest) {
  5248. // test for #2046 - URI length check shouldn't include other content on req
  5249. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5250. // leading /, space, HTTP/1.1)
  5251. std::string request =
  5252. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5253. auto res = cli_.Get(request.c_str());
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5256. }
  5257. TEST_F(ServerTest, LongHeader) {
  5258. Request req;
  5259. req.method = "GET";
  5260. req.path = "/hi";
  5261. std::string host_and_port;
  5262. host_and_port += HOST;
  5263. host_and_port += ":";
  5264. host_and_port += std::to_string(PORT);
  5265. req.headers.emplace("Host", host_and_port.c_str());
  5266. req.headers.emplace("Accept", "*/*");
  5267. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5268. req.headers.emplace(
  5269. "Header-Name",
  5270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5298. "@@@@@@@@@@@@@@@@");
  5299. auto res = std::make_shared<Response>();
  5300. auto error = Error::Success;
  5301. auto ret = cli_.send(req, *res, error);
  5302. ASSERT_TRUE(ret);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. }
  5305. TEST_F(ServerTest, LongQueryValue) {
  5306. auto start = std::chrono::high_resolution_clock::now();
  5307. cli_.set_keep_alive(true);
  5308. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5309. auto end = std::chrono::high_resolution_clock::now();
  5310. auto elapsed =
  5311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5312. .count();
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5315. EXPECT_LE(elapsed, 1000);
  5316. EXPECT_EQ("close", res->get_header_value("Connection"));
  5317. EXPECT_FALSE(cli_.is_socket_open());
  5318. }
  5319. TEST_F(ServerTest, TooLongQueryValue) {
  5320. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5321. ASSERT_FALSE(res);
  5322. EXPECT_EQ(Error::Read, res.error());
  5323. }
  5324. TEST_F(ServerTest, TooLongHeader) {
  5325. Request req;
  5326. req.method = "GET";
  5327. req.path = "/hi";
  5328. std::string host_and_port;
  5329. host_and_port += HOST;
  5330. host_and_port += ":";
  5331. host_and_port += std::to_string(PORT);
  5332. req.headers.emplace("Host", host_and_port.c_str());
  5333. req.headers.emplace("Accept", "*/*");
  5334. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5335. req.headers.emplace(
  5336. "Header-Name",
  5337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5365. "@@@@@@@@@@@@@@@@@");
  5366. auto res = std::make_shared<Response>();
  5367. auto error = Error::Success;
  5368. auto ret = cli_.send(req, *res, error);
  5369. ASSERT_TRUE(ret);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, HeaderCountAtLimit) {
  5373. // Test with headers just under the 100 limit
  5374. httplib::Headers headers;
  5375. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5376. // This should keep us just under the 100 header limit
  5377. for (int i = 0; i < 95; i++) {
  5378. std::string name = "X-Test-Header-" + std::to_string(i);
  5379. std::string value = "value" + std::to_string(i);
  5380. headers.emplace(name, value);
  5381. }
  5382. // This should work fine as we're under the limit
  5383. auto res = cli_.Get("/hi", headers);
  5384. EXPECT_TRUE(res);
  5385. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5386. }
  5387. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5388. // Test with many headers to exceed the 100 limit
  5389. httplib::Headers headers;
  5390. // Add 150 headers to definitely exceed the 100 limit
  5391. for (int i = 0; i < 150; i++) {
  5392. std::string name = "X-Test-Header-" + std::to_string(i);
  5393. std::string value = "value" + std::to_string(i);
  5394. headers.emplace(name, value);
  5395. }
  5396. // This should fail due to exceeding header count limit
  5397. cli_.set_keep_alive(true);
  5398. auto res = cli_.Get("/hi", headers);
  5399. // The server should respond with 400 Bad Request
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5402. EXPECT_EQ("close", res->get_header_value("Connection"));
  5403. EXPECT_FALSE(cli_.is_socket_open());
  5404. }
  5405. TEST_F(ServerTest, PercentEncoding) {
  5406. auto res = cli_.Get("/e%6edwith%");
  5407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. }
  5410. TEST_F(ServerTest, PercentEncodingUnicode) {
  5411. auto res = cli_.Get("/e%u006edwith%");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. }
  5415. TEST_F(ServerTest, InvalidPercentEncoding) {
  5416. auto res = cli_.Get("/%endwith%");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5419. }
  5420. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5421. auto res = cli_.Get("/%uendwith%");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5424. }
  5425. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5426. auto res = cli_.Get("/hello?aaa=bbb%");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5429. }
  5430. TEST_F(ServerTest, PlusSignEncoding) {
  5431. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5433. EXPECT_EQ(StatusCode::OK_200, res->status);
  5434. EXPECT_EQ("a +b", res->body);
  5435. }
  5436. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5437. // This test simulates a potential DoS attack using many headers
  5438. // to verify our security fix prevents memory exhaustion
  5439. httplib::Headers attack_headers;
  5440. // Attempt to add many headers like an attacker would (200 headers to far
  5441. // exceed limit)
  5442. for (int i = 0; i < 200; i++) {
  5443. std::string name = "X-Attack-Header-" + std::to_string(i);
  5444. std::string value = "attack_payload_" + std::to_string(i);
  5445. attack_headers.emplace(name, value);
  5446. }
  5447. // Try to POST with excessive headers
  5448. cli_.set_keep_alive(true);
  5449. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5450. // Should either fail or return 400 Bad Request due to security limit
  5451. if (res) {
  5452. // If we get a response, it should be 400 Bad Request
  5453. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5454. EXPECT_EQ("close", res->get_header_value("Connection"));
  5455. }
  5456. EXPECT_FALSE(cli_.is_socket_open());
  5457. }
  5458. TEST_F(ServerTest, MultipartFormData) {
  5459. UploadFormDataItems items = {
  5460. {"text1", "text default", "", ""},
  5461. {"text2", "aωb", "", ""},
  5462. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5463. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5464. {"file3", "", "", "application/octet-stream"},
  5465. {"file4", "", "", " application/json tmp-string "}};
  5466. auto res = cli_.Post("/multipart", items);
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. }
  5470. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5471. UploadFormDataItems items = {
  5472. {"text", "default text", "", ""},
  5473. {"multi_text1", "aaaaa", "", ""},
  5474. {"multi_text1", "bbbbb", "", ""},
  5475. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5476. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5477. "application/json"},
  5478. };
  5479. auto res = cli_.Post("/multipart/multi_file_values", items);
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. }
  5483. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5484. auto res = cli_.Get("/hi");
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5488. EXPECT_EQ("Hello World!", res->body);
  5489. }
  5490. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5491. Request req;
  5492. req.method = "POST";
  5493. req.path = "/chunked";
  5494. std::string host_and_port;
  5495. host_and_port += HOST;
  5496. host_and_port += ":";
  5497. host_and_port += std::to_string(PORT);
  5498. req.headers.emplace("Host", host_and_port.c_str());
  5499. req.headers.emplace("Accept", "*/*");
  5500. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5501. req.headers.emplace("Content-Type", "text/plain");
  5502. req.headers.emplace("Content-Length", "0");
  5503. req.headers.emplace(
  5504. "Transfer-Encoding",
  5505. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5506. // Client does not chunk, so make a chunked body manually.
  5507. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5508. auto res = std::make_shared<Response>();
  5509. auto error = Error::Success;
  5510. auto ret = cli_.send(req, *res, error);
  5511. ASSERT_TRUE(ret);
  5512. EXPECT_EQ(StatusCode::OK_200, res->status);
  5513. }
  5514. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5515. // rather than treat them as valid lengths.
  5516. template <typename ClientT>
  5517. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5518. Request req;
  5519. req.method = "POST";
  5520. req.path = "/chunked";
  5521. std::string host_and_port;
  5522. host_and_port += HOST;
  5523. host_and_port += ":";
  5524. host_and_port += std::to_string(PORT);
  5525. req.headers.emplace("Host", host_and_port.c_str());
  5526. req.headers.emplace("Content-Length", "0");
  5527. req.headers.emplace("Transfer-Encoding", "chunked");
  5528. req.body = body;
  5529. auto res = std::make_shared<Response>();
  5530. auto error = Error::Success;
  5531. ASSERT_TRUE(cli.send(req, *res, error));
  5532. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5533. }
  5534. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5535. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5536. }
  5537. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5538. expect_chunked_body_rejected(
  5539. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5540. }
  5541. TEST_F(ServerTest, GetStreamed2) {
  5542. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5545. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5546. EXPECT_EQ(true, res->has_header("Content-Range"));
  5547. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5548. EXPECT_EQ(std::string("ab"), res->body);
  5549. }
  5550. TEST_F(ServerTest, GetStreamed) {
  5551. auto res = cli_.Get("/streamed");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5555. EXPECT_EQ(std::string("aaabbb"), res->body);
  5556. }
  5557. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5558. auto res = cli_.Get("/streamed-without-length",
  5559. Headers{make_range_header({{0, -1}})});
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ(false, res->has_header("Content-Length"));
  5563. EXPECT_EQ(false, res->has_header("Content-Range"));
  5564. EXPECT_EQ(std::string("abcdefg"), res->body);
  5565. }
  5566. TEST_F(ServerTest, GetStreamedWithRange1) {
  5567. auto res =
  5568. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5570. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5571. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5572. EXPECT_EQ(true, res->has_header("Content-Range"));
  5573. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5574. EXPECT_EQ(std::string("def"), res->body);
  5575. }
  5576. TEST_F(ServerTest, GetStreamedWithRange2) {
  5577. auto res =
  5578. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5582. EXPECT_EQ(true, res->has_header("Content-Range"));
  5583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5584. EXPECT_EQ(std::string("bcdefg"), res->body);
  5585. }
  5586. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5587. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5590. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5591. EXPECT_EQ(true, res->has_header("Content-Range"));
  5592. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5593. EXPECT_EQ(std::string("efg"), res->body);
  5594. }
  5595. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5596. auto res =
  5597. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5600. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5601. EXPECT_EQ(false, res->has_header("Content-Range"));
  5602. EXPECT_EQ(0U, res->body.size());
  5603. }
  5604. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5605. // Only a 206 is served as a partial representation. Under any other status
  5606. // `apply_ranges()` reported the full content length, so the body must match
  5607. // that header, and the content provider must never be asked for an offset
  5608. // outside the representation.
  5609. auto check = [&](int status, const char *range) {
  5610. auto path =
  5611. std::string("/streamed-with-range?status=") + std::to_string(status);
  5612. auto ctx = path + " Range: " + range;
  5613. auto res = cli_.Get(path, Headers{{"Range", range}});
  5614. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5615. EXPECT_EQ(status, res->status) << ctx;
  5616. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5618. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5619. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5620. };
  5621. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5622. check(403, "bytes=3-5");
  5623. // The offset is far past the representation.
  5624. check(403, "bytes=100000-100200");
  5625. // `first_pos` is still -1 here, and the bounds asserts in
  5626. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5627. check(403, "bytes=-3");
  5628. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5629. // multipart branch would have written one that is empty.
  5630. check(403, "bytes=1-2, 4-5");
  5631. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5632. // covers the whole representation.
  5633. check(200, "bytes=3-5");
  5634. check(200, "bytes=1-2, 4-5");
  5635. }
  5636. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5637. auto res =
  5638. cli_.Get("/streamed-with-range",
  5639. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5640. "92233720368547758079223372036854775807"}});
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5643. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5644. EXPECT_EQ(false, res->has_header("Content-Range"));
  5645. EXPECT_EQ(0U, res->body.size());
  5646. }
  5647. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5648. auto res = cli_.Get(
  5649. "/with-range",
  5650. Headers{{"Range",
  5651. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5652. {"Accept-Encoding", ""}});
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5655. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5656. EXPECT_EQ(true, res->has_header("Content-Range"));
  5657. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5658. EXPECT_EQ(std::string("abcdefg"), res->body);
  5659. }
  5660. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5661. auto res = cli_.Get("/with-range", Headers{
  5662. {"Range", "bytes=0-"},
  5663. {"Accept-Encoding", ""},
  5664. });
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5667. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5668. EXPECT_EQ(true, res->has_header("Content-Range"));
  5669. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5670. EXPECT_EQ(std::string("abcdefg"), res->body);
  5671. }
  5672. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5673. auto res = cli_.Get("/streamed-with-range",
  5674. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5677. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5678. EXPECT_EQ(false, res->has_header("Content-Range"));
  5679. EXPECT_EQ(267U, res->body.size());
  5680. // Check that both range contents are present
  5681. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5682. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5683. // Check that Content-Range headers are present for both ranges
  5684. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5685. std::string::npos);
  5686. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5687. std::string::npos);
  5688. }
  5689. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5690. Ranges ranges;
  5691. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5692. ranges.emplace_back(0, -1);
  5693. }
  5694. auto res = cli_.Get("/streamed-with-range?error",
  5695. Headers{{make_range_header(ranges)}});
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5698. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5699. EXPECT_EQ(false, res->has_header("Content-Range"));
  5700. EXPECT_EQ(0U, res->body.size());
  5701. }
  5702. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5703. auto res = cli_.Get("/streamed-with-range",
  5704. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5707. EXPECT_EQ(5U, res->body.size());
  5708. // Check that overlapping ranges are coalesced into a single range
  5709. EXPECT_EQ("bcdef", res->body);
  5710. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5711. // Should be single range, not multipart
  5712. EXPECT_TRUE(res->has_header("Content-Range"));
  5713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5714. }
  5715. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5716. auto res = cli_.Get("/streamed-with-range",
  5717. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5720. EXPECT_EQ(268U, res->body.size());
  5721. // Check that both range contents are present
  5722. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5723. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5724. // Check that Content-Range headers are present for both ranges
  5725. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5726. std::string::npos);
  5727. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5728. std::string::npos);
  5729. }
  5730. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5731. auto res = cli_.Get("/streamed-with-range",
  5732. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5735. EXPECT_EQ(269U, res->body.size());
  5736. // Check that both duplicate range contents are present
  5737. size_t first_abc = res->body.find("abc\r\n");
  5738. EXPECT_TRUE(first_abc != std::string::npos);
  5739. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5740. EXPECT_TRUE(second_abc != std::string::npos);
  5741. // Check that Content-Range headers are present for both ranges
  5742. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5743. EXPECT_TRUE(first_range != std::string::npos);
  5744. size_t second_range =
  5745. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5746. EXPECT_TRUE(second_range != std::string::npos);
  5747. }
  5748. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5749. auto res =
  5750. cli_.Get("/streamed-with-range?error",
  5751. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5754. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5755. EXPECT_EQ(false, res->has_header("Content-Range"));
  5756. EXPECT_EQ(0U, res->body.size());
  5757. }
  5758. TEST_F(ServerTest, GetStreamedEndless) {
  5759. uint64_t offset = 0;
  5760. auto res = cli_.Get("/streamed-cancel",
  5761. [&](const char * /*data*/, uint64_t data_length) {
  5762. if (offset < 100) {
  5763. offset += data_length;
  5764. return true;
  5765. }
  5766. return false;
  5767. });
  5768. ASSERT_TRUE(!res);
  5769. EXPECT_EQ(Error::Canceled, res.error());
  5770. }
  5771. TEST_F(ServerTest, ClientStop) {
  5772. std::atomic_size_t count{4};
  5773. std::vector<std::thread> threads;
  5774. for (auto i = count.load(); i != 0; --i) {
  5775. threads.emplace_back([&]() {
  5776. auto res = cli_.Get("/streamed-cancel",
  5777. [&](const char *, uint64_t) { return true; });
  5778. --count;
  5779. ASSERT_TRUE(!res);
  5780. EXPECT_TRUE(res.error() == Error::Canceled ||
  5781. res.error() == Error::Read || res.error() == Error::Write);
  5782. });
  5783. }
  5784. std::this_thread::sleep_for(std::chrono::seconds(2));
  5785. while (count != 0) {
  5786. cli_.stop();
  5787. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5788. }
  5789. for (auto &t : threads) {
  5790. t.join();
  5791. }
  5792. }
  5793. TEST_F(ServerTest, GetWithRange1) {
  5794. auto res = cli_.Get("/with-range", Headers{
  5795. make_range_header({{3, 5}}),
  5796. {"Accept-Encoding", ""},
  5797. });
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5800. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5801. EXPECT_EQ(true, res->has_header("Content-Range"));
  5802. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5803. EXPECT_EQ(std::string("def"), res->body);
  5804. }
  5805. TEST_F(ServerTest, GetWithRange2) {
  5806. auto res = cli_.Get("/with-range", Headers{
  5807. make_range_header({{1, -1}}),
  5808. {"Accept-Encoding", ""},
  5809. });
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5812. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5813. EXPECT_EQ(true, res->has_header("Content-Range"));
  5814. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5815. EXPECT_EQ(std::string("bcdefg"), res->body);
  5816. }
  5817. TEST_F(ServerTest, GetWithRange3) {
  5818. auto res = cli_.Get("/with-range", Headers{
  5819. make_range_header({{0, 0}}),
  5820. {"Accept-Encoding", ""},
  5821. });
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5824. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5825. EXPECT_EQ(true, res->has_header("Content-Range"));
  5826. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5827. EXPECT_EQ(std::string("a"), res->body);
  5828. }
  5829. TEST_F(ServerTest, GetWithRange4) {
  5830. auto res = cli_.Get("/with-range", Headers{
  5831. make_range_header({{-1, 2}}),
  5832. {"Accept-Encoding", ""},
  5833. });
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5836. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5837. EXPECT_EQ(true, res->has_header("Content-Range"));
  5838. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5839. EXPECT_EQ(std::string("fg"), res->body);
  5840. }
  5841. TEST_F(ServerTest, GetWithRange5) {
  5842. auto res = cli_.Get("/with-range", Headers{
  5843. make_range_header({{0, 5}}),
  5844. {"Accept-Encoding", ""},
  5845. });
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5848. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5849. EXPECT_EQ(true, res->has_header("Content-Range"));
  5850. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5851. EXPECT_EQ(std::string("abcdef"), res->body);
  5852. }
  5853. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5854. auto res =
  5855. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5858. }
  5859. TEST_F(ServerTest, GetWithRangeMultipart) {
  5860. auto res =
  5861. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5864. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5865. EXPECT_EQ(false, res->has_header("Content-Range"));
  5866. EXPECT_EQ(267U, res->body.size());
  5867. }
  5868. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5869. auto res = cli_.Get("/with-range",
  5870. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5873. }
  5874. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5875. auto res = cli_.Get("/with-range-customized-response",
  5876. Headers{{make_range_header({{1, 2}})}});
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5879. EXPECT_EQ(true, res->has_header("Content-Length"));
  5880. EXPECT_EQ(false, res->has_header("Content-Range"));
  5881. EXPECT_EQ(JSON_DATA, res->body);
  5882. }
  5883. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5884. auto res = cli_.Get("/with-range-customized-response",
  5885. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5888. EXPECT_EQ(true, res->has_header("Content-Length"));
  5889. EXPECT_EQ(false, res->has_header("Content-Range"));
  5890. EXPECT_EQ(JSON_DATA, res->body);
  5891. }
  5892. TEST_F(ServerTest, Issue1772) {
  5893. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5896. }
  5897. TEST_F(ServerTest, Issue609) {
  5898. auto res = cli_.Delete("/issue609");
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. EXPECT_EQ(std::string("ok"), res->body);
  5902. }
  5903. TEST_F(ServerTest, GetStreamedChunked) {
  5904. auto res = cli_.Get("/streamed-chunked");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::OK_200, res->status);
  5907. EXPECT_EQ(std::string("123456789"), res->body);
  5908. }
  5909. TEST_F(ServerTest, GetStreamedChunked2) {
  5910. auto res = cli_.Get("/streamed-chunked2");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. EXPECT_EQ(std::string("123456789"), res->body);
  5914. }
  5915. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5916. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ(std::string("123456789"), res->body);
  5920. EXPECT_TRUE(res->has_header("Trailer"));
  5921. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5922. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5923. // Trailers are now stored separately from headers (security fix)
  5924. EXPECT_EQ(2U, res->trailers.size());
  5925. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5926. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5927. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5928. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5929. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5930. // Verify trailers are NOT in headers (security verification)
  5931. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5932. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5933. }
  5934. TEST_F(ServerTest, LargeChunkedPost) {
  5935. Request req;
  5936. req.method = "POST";
  5937. req.path = "/large-chunked";
  5938. std::string host_and_port;
  5939. host_and_port += HOST;
  5940. host_and_port += ":";
  5941. host_and_port += std::to_string(PORT);
  5942. req.headers.emplace("Host", host_and_port.c_str());
  5943. req.headers.emplace("Accept", "*/*");
  5944. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5945. req.headers.emplace("Content-Type", "text/plain");
  5946. req.headers.emplace("Content-Length", "0");
  5947. req.headers.emplace("Transfer-Encoding", "chunked");
  5948. std::string long_string(30 * 1024u, 'a');
  5949. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5950. // Attempt to make a large enough post to exceed OS buffers, to test that
  5951. // the server handles short reads if the full chunk data isn't available.
  5952. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5953. auto res = std::make_shared<Response>();
  5954. auto error = Error::Success;
  5955. auto ret = cli_.send(req, *res, error);
  5956. ASSERT_TRUE(ret);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. }
  5959. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5960. auto res = cli_.Get("/remote_addr");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5964. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5965. }
  5966. TEST_F(ServerTest, GetMethodLocalAddr) {
  5967. auto res = cli_.Get("/local_addr");
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5971. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5972. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5973. }
  5974. TEST_F(ServerTest, HTTPResponseSplitting) {
  5975. auto res = cli_.Get("/http_response_splitting");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST_F(ServerTest, SlowRequest) {
  5980. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5981. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5982. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5983. }
  5984. #if 0
  5985. TEST_F(ServerTest, SlowPost) {
  5986. char buffer[64 * 1024];
  5987. memset(buffer, 0x42, sizeof(buffer));
  5988. auto res = cli_.Post(
  5989. "/slowpost", 64 * 1024 * 1024,
  5990. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5991. auto ret = sink.write(buffer, sizeof(buffer));
  5992. EXPECT_TRUE(ret);
  5993. return true;
  5994. },
  5995. "text/plain");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::OK_200, res->status);
  5998. }
  5999. TEST_F(ServerTest, SlowPostFail) {
  6000. char buffer[64 * 1024];
  6001. memset(buffer, 0x42, sizeof(buffer));
  6002. cli_.set_write_timeout(std::chrono::seconds(0));
  6003. auto res = cli_.Post(
  6004. "/slowpost", 64 * 1024 * 1024,
  6005. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6006. sink.write(buffer, sizeof(buffer));
  6007. return true;
  6008. },
  6009. "text/plain");
  6010. ASSERT_TRUE(!res);
  6011. EXPECT_EQ(Error::Write, res.error());
  6012. }
  6013. #endif
  6014. TEST_F(ServerTest, Put) {
  6015. auto res = cli_.Put("/put", "PUT", "text/plain");
  6016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. EXPECT_EQ("PUT", res->body);
  6019. }
  6020. TEST_F(ServerTest, PutWithContentProvider) {
  6021. auto res = cli_.Put(
  6022. "/put", 3,
  6023. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6024. sink.os << "PUT";
  6025. return true;
  6026. },
  6027. "text/plain");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. EXPECT_EQ(StatusCode::OK_200, res->status);
  6030. EXPECT_EQ("PUT", res->body);
  6031. }
  6032. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6033. auto res = cli_.Post(
  6034. "/post", 42,
  6035. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6036. return false;
  6037. },
  6038. "text/plain");
  6039. ASSERT_TRUE(!res);
  6040. EXPECT_EQ(Error::Canceled, res.error());
  6041. }
  6042. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6043. auto res = cli_.Put(
  6044. "/put",
  6045. [](size_t /*offset*/, DataSink &sink) {
  6046. sink.os << "PUT";
  6047. sink.done();
  6048. return true;
  6049. },
  6050. "text/plain");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. EXPECT_EQ("PUT", res->body);
  6054. }
  6055. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6056. auto res = cli_.Post(
  6057. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6058. "text/plain");
  6059. ASSERT_TRUE(!res);
  6060. EXPECT_EQ(Error::Canceled, res.error());
  6061. }
  6062. TEST_F(ServerTest, PostLoopBack) {
  6063. std::string body;
  6064. auto res = cli_.Post(
  6065. "/post-loopback", 9,
  6066. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6067. EXPECT_EQ(9u, length);
  6068. sink.write("123", 3);
  6069. sink.write("456", 3);
  6070. sink.write("789", 3);
  6071. return true;
  6072. },
  6073. "text/plain",
  6074. [&body](const char *data, size_t data_length) {
  6075. body.append(data, data_length);
  6076. return true;
  6077. });
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::OK_200, res->status);
  6080. EXPECT_EQ("123456789", body);
  6081. }
  6082. TEST_F(ServerTest, PutLoopBack) {
  6083. std::string body;
  6084. auto res = cli_.Put(
  6085. "/put-loopback", 9,
  6086. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6087. EXPECT_EQ(9u, length);
  6088. sink.write("123", 3);
  6089. sink.write("456", 3);
  6090. sink.write("789", 3);
  6091. return true;
  6092. },
  6093. "text/plain",
  6094. [&body](const char *data, size_t data_length) {
  6095. body.append(data, data_length);
  6096. return true;
  6097. });
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("123456789", body);
  6101. }
  6102. TEST_F(ServerTest, PatchLoopBack) {
  6103. std::string body;
  6104. auto res = cli_.Patch(
  6105. "/patch-loopback", 9,
  6106. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6107. EXPECT_EQ(9u, length);
  6108. sink.write("123", 3);
  6109. sink.write("456", 3);
  6110. sink.write("789", 3);
  6111. return true;
  6112. },
  6113. "text/plain",
  6114. [&body](const char *data, size_t data_length) {
  6115. body.append(data, data_length);
  6116. return true;
  6117. });
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. EXPECT_EQ("123456789", body);
  6121. }
  6122. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6123. std::string body;
  6124. auto res = cli_.Post(
  6125. "/post-loopback",
  6126. [](size_t /*offset*/, DataSink &sink) {
  6127. sink.write("123", 3);
  6128. sink.write("456", 3);
  6129. sink.write("789", 3);
  6130. sink.done();
  6131. return true;
  6132. },
  6133. "text/plain",
  6134. [&body](const char *data, size_t data_length) {
  6135. body.append(data, data_length);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6139. EXPECT_EQ(StatusCode::OK_200, res->status);
  6140. EXPECT_EQ("123456789", body);
  6141. }
  6142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6143. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6144. cli_.set_compress(true);
  6145. auto res = cli_.Put(
  6146. "/put", 3,
  6147. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6148. sink.os << "PUT";
  6149. return true;
  6150. },
  6151. "text/plain");
  6152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6153. EXPECT_EQ(StatusCode::OK_200, res->status);
  6154. EXPECT_EQ("PUT", res->body);
  6155. }
  6156. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6157. cli_.set_compress(true);
  6158. auto res = cli_.Post(
  6159. "/post", 42,
  6160. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6161. return false;
  6162. },
  6163. "text/plain");
  6164. ASSERT_TRUE(!res);
  6165. EXPECT_EQ(Error::Canceled, res.error());
  6166. }
  6167. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6168. cli_.set_compress(true);
  6169. auto res = cli_.Put(
  6170. "/put",
  6171. [](size_t /*offset*/, DataSink &sink) {
  6172. sink.os << "PUT";
  6173. sink.done();
  6174. return true;
  6175. },
  6176. "text/plain");
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. EXPECT_EQ(StatusCode::OK_200, res->status);
  6179. EXPECT_EQ("PUT", res->body);
  6180. }
  6181. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6182. cli_.set_compress(true);
  6183. auto res = cli_.Post(
  6184. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6185. "text/plain");
  6186. ASSERT_TRUE(!res);
  6187. EXPECT_EQ(Error::Canceled, res.error());
  6188. }
  6189. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6190. cli_.set_compress(true);
  6191. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::OK_200, res->status);
  6194. EXPECT_EQ(LARGE_DATA, res->body);
  6195. }
  6196. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6197. #ifdef CPPHTTPLIB_SSL_ENABLED
  6198. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6199. Client cli(s.c_str());
  6200. cli.enable_server_certificate_verification(false);
  6201. #else
  6202. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6203. Client cli(s.c_str());
  6204. #endif
  6205. cli.set_compress(true);
  6206. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. EXPECT_EQ(LARGE_DATA, res->body);
  6210. // The compressed size should be less than a 10th of the original. May vary
  6211. // depending on the zlib library.
  6212. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6213. static_cast<uint64_t>(10 * 1024 * 1024));
  6214. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6215. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6216. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6217. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6218. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6219. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6220. #endif
  6221. }
  6222. TEST_F(ServerTest, PutContentWithDeflate) {
  6223. cli_.set_compress(false);
  6224. Headers headers;
  6225. headers.emplace("Content-Encoding", "deflate");
  6226. // PUT in deflate format:
  6227. auto res = cli_.Put("/put", headers,
  6228. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. EXPECT_EQ("PUT", res->body);
  6232. }
  6233. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6234. Headers headers;
  6235. headers.emplace("Accept-Encoding", "gzip, deflate");
  6236. auto res = cli_.Get("/streamed-chunked", headers);
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::OK_200, res->status);
  6239. EXPECT_EQ(std::string("123456789"), res->body);
  6240. }
  6241. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6242. Headers headers;
  6243. headers.emplace("Accept-Encoding", "gzip, deflate");
  6244. auto res = cli_.Get("/streamed-chunked2", headers);
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ(std::string("123456789"), res->body);
  6248. }
  6249. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6250. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. EXPECT_EQ(StatusCode::OK_200, res->status);
  6253. }
  6254. TEST(GzipDecompressor, ChunkedDecompression) {
  6255. std::string data;
  6256. for (size_t i = 0; i < 32 * 1024; ++i) {
  6257. data.push_back(static_cast<char>('a' + i % 26));
  6258. }
  6259. std::string compressed_data;
  6260. {
  6261. httplib::detail::gzip_compressor compressor;
  6262. bool result = compressor.compress(
  6263. data.data(), data.size(),
  6264. /*last=*/true,
  6265. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6266. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6267. compressed_data_size);
  6268. return true;
  6269. });
  6270. ASSERT_TRUE(result);
  6271. }
  6272. std::string decompressed_data;
  6273. {
  6274. httplib::detail::gzip_decompressor decompressor;
  6275. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6276. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6277. size_t chunk_size = 130;
  6278. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6279. chunk_begin += chunk_size) {
  6280. size_t current_chunk_size =
  6281. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6282. bool result = decompressor.decompress(
  6283. compressed_data.data() + chunk_begin, current_chunk_size,
  6284. [&](const char *decompressed_data_chunk,
  6285. size_t decompressed_data_chunk_size) {
  6286. decompressed_data.insert(decompressed_data.size(),
  6287. decompressed_data_chunk,
  6288. decompressed_data_chunk_size);
  6289. return true;
  6290. });
  6291. ASSERT_TRUE(result);
  6292. }
  6293. }
  6294. ASSERT_EQ(data, decompressed_data);
  6295. }
  6296. TEST(GzipDecompressor, DeflateDecompression) {
  6297. std::string original_text = "Raw deflate without gzip";
  6298. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6299. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6300. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6301. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6302. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6303. std::string decompressed_data;
  6304. {
  6305. httplib::detail::gzip_decompressor decompressor;
  6306. bool result = decompressor.decompress(
  6307. compressed_data.data(), compressed_data.size(),
  6308. [&](const char *decompressed_data_chunk,
  6309. size_t decompressed_data_chunk_size) {
  6310. decompressed_data.insert(decompressed_data.size(),
  6311. decompressed_data_chunk,
  6312. decompressed_data_chunk_size);
  6313. return true;
  6314. });
  6315. ASSERT_TRUE(result);
  6316. }
  6317. ASSERT_EQ(original_text, decompressed_data);
  6318. }
  6319. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6320. std::string original_text = "Raw deflate without gzip";
  6321. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6322. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6323. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6324. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6325. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6326. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6327. std::string decompressed_data;
  6328. {
  6329. httplib::detail::gzip_decompressor decompressor;
  6330. bool result = decompressor.decompress(
  6331. compressed_data.data(), compressed_data.size(),
  6332. [&](const char *decompressed_data_chunk,
  6333. size_t decompressed_data_chunk_size) {
  6334. decompressed_data.insert(decompressed_data.size(),
  6335. decompressed_data_chunk,
  6336. decompressed_data_chunk_size);
  6337. return true;
  6338. });
  6339. ASSERT_TRUE(result);
  6340. }
  6341. ASSERT_EQ(original_text, decompressed_data);
  6342. }
  6343. #endif
  6344. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6345. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6346. Headers headers;
  6347. headers.emplace("Accept-Encoding", "br");
  6348. auto res = cli_.Get("/streamed-chunked", headers);
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. EXPECT_EQ(std::string("123456789"), res->body);
  6352. }
  6353. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6354. Headers headers;
  6355. headers.emplace("Accept-Encoding", "br");
  6356. auto res = cli_.Get("/streamed-chunked2", headers);
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ(std::string("123456789"), res->body);
  6360. }
  6361. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6362. cli_.set_compress(true);
  6363. auto res = cli_.Put(
  6364. "/put", 3,
  6365. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6366. sink.os << "PUT";
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. EXPECT_EQ("PUT", res->body);
  6373. }
  6374. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6375. cli_.set_compress(true);
  6376. auto res = cli_.Put(
  6377. "/put",
  6378. [](size_t /*offset*/, DataSink &sink) {
  6379. sink.os << "PUT";
  6380. sink.done();
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ("PUT", res->body);
  6387. }
  6388. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6389. cli_.set_compress(true);
  6390. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. EXPECT_EQ(LARGE_DATA, res->body);
  6394. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6395. }
  6396. #endif
  6397. TEST_F(ServerTest, Patch) {
  6398. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("PATCH", res->body);
  6402. }
  6403. TEST_F(ServerTest, Delete) {
  6404. auto res = cli_.Delete("/delete");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("DELETE", res->body);
  6408. }
  6409. TEST_F(ServerTest, DeleteContentReceiver) {
  6410. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. EXPECT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ("content", res->body);
  6414. }
  6415. TEST_F(ServerTest, Options) {
  6416. auto res = cli_.Options("*");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6420. EXPECT_TRUE(res->body.empty());
  6421. }
  6422. TEST_F(ServerTest, URL) {
  6423. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. }
  6427. TEST_F(ServerTest, ArrayParam) {
  6428. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. }
  6432. TEST_F(ServerTest, ArrayParamValues) {
  6433. auto res =
  6434. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. }
  6438. TEST_F(ServerTest, NoMultipleHeaders) {
  6439. Headers headers = {{"Content-Length", "5"}};
  6440. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6441. "text/plain");
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::OK_200, res->status);
  6444. }
  6445. TEST_F(ServerTest, PostContentReceiver) {
  6446. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. ASSERT_EQ(StatusCode::OK_200, res->status);
  6449. ASSERT_EQ("content", res->body);
  6450. }
  6451. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6452. UploadFormDataItems items = {
  6453. {"text1", "text default", "", ""},
  6454. {"text2", "aωb", "", ""},
  6455. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6456. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6457. {"file3", "", "", "application/octet-stream"},
  6458. };
  6459. auto res = cli_.Post("/content_receiver", items);
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::OK_200, res->status);
  6462. }
  6463. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6464. UploadFormDataItems items = {
  6465. {"text1", "text default", "", ""},
  6466. {"text2", "aωb", "", ""},
  6467. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6468. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6469. {"file3", "", "", "application/octet-stream"},
  6470. };
  6471. auto boundary = std::string("+++++");
  6472. std::string body;
  6473. for (const auto &item : items) {
  6474. body += "--" + boundary + "\r\n";
  6475. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6476. if (!item.filename.empty()) {
  6477. body += "; filename=\"" + item.filename + "\"";
  6478. }
  6479. body += "\r\n";
  6480. if (!item.content_type.empty()) {
  6481. body += "Content-Type: " + item.content_type + "\r\n";
  6482. }
  6483. body += "\r\n";
  6484. body += item.content + "\r\n";
  6485. }
  6486. body += "--" + boundary + "--\r\n";
  6487. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6488. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. }
  6492. TEST(MultipartFormDataTest, FieldEscaping) {
  6493. Server svr;
  6494. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6495. const ContentReader &content_reader) {
  6496. ASSERT_TRUE(req.is_multipart_form_data());
  6497. std::vector<FormData> received;
  6498. content_reader(
  6499. [&](const FormData &file) {
  6500. received.push_back(file);
  6501. return true;
  6502. },
  6503. [&](const char *data, size_t data_length) {
  6504. received.back().content.append(data, data_length);
  6505. return true;
  6506. });
  6507. // '"', CR and LF in names and filenames are escaped following the
  6508. // WHATWG HTML standard, so each part still parses as a single part
  6509. // with no injected headers. Content types get CR/LF escaped too,
  6510. // while '"' (legal there, e.g. quoted charset) is preserved.
  6511. ASSERT_EQ(4U, received.size());
  6512. EXPECT_EQ("na%22me", received[0].name);
  6513. EXPECT_EQ("quoted name", received[0].content);
  6514. EXPECT_EQ("file", received[1].name);
  6515. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6516. received[1].filename);
  6517. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6518. EXPECT_EQ("injected", received[1].content);
  6519. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6520. EXPECT_EQ("my%22file.txt", received[2].filename);
  6521. EXPECT_EQ("cr lf name", received[2].content);
  6522. EXPECT_EQ("typed", received[3].name);
  6523. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6524. received[3].content_type);
  6525. EXPECT_EQ("typed content", received[3].content);
  6526. });
  6527. auto port = svr.bind_to_any_port("localhost");
  6528. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. t.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", port);
  6536. UploadFormDataItems items = {
  6537. {"na\"me", "quoted name", "", ""},
  6538. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6539. "application/octet-stream"},
  6540. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6541. {"typed", "typed content", "",
  6542. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6543. };
  6544. auto res = cli.Post("/post", items);
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. EXPECT_EQ(StatusCode::OK_200, res->status);
  6547. }
  6548. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6549. const UploadFormDataItems items = {
  6550. {"name1", "Content 1", "", ""},
  6551. {"name2", "Content 2", "file2.txt", "text/plain"},
  6552. };
  6553. Server svr;
  6554. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6555. const ContentReader &content_reader) {
  6556. ASSERT_TRUE(req.is_multipart_form_data());
  6557. std::vector<FormData> received;
  6558. content_reader(
  6559. [&](const FormData &file) {
  6560. received.push_back(file);
  6561. return true;
  6562. },
  6563. [&](const char *data, size_t data_length) {
  6564. received.back().content.append(data, data_length);
  6565. return true;
  6566. });
  6567. ASSERT_EQ(2U, received.size());
  6568. EXPECT_EQ("name1", received[0].name);
  6569. EXPECT_EQ("Content 1", received[0].content);
  6570. EXPECT_EQ("name2", received[1].name);
  6571. EXPECT_EQ("Content 2", received[1].content);
  6572. EXPECT_EQ("file2.txt", received[1].filename);
  6573. EXPECT_EQ("text/plain", received[1].content_type);
  6574. });
  6575. auto port = svr.bind_to_any_port("localhost");
  6576. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6577. auto se = detail::scope_exit([&] {
  6578. svr.stop();
  6579. t.join();
  6580. ASSERT_FALSE(svr.is_running());
  6581. });
  6582. svr.wait_until_ready();
  6583. Client cli("localhost", port);
  6584. // Whole-body serialization with a generated boundary
  6585. {
  6586. MultipartFormDataWriter writer;
  6587. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6588. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6589. writer.content_type());
  6590. auto body = writer.serialize(items);
  6591. EXPECT_EQ(body.size(), writer.content_length(items));
  6592. auto res = cli.Post("/post", body, writer.content_type());
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. }
  6596. // Per-part framing with a custom boundary via a content provider
  6597. {
  6598. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6599. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6600. MultipartFormDataWriter writer("custom-boundary_123");
  6601. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6602. std::string body;
  6603. for (const auto &item : items) {
  6604. body += writer.item_begin(item);
  6605. body += item.content;
  6606. body += MultipartFormDataWriter::item_end();
  6607. }
  6608. body += writer.finish();
  6609. EXPECT_EQ(body.size(), writer.content_length(items));
  6610. auto res = cli.Post(
  6611. "/post", body.size(),
  6612. [&](size_t offset, size_t length, DataSink &sink) {
  6613. sink.write(body.data() + offset, length);
  6614. return true;
  6615. },
  6616. writer.content_type());
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. }
  6620. }
  6621. TEST_F(ServerTest, PostContentReceiverGzip) {
  6622. cli_.set_compress(true);
  6623. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. ASSERT_EQ(StatusCode::OK_200, res->status);
  6626. ASSERT_EQ("content", res->body);
  6627. }
  6628. TEST_F(ServerTest, PutContentReceiver) {
  6629. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. ASSERT_EQ(StatusCode::OK_200, res->status);
  6632. ASSERT_EQ("content", res->body);
  6633. }
  6634. TEST_F(ServerTest, PatchContentReceiver) {
  6635. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6637. ASSERT_EQ(StatusCode::OK_200, res->status);
  6638. ASSERT_EQ("content", res->body);
  6639. }
  6640. template <typename ClientType>
  6641. void TestWithHeadersAndContentReceiver(
  6642. ClientType &cli,
  6643. std::function<Result(ClientType &, const std::string &, const Headers &,
  6644. const std::string &, const std::string &,
  6645. ContentReceiver, DownloadProgress)>
  6646. request_func) {
  6647. Headers headers;
  6648. headers.emplace("X-Custom-Header", "test-value");
  6649. std::string received_body;
  6650. auto res = request_func(
  6651. cli, "/content_receiver", headers, "content", "application/json",
  6652. [&](const char *data, size_t data_length) {
  6653. received_body.append(data, data_length);
  6654. return true;
  6655. },
  6656. nullptr);
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("content", received_body);
  6660. }
  6661. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6662. #ifdef CPPHTTPLIB_SSL_ENABLED
  6663. using ClientT = SSLClient;
  6664. #else
  6665. using ClientT = Client;
  6666. #endif
  6667. TestWithHeadersAndContentReceiver<ClientT>(
  6668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6669. const std::string &body, const std::string &content_type,
  6670. ContentReceiver receiver, DownloadProgress progress) {
  6671. return cli.Post(path, headers, body, content_type, receiver, progress);
  6672. });
  6673. }
  6674. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6675. #ifdef CPPHTTPLIB_SSL_ENABLED
  6676. using ClientT = SSLClient;
  6677. #else
  6678. using ClientT = Client;
  6679. #endif
  6680. TestWithHeadersAndContentReceiver<ClientT>(
  6681. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6682. const std::string &body, const std::string &content_type,
  6683. ContentReceiver receiver, DownloadProgress progress) {
  6684. return cli.Put(path, headers, body, content_type, receiver, progress);
  6685. });
  6686. }
  6687. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6688. #ifdef CPPHTTPLIB_SSL_ENABLED
  6689. using ClientT = SSLClient;
  6690. #else
  6691. using ClientT = Client;
  6692. #endif
  6693. TestWithHeadersAndContentReceiver<ClientT>(
  6694. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6695. const std::string &body, const std::string &content_type,
  6696. ContentReceiver receiver, DownloadProgress progress) {
  6697. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6698. });
  6699. }
  6700. template <typename ClientType>
  6701. void TestWithHeadersAndContentReceiverWithProgress(
  6702. ClientType &cli,
  6703. std::function<Result(ClientType &, const std::string &, const Headers &,
  6704. const std::string &, const std::string &,
  6705. ContentReceiver, DownloadProgress)>
  6706. request_func) {
  6707. Headers headers;
  6708. headers.emplace("X-Test-Header", "progress-test");
  6709. std::string received_body;
  6710. auto progress_called = false;
  6711. auto res = request_func(
  6712. cli, "/content_receiver", headers, "content", "text/plain",
  6713. [&](const char *data, size_t data_length) {
  6714. received_body.append(data, data_length);
  6715. return true;
  6716. },
  6717. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6718. progress_called = true;
  6719. return true;
  6720. });
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. EXPECT_EQ("content", received_body);
  6724. EXPECT_TRUE(progress_called);
  6725. }
  6726. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6727. #ifdef CPPHTTPLIB_SSL_ENABLED
  6728. using ClientT = SSLClient;
  6729. #else
  6730. using ClientT = Client;
  6731. #endif
  6732. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6733. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6734. const std::string &body, const std::string &content_type,
  6735. ContentReceiver receiver, DownloadProgress progress) {
  6736. return cli.Post(path, headers, body, content_type, receiver, progress);
  6737. });
  6738. }
  6739. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6740. #ifdef CPPHTTPLIB_SSL_ENABLED
  6741. using ClientT = SSLClient;
  6742. #else
  6743. using ClientT = Client;
  6744. #endif
  6745. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6746. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6747. const std::string &body, const std::string &content_type,
  6748. ContentReceiver receiver, DownloadProgress progress) {
  6749. return cli.Put(path, headers, body, content_type, receiver, progress);
  6750. });
  6751. }
  6752. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6753. #ifdef CPPHTTPLIB_SSL_ENABLED
  6754. using ClientT = SSLClient;
  6755. #else
  6756. using ClientT = Client;
  6757. #endif
  6758. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6759. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6760. const std::string &body, const std::string &content_type,
  6761. ContentReceiver receiver, DownloadProgress progress) {
  6762. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6763. });
  6764. }
  6765. template <typename ClientType>
  6766. void TestWithHeadersAndContentReceiverError(
  6767. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6768. const Headers &, const std::string &,
  6769. const std::string &, ContentReceiver)>
  6770. request_func) {
  6771. Headers headers;
  6772. headers.emplace("X-Error-Test", "true");
  6773. std::string received_body;
  6774. auto receiver_failed = false;
  6775. auto res =
  6776. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6777. [&](const char *data, size_t data_length) {
  6778. received_body.append(data, data_length);
  6779. receiver_failed = true;
  6780. return false;
  6781. });
  6782. ASSERT_FALSE(res);
  6783. EXPECT_TRUE(receiver_failed);
  6784. }
  6785. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6786. #ifdef CPPHTTPLIB_SSL_ENABLED
  6787. using ClientT = SSLClient;
  6788. #else
  6789. using ClientT = Client;
  6790. #endif
  6791. TestWithHeadersAndContentReceiverError<ClientT>(
  6792. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6793. const std::string &body, const std::string &content_type,
  6794. ContentReceiver receiver) {
  6795. return cli.Post(path, headers, body, content_type, receiver);
  6796. });
  6797. }
  6798. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6799. #ifdef CPPHTTPLIB_SSL_ENABLED
  6800. using ClientT = SSLClient;
  6801. #else
  6802. using ClientT = Client;
  6803. #endif
  6804. TestWithHeadersAndContentReceiverError<ClientT>(
  6805. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6806. const std::string &body, const std::string &content_type,
  6807. ContentReceiver receiver) {
  6808. return cli.Put(path, headers, body, content_type, receiver);
  6809. });
  6810. }
  6811. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6812. #ifdef CPPHTTPLIB_SSL_ENABLED
  6813. using ClientT = SSLClient;
  6814. #else
  6815. using ClientT = Client;
  6816. #endif
  6817. TestWithHeadersAndContentReceiverError<ClientT>(
  6818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6819. const std::string &body, const std::string &content_type,
  6820. ContentReceiver receiver) {
  6821. return cli.Patch(path, headers, body, content_type, receiver);
  6822. });
  6823. }
  6824. TEST_F(ServerTest, PostQueryStringAndBody) {
  6825. auto res =
  6826. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. ASSERT_EQ(StatusCode::OK_200, res->status);
  6829. }
  6830. TEST_F(ServerTest, HTTP2Magic) {
  6831. Request req;
  6832. req.method = "PRI";
  6833. req.path = "*";
  6834. req.body = "SM";
  6835. auto res = std::make_shared<Response>();
  6836. auto error = Error::Success;
  6837. auto ret = cli_.send(req, *res, error);
  6838. ASSERT_TRUE(ret);
  6839. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6840. }
  6841. TEST_F(ServerTest, KeepAlive) {
  6842. auto res = cli_.Get("/hi");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. EXPECT_EQ("Hello World!", res->body);
  6847. res = cli_.Get("/hi");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6851. EXPECT_EQ("Hello World!", res->body);
  6852. res = cli_.Get("/hi");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6856. EXPECT_EQ("Hello World!", res->body);
  6857. res = cli_.Get("/not-exist");
  6858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6860. res = cli_.Post("/empty", "", "text/plain");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6864. EXPECT_EQ("empty", res->body);
  6865. EXPECT_EQ("close", res->get_header_value("Connection"));
  6866. res = cli_.Post(
  6867. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6868. "text/plain");
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6872. EXPECT_EQ("empty", res->body);
  6873. cli_.set_keep_alive(false);
  6874. res = cli_.Get("/last-request");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::OK_200, res->status);
  6877. EXPECT_EQ("close", res->get_header_value("Connection"));
  6878. }
  6879. TEST_F(ServerTest, TooManyRedirect) {
  6880. cli_.set_follow_location(true);
  6881. auto res = cli_.Get("/redirect/0");
  6882. ASSERT_TRUE(!res);
  6883. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6884. }
  6885. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6886. Request req;
  6887. req.method = "FOOBAR";
  6888. req.path = "/hi";
  6889. cli_.set_keep_alive(true);
  6890. auto res = cli_.send(req);
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6893. EXPECT_EQ("close", res->get_header_value("Connection"));
  6894. EXPECT_FALSE(cli_.is_socket_open());
  6895. }
  6896. TEST_F(ServerTest, CustomRouteReadsBody) {
  6897. const std::string xml =
  6898. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  6899. Request req;
  6900. req.method = "PROPFIND";
  6901. req.path = "/dav/dir";
  6902. req.set_header("Depth", "1");
  6903. req.body = xml;
  6904. auto res = cli_.send(req);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6907. EXPECT_EQ(xml, res->body);
  6908. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  6909. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  6910. }
  6911. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  6912. Request req;
  6913. req.method = "PROPFIND";
  6914. req.path = "/dav/42";
  6915. auto res = cli_.send(req);
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6918. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  6919. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  6920. }
  6921. TEST_F(ServerTest, CustomRouteRegexPattern) {
  6922. Request req;
  6923. req.method = "PROPFIND";
  6924. req.path = "/dav-re/123";
  6925. auto res = cli_.send(req);
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6928. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  6929. }
  6930. TEST_F(ServerTest, CustomRouteWithoutBody) {
  6931. Request req;
  6932. req.method = "MKCOL";
  6933. req.path = "/dav-mkcol";
  6934. auto res = cli_.send(req);
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::Created_201, res->status);
  6937. }
  6938. TEST_F(ServerTest, CustomRouteWithContentReader) {
  6939. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  6940. Request req;
  6941. req.method = "REPORT";
  6942. req.path = "/dav-report";
  6943. req.body = xml;
  6944. auto res = cli_.send(req);
  6945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6946. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6947. EXPECT_EQ(xml, res->body);
  6948. }
  6949. // A content reader route must fire even when the request carries no body,
  6950. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  6951. // Without that, a body-less PROPFIND-style request would fall through to 404.
  6952. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  6953. Request req;
  6954. req.method = "REPORT";
  6955. req.path = "/dav-report";
  6956. auto res = cli_.send(req);
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6959. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  6960. }
  6961. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  6962. Request req;
  6963. req.method = "PROPFIND";
  6964. req.path = "/not-dav";
  6965. auto res = cli_.send(req);
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6968. }
  6969. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  6970. Request req;
  6971. req.method = "UNLOCK";
  6972. req.path = "/dav/dir";
  6973. cli_.set_keep_alive(true);
  6974. auto res = cli_.send(req);
  6975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6976. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6977. EXPECT_EQ("close", res->get_header_value("Connection"));
  6978. EXPECT_FALSE(cli_.is_socket_open());
  6979. }
  6980. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  6981. // The mount point serves this path, but only for GET and HEAD.
  6982. auto get_res = cli_.Get("/dir/index.html");
  6983. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  6984. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  6985. Request req;
  6986. req.method = "PROPFIND";
  6987. req.path = "/dir/index.html";
  6988. auto res = cli_.send(req);
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6991. }
  6992. TEST_F(ServerTest, CustomRouteKeepAlive) {
  6993. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6994. cli_.set_keep_alive(true);
  6995. for (auto i = 0; i < 2; i++) {
  6996. Request req;
  6997. req.method = "PROPFIND";
  6998. req.path = "/dav/dir";
  6999. req.body = xml;
  7000. auto res = cli_.send(req);
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7003. EXPECT_EQ(xml, res->body);
  7004. EXPECT_TRUE(cli_.is_socket_open());
  7005. }
  7006. // A built-in method must still be served on the same connection.
  7007. cli_.set_keep_alive(false);
  7008. auto res = cli_.Get("/hi");
  7009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7010. EXPECT_EQ(StatusCode::OK_200, res->status);
  7011. EXPECT_EQ("close", res->get_header_value("Connection"));
  7012. }
  7013. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7014. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7015. Request req;
  7016. req.method = "PROPFIND";
  7017. req.path = "/dav/dir";
  7018. req.set_header("Expect", "100-continue");
  7019. req.body = xml;
  7020. auto res = cli_.send(req);
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7023. EXPECT_EQ(xml, res->body);
  7024. }
  7025. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7026. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7027. TEST_F(ServerTest, Gzip) {
  7028. Headers headers;
  7029. headers.emplace("Accept-Encoding", "gzip, deflate");
  7030. auto res = cli_.Get("/compress", headers);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7034. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7035. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7036. "7890123456789012345678901234567890",
  7037. res->body);
  7038. EXPECT_EQ(StatusCode::OK_200, res->status);
  7039. }
  7040. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7041. Headers headers;
  7042. headers.emplace("Accept-Encoding", "gzip, deflate");
  7043. auto res = cli_.Get("/compress-with-charset", headers);
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7046. EXPECT_EQ("application/json; charset=utf-8",
  7047. res->get_header_value("Content-Type"));
  7048. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7049. "7890123456789012345678901234567890",
  7050. res->body);
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7054. Headers headers;
  7055. headers.emplace("Accept-Encoding", "");
  7056. auto res = cli_.Get("/compress", headers);
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7060. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7061. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7062. "7890123456789012345678901234567890",
  7063. res->body);
  7064. EXPECT_EQ(StatusCode::OK_200, res->status);
  7065. }
  7066. TEST_F(ServerTest, GzipWithContentReceiver) {
  7067. Headers headers;
  7068. headers.emplace("Accept-Encoding", "gzip, deflate");
  7069. std::string body;
  7070. auto res = cli_.Get("/compress", headers,
  7071. [&](const char *data, uint64_t data_length) {
  7072. EXPECT_EQ(100U, data_length);
  7073. body.append(data, data_length);
  7074. return true;
  7075. });
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7079. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7081. "7890123456789012345678901234567890",
  7082. body);
  7083. EXPECT_EQ(StatusCode::OK_200, res->status);
  7084. }
  7085. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7086. Headers headers;
  7087. headers.emplace("Accept-Encoding", "gzip, deflate");
  7088. cli_.set_decompress(false);
  7089. auto res = cli_.Get("/compress", headers);
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7093. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7094. EXPECT_EQ(33U, res->body.size());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. }
  7097. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7098. Headers headers;
  7099. headers.emplace("Accept-Encoding", "");
  7100. std::string body;
  7101. auto res = cli_.Get("/compress", headers,
  7102. [&](const char *data, uint64_t data_length) {
  7103. EXPECT_EQ(100U, data_length);
  7104. body.append(data, data_length);
  7105. return true;
  7106. });
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7112. "7890123456789012345678901234567890",
  7113. body);
  7114. EXPECT_EQ(StatusCode::OK_200, res->status);
  7115. }
  7116. TEST_F(ServerTest, NoGzip) {
  7117. Headers headers;
  7118. headers.emplace("Accept-Encoding", "gzip, deflate");
  7119. auto res = cli_.Get("/nocompress", headers);
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7122. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7125. "7890123456789012345678901234567890",
  7126. res->body);
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. }
  7129. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7130. Headers headers;
  7131. headers.emplace("Accept-Encoding", "gzip, deflate");
  7132. std::string body;
  7133. auto res = cli_.Get("/nocompress", headers,
  7134. [&](const char *data, uint64_t data_length) {
  7135. EXPECT_EQ(100U, data_length);
  7136. body.append(data, data_length);
  7137. return true;
  7138. });
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7144. "7890123456789012345678901234567890",
  7145. body);
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. }
  7148. TEST_F(ServerTest, MultipartFormDataGzip) {
  7149. UploadFormDataItems items = {
  7150. {"key1", "test", "", ""},
  7151. {"key2", "--abcdefg123", "", ""},
  7152. };
  7153. cli_.set_compress(true);
  7154. auto res = cli_.Post("/compress-multipart", items);
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::OK_200, res->status);
  7157. }
  7158. #endif
  7159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7160. TEST_F(ServerTest, Brotli) {
  7161. Headers headers;
  7162. headers.emplace("Accept-Encoding", "br");
  7163. auto res = cli_.Get("/compress", headers);
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7167. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7169. "7890123456789012345678901234567890",
  7170. res->body);
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. }
  7173. #endif
  7174. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7175. TEST_F(ServerTest, Zstd) {
  7176. Headers headers;
  7177. headers.emplace("Accept-Encoding", "zstd");
  7178. auto res = cli_.Get("/compress", headers);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7182. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7183. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7184. "7890123456789012345678901234567890",
  7185. res->body);
  7186. EXPECT_EQ(StatusCode::OK_200, res->status);
  7187. }
  7188. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7189. Headers headers;
  7190. headers.emplace("Accept-Encoding", "");
  7191. auto res = cli_.Get("/compress", headers);
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7195. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7196. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7197. "7890123456789012345678901234567890",
  7198. res->body);
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7202. Headers headers;
  7203. headers.emplace("Accept-Encoding", "zstd");
  7204. std::string body;
  7205. auto res = cli_.Get("/compress", headers,
  7206. [&](const char *data, uint64_t data_length) {
  7207. EXPECT_EQ(100U, data_length);
  7208. body.append(data, data_length);
  7209. return true;
  7210. });
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7215. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7216. "7890123456789012345678901234567890",
  7217. body);
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7221. Headers headers;
  7222. headers.emplace("Accept-Encoding", "zstd");
  7223. cli_.set_decompress(false);
  7224. auto res = cli_.Get("/compress", headers);
  7225. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7226. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7227. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7228. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7231. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7232. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. ASSERT_EQ(26U, res->body.size());
  7235. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7236. 0);
  7237. }
  7238. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7239. Headers headers;
  7240. headers.emplace("Accept-Encoding", "");
  7241. std::string body;
  7242. auto res = cli_.Get("/compress", headers,
  7243. [&](const char *data, uint64_t data_length) {
  7244. EXPECT_EQ(100U, data_length);
  7245. body.append(data, data_length);
  7246. return true;
  7247. });
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7250. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7251. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7252. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7253. "7890123456789012345678901234567890",
  7254. body);
  7255. EXPECT_EQ(StatusCode::OK_200, res->status);
  7256. }
  7257. TEST_F(ServerTest, NoZstd) {
  7258. Headers headers;
  7259. headers.emplace("Accept-Encoding", "zstd");
  7260. auto res = cli_.Get("/nocompress", headers);
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7263. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7264. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7265. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7266. "7890123456789012345678901234567890",
  7267. res->body);
  7268. EXPECT_EQ(StatusCode::OK_200, res->status);
  7269. }
  7270. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7271. Headers headers;
  7272. headers.emplace("Accept-Encoding", "zstd");
  7273. std::string body;
  7274. auto res = cli_.Get("/nocompress", headers,
  7275. [&](const char *data, uint64_t data_length) {
  7276. EXPECT_EQ(100U, data_length);
  7277. body.append(data, data_length);
  7278. return true;
  7279. });
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7282. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7285. "7890123456789012345678901234567890",
  7286. body);
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. // TODO: How to enable zstd ??
  7290. TEST_F(ServerTest, MultipartFormDataZstd) {
  7291. UploadFormDataItems items = {
  7292. {"key1", "test", "", ""},
  7293. {"key2", "--abcdefg123", "", ""},
  7294. };
  7295. Headers headers;
  7296. headers.emplace("Accept-Encoding", "zstd");
  7297. cli_.set_compress(true);
  7298. auto res = cli_.Post("/compress-multipart", headers, items);
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7303. Headers headers;
  7304. headers.emplace("Accept-Encoding", "zstd");
  7305. cli_.set_compress(true);
  7306. auto res = cli_.Put(
  7307. "/put", headers, 3,
  7308. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7309. sink.os << "PUT";
  7310. return true;
  7311. },
  7312. "text/plain");
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::OK_200, res->status);
  7315. EXPECT_EQ("PUT", res->body);
  7316. }
  7317. // Pre-compression logging tests
  7318. TEST_F(ServerTest, PreCompressionLogging) {
  7319. // Test data for compression (matches the actual /compress endpoint content)
  7320. const std::string test_content =
  7321. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7322. "3456789012345678901234567890";
  7323. // Variables to capture logging data
  7324. std::string pre_compression_body;
  7325. std::string pre_compression_content_type;
  7326. std::string pre_compression_content_encoding;
  7327. std::string post_compression_body;
  7328. std::string post_compression_content_type;
  7329. std::string post_compression_content_encoding;
  7330. // Set up pre-compression logger
  7331. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7332. const Response &res) {
  7333. pre_compression_body = res.body;
  7334. pre_compression_content_type = res.get_header_value("Content-Type");
  7335. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7336. });
  7337. // Set up post-compression logger
  7338. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7339. post_compression_body = res.body;
  7340. post_compression_content_type = res.get_header_value("Content-Type");
  7341. post_compression_content_encoding =
  7342. res.get_header_value("Content-Encoding");
  7343. });
  7344. // Test with gzip compression
  7345. Headers headers;
  7346. headers.emplace("Accept-Encoding", "gzip");
  7347. auto res = cli_.Get("/compress", headers);
  7348. // Verify response was compressed
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7352. // Verify pre-compression logger captured uncompressed content
  7353. EXPECT_EQ(test_content, pre_compression_body);
  7354. EXPECT_EQ("text/plain", pre_compression_content_type);
  7355. EXPECT_TRUE(pre_compression_content_encoding
  7356. .empty()); // No encoding header before compression
  7357. // Verify post-compression logger captured compressed content
  7358. EXPECT_NE(test_content,
  7359. post_compression_body); // Should be different after compression
  7360. EXPECT_EQ("text/plain", post_compression_content_type);
  7361. EXPECT_EQ("gzip", post_compression_content_encoding);
  7362. // Verify compressed content is smaller
  7363. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7364. }
  7365. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7366. const std::string test_content =
  7367. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7368. "3456789012345678901234567890";
  7369. std::string pre_compression_body;
  7370. std::string post_compression_body;
  7371. svr_.set_pre_compression_logger(
  7372. [&](const Request & /*req*/, const Response &res) {
  7373. pre_compression_body = res.body;
  7374. });
  7375. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7376. post_compression_body = res.body;
  7377. });
  7378. Headers headers;
  7379. headers.emplace("Accept-Encoding", "br");
  7380. auto res = cli_.Get("/compress", headers);
  7381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7384. // Verify pre-compression content is uncompressed
  7385. EXPECT_EQ(test_content, pre_compression_body);
  7386. // Verify post-compression content is compressed
  7387. EXPECT_NE(test_content, post_compression_body);
  7388. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7389. }
  7390. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7391. const std::string test_content =
  7392. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7393. "3456789012345678901234567890";
  7394. std::string pre_compression_body;
  7395. std::string post_compression_body;
  7396. svr_.set_pre_compression_logger(
  7397. [&](const Request & /*req*/, const Response &res) {
  7398. pre_compression_body = res.body;
  7399. });
  7400. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7401. post_compression_body = res.body;
  7402. });
  7403. // Request without compression (use /nocompress endpoint)
  7404. Headers headers;
  7405. auto res = cli_.Get("/nocompress", headers);
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7409. // Pre-compression logger should not be called when no compression is applied
  7410. EXPECT_TRUE(
  7411. pre_compression_body.empty()); // Pre-compression logger not called
  7412. EXPECT_EQ(
  7413. test_content,
  7414. post_compression_body); // Post-compression logger captures final content
  7415. }
  7416. TEST_F(ServerTest, LoggerSeesContentLength) {
  7417. size_t logged_content_length = 0;
  7418. std::string logged_content_length_header;
  7419. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7420. logged_content_length = res.content_length_;
  7421. logged_content_length_header = res.get_header_value("Content-Length");
  7422. });
  7423. auto res = cli_.Get("/nocompress");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ(res->body.size(), logged_content_length);
  7427. EXPECT_EQ(std::to_string(logged_content_length),
  7428. logged_content_length_header);
  7429. }
  7430. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7431. const std::string test_content =
  7432. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7433. "3456789012345678901234567890";
  7434. std::string pre_compression_body;
  7435. bool pre_logger_called = false;
  7436. // Set only pre-compression logger
  7437. svr_.set_pre_compression_logger(
  7438. [&](const Request & /*req*/, const Response &res) {
  7439. pre_compression_body = res.body;
  7440. pre_logger_called = true;
  7441. });
  7442. Headers headers;
  7443. headers.emplace("Accept-Encoding", "gzip");
  7444. auto res = cli_.Get("/compress", headers);
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7448. // Verify pre-compression logger was called
  7449. EXPECT_TRUE(pre_logger_called);
  7450. EXPECT_EQ(test_content, pre_compression_body);
  7451. }
  7452. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7453. {
  7454. // Test with Expect: 100-continue header - success case
  7455. // Server returns 100 Continue, client sends body, server returns 200 OK
  7456. Request req;
  7457. req.method = "POST";
  7458. req.path = "/post-large";
  7459. req.set_header("Expect", "100-continue");
  7460. req.body = LARGE_DATA;
  7461. Response res;
  7462. auto error = Error::Success;
  7463. cli_.set_keep_alive(true);
  7464. auto ret = cli_.send(req, res, error);
  7465. EXPECT_TRUE(ret);
  7466. EXPECT_EQ(StatusCode::OK_200, res.status);
  7467. EXPECT_EQ(LARGE_DATA, res.body);
  7468. }
  7469. {
  7470. // Test with Expect: 100-continue header - error case
  7471. // Client should not send the body when server returns an error
  7472. Request req;
  7473. req.method = "POST";
  7474. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7475. req.set_header("Expect", "100-continue");
  7476. req.body = LARGE_DATA;
  7477. Response res;
  7478. auto error = Error::Success;
  7479. auto start = std::chrono::high_resolution_clock::now();
  7480. cli_.set_keep_alive(true);
  7481. auto ret = cli_.send(req, res, error);
  7482. auto end = std::chrono::high_resolution_clock::now();
  7483. auto elapsed =
  7484. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7485. .count();
  7486. // With Expect: 100-continue, request completes successfully but with error
  7487. EXPECT_TRUE(ret);
  7488. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7489. EXPECT_EQ("close", res.get_header_value("Connection"));
  7490. EXPECT_FALSE(cli_.is_socket_open());
  7491. EXPECT_LE(elapsed, 2000);
  7492. }
  7493. {
  7494. // Send an extra GET request to ensure error recovery without hanging
  7495. Request req;
  7496. req.method = "GET";
  7497. req.path = "/hi";
  7498. auto start = std::chrono::high_resolution_clock::now();
  7499. auto res = cli_.send(req);
  7500. auto end = std::chrono::high_resolution_clock::now();
  7501. auto elapsed =
  7502. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7503. .count();
  7504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7505. EXPECT_EQ(StatusCode::OK_200, res->status);
  7506. EXPECT_EQ("Hello World!", res->body);
  7507. EXPECT_LE(elapsed, 500);
  7508. }
  7509. }
  7510. TEST(ZstdDecompressor, ChunkedDecompression) {
  7511. std::string data;
  7512. for (size_t i = 0; i < 32 * 1024; ++i) {
  7513. data.push_back(static_cast<char>('a' + i % 26));
  7514. }
  7515. std::string compressed_data;
  7516. {
  7517. httplib::detail::zstd_compressor compressor;
  7518. bool result = compressor.compress(
  7519. data.data(), data.size(),
  7520. /*last=*/true,
  7521. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7522. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7523. compressed_data_size);
  7524. return true;
  7525. });
  7526. ASSERT_TRUE(result);
  7527. }
  7528. std::string decompressed_data;
  7529. {
  7530. httplib::detail::zstd_decompressor decompressor;
  7531. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7532. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7533. size_t chunk_size = 130;
  7534. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7535. chunk_begin += chunk_size) {
  7536. size_t current_chunk_size =
  7537. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7538. bool result = decompressor.decompress(
  7539. compressed_data.data() + chunk_begin, current_chunk_size,
  7540. [&](const char *decompressed_data_chunk,
  7541. size_t decompressed_data_chunk_size) {
  7542. decompressed_data.insert(decompressed_data.size(),
  7543. decompressed_data_chunk,
  7544. decompressed_data_chunk_size);
  7545. return true;
  7546. });
  7547. ASSERT_TRUE(result);
  7548. }
  7549. }
  7550. ASSERT_EQ(data, decompressed_data);
  7551. }
  7552. TEST(ZstdDecompressor, Decompress) {
  7553. std::string original_text = "Compressed with ZSTD";
  7554. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7555. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7556. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7557. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7558. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7559. std::string decompressed_data;
  7560. {
  7561. httplib::detail::zstd_decompressor decompressor;
  7562. bool result = decompressor.decompress(
  7563. compressed_data.data(), compressed_data.size(),
  7564. [&](const char *decompressed_data_chunk,
  7565. size_t decompressed_data_chunk_size) {
  7566. decompressed_data.insert(decompressed_data.size(),
  7567. decompressed_data_chunk,
  7568. decompressed_data_chunk_size);
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(result);
  7572. }
  7573. ASSERT_EQ(original_text, decompressed_data);
  7574. }
  7575. #endif
  7576. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7577. // separate chunks so that the server sees each part in its own read(). Used to
  7578. // place a read boundary at a specific offset of a request body.
  7579. static bool send_request_in_parts(time_t read_timeout_sec,
  7580. const std::vector<std::string> &parts,
  7581. std::string *resp = nullptr,
  7582. int port = PORT) {
  7583. auto error = Error::Success;
  7584. auto client_sock = detail::create_client_socket(
  7585. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7586. /*connection_timeout_sec=*/5, 0,
  7587. /*read_timeout_sec=*/5, 0,
  7588. /*write_timeout_sec=*/5, 0, std::string(), error);
  7589. if (client_sock == INVALID_SOCKET) { return false; }
  7590. auto ret = detail::process_client_socket(
  7591. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7592. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7593. for (size_t i = 0; i < parts.size(); i++) {
  7594. const auto &part = parts[i];
  7595. if (part.size() !=
  7596. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7597. return false;
  7598. }
  7599. if (i + 1 < parts.size()) {
  7600. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7601. }
  7602. }
  7603. char buf[512];
  7604. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7605. while (line_reader.getline()) {
  7606. if (resp) { *resp += line_reader.ptr(); }
  7607. }
  7608. return true;
  7609. });
  7610. detail::close_socket(client_sock);
  7611. return ret;
  7612. }
  7613. // Sends a raw request to a server listening at HOST:PORT.
  7614. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7615. std::string *resp = nullptr, int port = PORT) {
  7616. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7617. }
  7618. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7619. Server svr;
  7620. std::string header_value;
  7621. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7622. header_value = req.get_header_value("foo");
  7623. res.set_content("ok", "text/plain");
  7624. });
  7625. thread t = thread([&] { svr.listen(HOST, PORT); });
  7626. auto se = detail::scope_exit([&] {
  7627. svr.stop();
  7628. t.join();
  7629. ASSERT_FALSE(svr.is_running());
  7630. });
  7631. svr.wait_until_ready();
  7632. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7633. // like characters are not treated the same - use vertical tab and escape.
  7634. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7635. "foo: \t \v bar \x1B\t \r\n"
  7636. "Connection: close\r\n"
  7637. "\r\n";
  7638. std::string res;
  7639. ASSERT_TRUE(send_request(5, req, &res));
  7640. EXPECT_EQ(header_value, "");
  7641. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7642. }
  7643. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7644. Server svr;
  7645. std::string received;
  7646. svr.Get("/order", [&](const Request &req, Response &res) {
  7647. received = entries_to_string(req.headers);
  7648. res.set_content("ok", "text/plain");
  7649. });
  7650. auto port = svr.bind_to_any_port(HOST);
  7651. thread t = thread([&] { svr.listen_after_bind(); });
  7652. auto se = detail::scope_exit([&] {
  7653. svr.stop();
  7654. t.join();
  7655. ASSERT_FALSE(svr.is_running());
  7656. });
  7657. svr.wait_until_ready();
  7658. const std::string req = "GET /order HTTP/1.1\r\n"
  7659. "X-First: 1\r\n"
  7660. "X-Dup: a\r\n"
  7661. "X-Second: 2\r\n"
  7662. "X-Dup: b\r\n"
  7663. "Connection: close\r\n"
  7664. "\r\n";
  7665. std::string res;
  7666. ASSERT_TRUE(send_request(5, req, &res, port));
  7667. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7668. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7669. }
  7670. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7671. Server svr;
  7672. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7673. res.set_header("Set-Cookie", "first=1");
  7674. res.set_header("X-Between", "y");
  7675. res.set_header("Set-Cookie", "second=2");
  7676. res.set_content("ok", "text/plain");
  7677. });
  7678. auto port = svr.bind_to_any_port(HOST);
  7679. thread t = thread([&] { svr.listen_after_bind(); });
  7680. auto se = detail::scope_exit([&] {
  7681. svr.stop();
  7682. t.join();
  7683. ASSERT_FALSE(svr.is_running());
  7684. });
  7685. svr.wait_until_ready();
  7686. Client cli(HOST, port);
  7687. auto res = cli.Get("/cookies");
  7688. ASSERT_TRUE(res);
  7689. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7690. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7691. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7692. }
  7693. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7694. Server svr;
  7695. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7696. auto i = new int(0);
  7697. res.set_header("Trailer", "X-Safe, X-Reflected");
  7698. res.set_chunked_content_provider(
  7699. "text/plain",
  7700. [i](size_t /*offset*/, DataSink &sink) {
  7701. if (*i == 0) {
  7702. sink.os << "body";
  7703. } else {
  7704. Headers trailer;
  7705. // A valid trailer that must survive.
  7706. trailer.emplace("X-Safe", "safe");
  7707. // Attacker-controlled value carrying CR/LF (response splitting).
  7708. trailer.emplace("X-Reflected",
  7709. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7710. // Attacker-controlled name carrying CR/LF.
  7711. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7712. sink.done_with_trailer(trailer);
  7713. }
  7714. (*i)++;
  7715. return true;
  7716. },
  7717. [i](bool /*success*/) { delete i; });
  7718. });
  7719. thread t = thread([&] { svr.listen(HOST, PORT); });
  7720. auto se = detail::scope_exit([&] {
  7721. svr.stop();
  7722. t.join();
  7723. ASSERT_FALSE(svr.is_running());
  7724. });
  7725. svr.wait_until_ready();
  7726. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7727. "Host: " + HOST +
  7728. "\r\n"
  7729. "Connection: close\r\n"
  7730. "\r\n";
  7731. std::string res;
  7732. ASSERT_TRUE(send_request(5, req, &res));
  7733. // The injected fields must not appear anywhere in the raw response.
  7734. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7735. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7736. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7737. // Invalid trailers are dropped entirely, matching set_header().
  7738. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7739. // The valid trailer still passes through.
  7740. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7741. }
  7742. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7743. Server svr;
  7744. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7745. // res.headers is a public field an application can populate directly,
  7746. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7747. // A valid header that must survive.
  7748. res.headers.emplace("X-Safe", "safe");
  7749. // Attacker-controlled value carrying CR/LF (response splitting).
  7750. res.headers.emplace("X-Reflected",
  7751. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7752. // Attacker-controlled name carrying CR/LF.
  7753. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7754. res.set_content("body", "text/plain");
  7755. });
  7756. thread t = thread([&] { svr.listen(HOST, PORT); });
  7757. auto se = detail::scope_exit([&] {
  7758. svr.stop();
  7759. t.join();
  7760. ASSERT_FALSE(svr.is_running());
  7761. });
  7762. svr.wait_until_ready();
  7763. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7764. "Host: " + HOST +
  7765. "\r\n"
  7766. "Connection: close\r\n"
  7767. "\r\n";
  7768. std::string res;
  7769. ASSERT_TRUE(send_request(5, req, &res));
  7770. // The injected fields must not appear anywhere in the raw response.
  7771. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7772. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7773. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7774. // Invalid headers are dropped entirely, matching set_header().
  7775. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7776. // The valid header still passes through.
  7777. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7778. }
  7779. // Forward declaration: in split builds split.py strips `inline` and moves the
  7780. // definition into httplib.cc, so detail::write_request_line is not visible from
  7781. // the public httplib.h. Re-declaring it here lets the tests link against the
  7782. // symbol in both header-only and split builds.
  7783. namespace httplib {
  7784. namespace detail {
  7785. ssize_t write_request_line(Stream &strm, const std::string &method,
  7786. const std::string &path);
  7787. } // namespace detail
  7788. } // namespace httplib
  7789. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7790. // A well-formed target is written verbatim.
  7791. {
  7792. detail::BufferStream strm;
  7793. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7794. EXPECT_GT(n, 0);
  7795. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7796. }
  7797. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7798. // otherwise it splits the request line and injects a header or a whole
  7799. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7800. // when path encoding is disabled.
  7801. const std::string evil_targets[] = {
  7802. "/a\r\nInjected: pwned",
  7803. "/a\rInjected",
  7804. "/a\nInjected",
  7805. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7806. };
  7807. for (const auto &evil : evil_targets) {
  7808. detail::BufferStream strm;
  7809. auto n = detail::write_request_line(strm, "GET", evil);
  7810. EXPECT_LT(n, 0);
  7811. EXPECT_TRUE(strm.get_buffer().empty());
  7812. }
  7813. }
  7814. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7815. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7816. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7817. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7818. // client must fail cleanly with Error::Write instead of putting a
  7819. // request-line-less, header-injecting request on the wire.
  7820. Server svr;
  7821. svr.Get("/a", [](const Request &, Response &res) {
  7822. res.set_content("ok", "text/plain");
  7823. });
  7824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7825. auto se = detail::scope_exit([&] {
  7826. svr.stop();
  7827. thread.join();
  7828. ASSERT_FALSE(svr.is_running());
  7829. });
  7830. svr.wait_until_ready();
  7831. {
  7832. Client cli(HOST, PORT);
  7833. cli.set_path_encode(false);
  7834. // The request is rejected before anything is written, so the connection
  7835. // stays silent and the subsequent response read would otherwise block for
  7836. // the full default read timeout. Shorten it -- the assertion is on the
  7837. // error, not the timeout.
  7838. cli.set_read_timeout(1, 0);
  7839. auto res = cli.Get("/a\r\nInjected: pwned");
  7840. EXPECT_FALSE(res);
  7841. EXPECT_EQ(Error::Write, res.error());
  7842. }
  7843. }
  7844. // Sends a raw request and verifies that there isn't a crash or exception.
  7845. static void test_raw_request(const std::string &req,
  7846. std::string *out = nullptr) {
  7847. Server svr;
  7848. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7849. res.set_content("ok", "text/plain");
  7850. });
  7851. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7852. res.set_content("ok", "text/plain");
  7853. });
  7854. svr.Get("/header_field_value_check",
  7855. [&](const Request & /*req*/, Response &res) {
  7856. res.set_content("ok", "text/plain");
  7857. });
  7858. svr.CustomRoute("PROPFIND", "/dav",
  7859. [&](const Request & /*req*/, Response &res) {
  7860. res.status = StatusCode::MultiStatus_207;
  7861. });
  7862. // Server read timeout must be longer than the client read timeout for the
  7863. // bug to reproduce, probably to force the server to process a request
  7864. // without a trailing blank line.
  7865. const time_t client_read_timeout_sec = 1;
  7866. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7867. bool listen_thread_ok = false;
  7868. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7869. auto se = detail::scope_exit([&] {
  7870. svr.stop();
  7871. t.join();
  7872. ASSERT_FALSE(svr.is_running());
  7873. EXPECT_TRUE(listen_thread_ok);
  7874. });
  7875. svr.wait_until_ready();
  7876. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7877. }
  7878. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7879. // A certain header line causes an exception if the header property is parsed
  7880. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7881. test_raw_request(
  7882. "GET /hi HTTP/1.1\r\n"
  7883. " : "
  7884. " "
  7885. " ");
  7886. }
  7887. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7888. // A certain header line causes an exception if the header property *name* is
  7889. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7890. // greedy matcher and requires backtracking when there are a lot of ":"
  7891. // characters.
  7892. // This occurs with libc++ but not libstdc++.
  7893. test_raw_request(
  7894. "GET /hi HTTP/1.1\r\n"
  7895. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7896. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7897. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7898. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7899. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7900. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7901. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7902. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7903. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7904. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7905. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7906. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7907. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7908. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7909. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7910. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7911. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7912. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7913. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7914. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7915. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7916. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7917. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7918. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7919. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7920. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7921. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7922. "&&&%%%");
  7923. }
  7924. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7925. // Make sure this doesn't crash the server.
  7926. // In a previous version of the header line regex, the "\r" rendered the line
  7927. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7928. // a new position where the leading white space ended and the field value
  7929. // began.
  7930. // The crash occurs with libc++ but not libstdc++.
  7931. test_raw_request("GET /hi HTTP/1.1\r\n"
  7932. "a:" +
  7933. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7934. "\r\n"
  7935. "\r\n");
  7936. }
  7937. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7938. std::string out;
  7939. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7940. "Content-Type: text/plain\r\n"
  7941. "Transfer-Encoding: chunked\r\n"
  7942. "\r\n"
  7943. "nothex\r\n",
  7944. &out);
  7945. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7946. }
  7947. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7948. std::string out;
  7949. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7950. "Content-Type: text/plain\r\n"
  7951. "Transfer-Encoding: chunked\r\n"
  7952. "\r\n"
  7953. "3\r\n"
  7954. "xyz\r\n"
  7955. "NaN\r\n",
  7956. &out);
  7957. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7958. }
  7959. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7960. std::string out;
  7961. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7962. "Content-Type: text/plain\r\n"
  7963. "Transfer-Encoding: chunked\r\n"
  7964. "\r\n"
  7965. // Length is too large for 64 bits.
  7966. "1ffffffffffffffff\r\n"
  7967. "xyz\r\n",
  7968. &out);
  7969. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7970. }
  7971. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7972. test_raw_request("GET /hi HTTP/1.1\r\n"
  7973. "Content-Type: text/plain\r\n\r");
  7974. }
  7975. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7976. std::string out;
  7977. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7979. }
  7980. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7981. Server svr;
  7982. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7983. EXPECT_TRUE(!req.remote_addr.empty());
  7984. });
  7985. thread t = thread([&] { svr.listen(HOST, PORT); });
  7986. auto se = detail::scope_exit([&] {
  7987. svr.stop();
  7988. t.join();
  7989. ASSERT_FALSE(svr.is_running());
  7990. });
  7991. svr.wait_until_ready();
  7992. // Send an invalid request line to trigger Bad Request
  7993. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7994. std::string out;
  7995. ASSERT_TRUE(send_request(5, bad_req, &out));
  7996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7997. }
  7998. // A custom method with neither Content-Length nor Transfer-Encoding must be
  7999. // answered right away rather than blocking on a read that waits for EOF.
  8000. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8001. std::string out;
  8002. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8003. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8004. }
  8005. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8006. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8007. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8008. for (const auto *method : methods) {
  8009. Server svr;
  8010. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8011. EXPECT_FALSE(svr.is_valid()) << method;
  8012. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8013. }
  8014. }
  8015. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8016. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8017. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8018. for (const auto *method : methods) {
  8019. Server svr;
  8020. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8021. EXPECT_FALSE(svr.is_valid()) << method;
  8022. }
  8023. }
  8024. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8025. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8026. "COPY", "MOVE", "LOCK",
  8027. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8028. Server svr;
  8029. for (const auto *method : methods) {
  8030. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8031. }
  8032. EXPECT_TRUE(svr.is_valid());
  8033. }
  8034. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8035. Server svr;
  8036. svr.CustomRoute("POST", "/x",
  8037. [](const Request &, Response &, const ContentReader &) {});
  8038. EXPECT_FALSE(svr.is_valid());
  8039. }
  8040. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8041. Server svr;
  8042. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8043. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8044. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8045. EXPECT_FALSE(svr.is_valid());
  8046. }
  8047. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8048. Server svr;
  8049. auto captured = Error::Success;
  8050. svr.set_error_logger(
  8051. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8052. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8053. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8054. }
  8055. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8056. std::string out;
  8057. std::string request(
  8058. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8059. test_raw_request(request, &out);
  8060. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8061. }
  8062. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8063. std::string out;
  8064. std::string request(
  8065. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8066. test_raw_request(request, &out);
  8067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8068. }
  8069. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8070. std::string out;
  8071. std::string request(
  8072. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8073. test_raw_request(request, &out);
  8074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8075. }
  8076. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8077. std::string out;
  8078. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8079. "Test: \r\n\r\n",
  8080. &out);
  8081. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8082. }
  8083. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8084. Server svr;
  8085. std::string x_custom;
  8086. std::string cookie;
  8087. std::string xff;
  8088. std::string x_unicode;
  8089. std::string x_iis;
  8090. svr.Get("/check", [&](const Request &req, Response &res) {
  8091. x_custom = req.get_header_value("X-Custom");
  8092. cookie = req.get_header_value("Cookie");
  8093. xff = req.get_header_value("X-Forwarded-For");
  8094. x_unicode = req.get_header_value("X-Unicode");
  8095. x_iis = req.get_header_value("X-IIS");
  8096. res.set_content("ok", "text/plain");
  8097. });
  8098. thread t = thread([&] { svr.listen(HOST, PORT); });
  8099. auto se = detail::scope_exit([&] {
  8100. svr.stop();
  8101. t.join();
  8102. ASSERT_FALSE(svr.is_running());
  8103. });
  8104. svr.wait_until_ready();
  8105. const std::string req = "GET /check HTTP/1.1\r\n"
  8106. "Host: localhost\r\n"
  8107. "X-Custom: a%0D%0AInjected: b\r\n"
  8108. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8109. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8110. "X-Unicode: %E3%81%82\r\n"
  8111. "X-IIS: %u00E9\r\n"
  8112. "Connection: close\r\n"
  8113. "\r\n";
  8114. std::string res;
  8115. ASSERT_TRUE(send_request(5, req, &res));
  8116. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8117. // Every value must be returned verbatim (wire form), with no decoding.
  8118. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8119. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8120. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8121. EXPECT_EQ("%E3%81%82", x_unicode);
  8122. EXPECT_EQ("%u00E9", x_iis);
  8123. }
  8124. // Applications that previously relied on automatic percent-decoding can
  8125. // reproduce the old behavior by explicitly calling decode_path_component()
  8126. // or, for RFC 3986 conformance, decode_uri_component().
  8127. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8128. Server svr;
  8129. std::string decoded;
  8130. svr.Get("/check", [&](const Request &req, Response &res) {
  8131. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8132. res.set_content("ok", "text/plain");
  8133. });
  8134. thread t = thread([&] { svr.listen(HOST, PORT); });
  8135. auto se = detail::scope_exit([&] {
  8136. svr.stop();
  8137. t.join();
  8138. ASSERT_FALSE(svr.is_running());
  8139. });
  8140. svr.wait_until_ready();
  8141. const std::string req = "GET /check HTTP/1.1\r\n"
  8142. "Host: localhost\r\n"
  8143. "X-Custom: hello%20world\r\n"
  8144. "Connection: close\r\n"
  8145. "\r\n";
  8146. std::string res;
  8147. ASSERT_TRUE(send_request(5, req, &res));
  8148. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8149. EXPECT_EQ("hello world", decoded);
  8150. }
  8151. // Regression test for #2033. Browsers send Referer values that include
  8152. // percent-encoded characters such as %0A inside the URL. Decoding the
  8153. // header value would either trip the post-decode CR/LF/NUL guard (the
  8154. // original bug, returning 400) or, after that guard was relaxed, silently
  8155. // store a literal LF — both unacceptable. The wire form must round-trip.
  8156. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8157. Server svr;
  8158. std::string referer;
  8159. svr.Get("/check", [&](const Request &req, Response &res) {
  8160. referer = req.get_header_value("Referer");
  8161. res.set_content("ok", "text/plain");
  8162. });
  8163. thread t = thread([&] { svr.listen(HOST, PORT); });
  8164. auto se = detail::scope_exit([&] {
  8165. svr.stop();
  8166. t.join();
  8167. ASSERT_FALSE(svr.is_running());
  8168. });
  8169. svr.wait_until_ready();
  8170. const std::string req = "GET /check HTTP/1.1\r\n"
  8171. "Host: localhost\r\n"
  8172. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8173. "Connection: close\r\n"
  8174. "\r\n";
  8175. std::string res;
  8176. ASSERT_TRUE(send_request(5, req, &res));
  8177. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8178. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8179. }
  8180. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8181. Server svr;
  8182. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8183. res.set_header("Cache-Control", "no-cache");
  8184. res.set_chunked_content_provider(
  8185. "text/event-stream", [](size_t offset, DataSink &sink) {
  8186. std::string s = "data:";
  8187. s += std::to_string(offset);
  8188. s += "\n\n";
  8189. auto ret = sink.write(s.data(), s.size());
  8190. EXPECT_TRUE(ret);
  8191. std::this_thread::sleep_for(std::chrono::seconds(1));
  8192. return true;
  8193. });
  8194. });
  8195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8196. svr.wait_until_ready();
  8197. Client client(HOST, PORT);
  8198. const Headers headers = {{"Accept", "text/event-stream"}};
  8199. auto get_thread = std::thread([&client, &headers]() {
  8200. auto res = client.Get(
  8201. "/events", headers,
  8202. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8203. });
  8204. auto se = detail::scope_exit([&] {
  8205. svr.stop();
  8206. get_thread.join();
  8207. listen_thread.join();
  8208. ASSERT_FALSE(svr.is_running());
  8209. });
  8210. // Give GET time to get a few messages.
  8211. std::this_thread::sleep_for(std::chrono::seconds(2));
  8212. }
  8213. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8214. httplib::Server svr;
  8215. svr.Post("/hi",
  8216. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8217. res.status = StatusCode::OK_200;
  8218. });
  8219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8220. svr.wait_until_ready();
  8221. Client cli(HOST, PORT);
  8222. auto res = cli.Post("/hi", "data", "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. svr.stop();
  8226. thread.join();
  8227. ASSERT_FALSE(svr.is_running());
  8228. res = cli.Post("/hi", "data", "text/plain");
  8229. ASSERT_FALSE(res);
  8230. }
  8231. TEST(ServerStopTest, ListenFailure) {
  8232. Server svr;
  8233. auto t = thread([&]() {
  8234. auto ret = svr.listen("????", PORT);
  8235. EXPECT_FALSE(ret);
  8236. });
  8237. svr.wait_until_ready();
  8238. svr.stop();
  8239. t.join();
  8240. }
  8241. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8242. TEST(ServerStopTest, Decommision) {
  8243. Server svr;
  8244. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8245. for (int i = 0; i < 4; i++) {
  8246. auto is_even = !(i % 2);
  8247. std::thread t{[&] {
  8248. try {
  8249. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8250. if (is_even) {
  8251. throw std::runtime_error("Some thing that happens to go wrong.");
  8252. }
  8253. svr.listen(HOST, PORT);
  8254. } catch (...) { svr.decommission(); }
  8255. }};
  8256. svr.wait_until_ready();
  8257. // Server is up
  8258. {
  8259. Client cli(HOST, PORT);
  8260. auto res = cli.Get("/hi");
  8261. if (is_even) {
  8262. EXPECT_FALSE(res);
  8263. } else {
  8264. EXPECT_TRUE(res);
  8265. EXPECT_EQ("hi...", res->body);
  8266. }
  8267. }
  8268. svr.stop();
  8269. t.join();
  8270. // Server is down...
  8271. {
  8272. Client cli(HOST, PORT);
  8273. auto res = cli.Get("/hi");
  8274. EXPECT_FALSE(res);
  8275. }
  8276. }
  8277. }
  8278. #endif
  8279. // Helper function for string body upload progress tests
  8280. template <typename SetupHandler, typename ClientCall>
  8281. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8282. ClientCall &&client_call,
  8283. const string &body) {
  8284. Server svr;
  8285. setup_handler(svr);
  8286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8287. auto se = detail::scope_exit([&] {
  8288. svr.stop();
  8289. t.join();
  8290. });
  8291. svr.wait_until_ready();
  8292. Client cli(HOST, PORT);
  8293. vector<uint64_t> progress_values;
  8294. bool progress_called = false;
  8295. auto res =
  8296. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8297. progress_values.push_back(current);
  8298. progress_called = true;
  8299. return true;
  8300. });
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(200, res->status);
  8303. EXPECT_TRUE(progress_called);
  8304. }
  8305. TEST(UploadProgressTest, PostStringBodyBasic) {
  8306. TestStringBodyUploadProgress(
  8307. [](Server &svr) {
  8308. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8309. res.set_content("received", "text/plain");
  8310. });
  8311. },
  8312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8313. return cli.Post("/test", body, "text/plain", progress_callback);
  8314. },
  8315. "test data for upload progress");
  8316. }
  8317. TEST(UploadProgressTest, PutStringBodyBasic) {
  8318. TestStringBodyUploadProgress(
  8319. [](Server &svr) {
  8320. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8321. res.set_content("put received", "text/plain");
  8322. });
  8323. },
  8324. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8325. return cli.Put("/test", body, "text/plain", progress_callback);
  8326. },
  8327. "put test data for upload progress");
  8328. }
  8329. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8330. TestStringBodyUploadProgress(
  8331. [](Server &svr) {
  8332. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8333. res.set_content("patch received", "text/plain");
  8334. });
  8335. },
  8336. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8337. return cli.Patch("/test", body, "text/plain", progress_callback);
  8338. },
  8339. "patch test data for upload progress");
  8340. }
  8341. // Helper function for content provider upload progress tests
  8342. template <typename SetupHandler, typename ClientCall>
  8343. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8344. ClientCall &&client_call) {
  8345. Server svr;
  8346. setup_handler(svr);
  8347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8348. auto se = detail::scope_exit([&] {
  8349. svr.stop();
  8350. t.join();
  8351. });
  8352. svr.wait_until_ready();
  8353. Client cli(HOST, PORT);
  8354. vector<uint64_t> progress_values;
  8355. auto res =
  8356. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8357. progress_values.push_back(current);
  8358. return true;
  8359. });
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(200, res->status);
  8362. EXPECT_FALSE(progress_values.empty());
  8363. }
  8364. TEST(UploadProgressTest, PostContentProviderProgress) {
  8365. TestContentProviderUploadProgress(
  8366. [](Server &svr) {
  8367. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8368. res.set_content("provider received", "text/plain");
  8369. });
  8370. },
  8371. [](Client &cli, UploadProgress progress_callback) {
  8372. return cli.Post(
  8373. "/test", 10,
  8374. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8375. sink.os << "test data";
  8376. return true;
  8377. },
  8378. "text/plain", progress_callback);
  8379. });
  8380. }
  8381. // Helper function for multipart upload progress tests
  8382. template <typename SetupHandler, typename ClientCall>
  8383. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8384. ClientCall &&client_call,
  8385. const string &endpoint) {
  8386. Server svr;
  8387. setup_handler(svr);
  8388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. });
  8393. svr.wait_until_ready();
  8394. Client cli(HOST, PORT);
  8395. vector<uint64_t> progress_values;
  8396. UploadFormDataItems items = {
  8397. {"field1", "value1", "", ""},
  8398. {"field2", "longer value for progress tracking test", "", ""},
  8399. {"file1", "file content data for upload progress", "test.txt",
  8400. "text/plain"}};
  8401. auto res = client_call(cli, endpoint, items,
  8402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8403. progress_values.push_back(current);
  8404. return true;
  8405. });
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(200, res->status);
  8408. EXPECT_FALSE(progress_values.empty());
  8409. }
  8410. TEST(UploadProgressTest, PostMultipartProgress) {
  8411. TestMultipartUploadProgress(
  8412. [](Server &svr) {
  8413. svr.Post("/multipart", [](const Request &req, Response &res) {
  8414. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8415. res.set_content("multipart received", "text/plain");
  8416. });
  8417. },
  8418. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8419. UploadProgress progress_callback) {
  8420. return cli.Post(endpoint, items, progress_callback);
  8421. },
  8422. "/multipart");
  8423. }
  8424. // Helper function for basic download progress tests
  8425. template <typename SetupHandler, typename ClientCall>
  8426. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8427. ClientCall &&client_call, const string &endpoint,
  8428. size_t expected_content_size) {
  8429. Server svr;
  8430. setup_handler(svr);
  8431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8432. auto se = detail::scope_exit([&] {
  8433. svr.stop();
  8434. t.join();
  8435. });
  8436. svr.wait_until_ready();
  8437. Client cli(HOST, PORT);
  8438. vector<uint64_t> progress_values;
  8439. auto res = client_call(cli, endpoint,
  8440. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8441. progress_values.push_back(current);
  8442. return true;
  8443. });
  8444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8445. EXPECT_EQ(200, res->status);
  8446. EXPECT_FALSE(progress_values.empty());
  8447. EXPECT_EQ(expected_content_size, res->body.size());
  8448. }
  8449. TEST(DownloadProgressTest, GetBasic) {
  8450. TestBasicDownloadProgress(
  8451. [](Server &svr) {
  8452. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8453. string content(1000, 'D');
  8454. res.set_content(content, "text/plain");
  8455. });
  8456. },
  8457. [](Client &cli, const string &endpoint,
  8458. DownloadProgress progress_callback) {
  8459. return cli.Get(endpoint, progress_callback);
  8460. },
  8461. "/download", 1000u);
  8462. }
  8463. // Helper function for content receiver download progress tests
  8464. template <typename SetupHandler, typename ClientCall>
  8465. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8466. ClientCall &&client_call,
  8467. const string &endpoint,
  8468. size_t expected_content_size) {
  8469. Server svr;
  8470. setup_handler(svr);
  8471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8472. auto se = detail::scope_exit([&] {
  8473. svr.stop();
  8474. t.join();
  8475. });
  8476. svr.wait_until_ready();
  8477. Client cli(HOST, PORT);
  8478. vector<uint64_t> progress_values;
  8479. string received_body;
  8480. auto res = client_call(
  8481. cli, endpoint,
  8482. [&](const char *data, size_t data_length) -> bool {
  8483. received_body.append(data, data_length);
  8484. return true;
  8485. },
  8486. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8487. progress_values.push_back(current);
  8488. return true;
  8489. });
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(200, res->status);
  8492. EXPECT_FALSE(progress_values.empty());
  8493. EXPECT_EQ(expected_content_size, received_body.size());
  8494. EXPECT_TRUE(res->body.empty());
  8495. }
  8496. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8497. TestContentReceiverDownloadProgress(
  8498. [](Server &svr) {
  8499. svr.Get("/download-receiver",
  8500. [](const Request & /*req*/, Response &res) {
  8501. string content(2000, 'R');
  8502. res.set_content(content, "text/plain");
  8503. });
  8504. },
  8505. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8506. DownloadProgress progress_callback) {
  8507. return cli.Get(endpoint, content_receiver, progress_callback);
  8508. },
  8509. "/download-receiver", 2000u);
  8510. }
  8511. TEST(StreamingTest, NoContentLengthStreaming) {
  8512. Server svr;
  8513. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8514. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8515. if (offset < 6) {
  8516. sink.os << (offset < 3 ? "a" : "b");
  8517. } else {
  8518. sink.done();
  8519. }
  8520. return true;
  8521. });
  8522. });
  8523. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8524. auto listen_se = detail::scope_exit([&] {
  8525. svr.stop();
  8526. listen_thread.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. });
  8529. svr.wait_until_ready();
  8530. Client client(HOST, PORT);
  8531. auto get_thread = std::thread([&client]() {
  8532. std::string s;
  8533. auto res =
  8534. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8535. s += std::string(data, len);
  8536. return true;
  8537. });
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. EXPECT_EQ("aaabbb", s);
  8541. });
  8542. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8543. // Give GET time to get a few messages.
  8544. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8545. }
  8546. TEST(MountTest, Unmount) {
  8547. Server svr;
  8548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. listen_thread.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. });
  8554. svr.wait_until_ready();
  8555. Client cli("localhost", PORT);
  8556. svr.set_mount_point("/mount2", "./www2");
  8557. auto res = cli.Get("/");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8560. res = cli.Get("/mount2/dir/test.html");
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. svr.set_mount_point("/", "./www");
  8564. res = cli.Get("/dir/");
  8565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8566. EXPECT_EQ(StatusCode::OK_200, res->status);
  8567. svr.remove_mount_point("/");
  8568. res = cli.Get("/dir/");
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8571. svr.remove_mount_point("/mount2");
  8572. res = cli.Get("/mount2/dir/test.html");
  8573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8575. }
  8576. TEST(MountTest, PathSegmentBoundary) {
  8577. Server svr;
  8578. svr.set_mount_point("/mount2", "./www2");
  8579. svr.set_mount_point("/", "./www");
  8580. auto port = svr.bind_to_any_port(HOST);
  8581. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8582. auto se = detail::scope_exit([&] {
  8583. svr.stop();
  8584. listen_thread.join();
  8585. ASSERT_FALSE(svr.is_running());
  8586. });
  8587. svr.wait_until_ready();
  8588. Client cli(HOST, port);
  8589. auto res = cli.Get("/mount2/dir/test.html");
  8590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. // "/mount2" must not match part-way through a path segment.
  8593. res = cli.Get("/mount2dir/test.html");
  8594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8596. // A mount point ending in '/' keeps matching every path below it.
  8597. res = cli.Get("/dir/test.html");
  8598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8599. EXPECT_EQ(StatusCode::OK_200, res->status);
  8600. }
  8601. TEST(MountTest, Redicect) {
  8602. Server svr;
  8603. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. listen_thread.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.set_mount_point("/", "./www");
  8610. svr.wait_until_ready();
  8611. Client cli("localhost", PORT);
  8612. auto res = cli.Get("/dir/");
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. res = cli.Get("/dir");
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8618. res = cli.Get("/file");
  8619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8620. EXPECT_EQ(StatusCode::OK_200, res->status);
  8621. res = cli.Get("/file/");
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8624. cli.set_follow_location(true);
  8625. res = cli.Get("/dir");
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. }
  8629. TEST(MountTest, MultibytesPathName) {
  8630. Server svr;
  8631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8632. auto se = detail::scope_exit([&] {
  8633. svr.stop();
  8634. listen_thread.join();
  8635. ASSERT_FALSE(svr.is_running());
  8636. });
  8637. svr.set_mount_point("/", "./www");
  8638. svr.wait_until_ready();
  8639. Client cli("localhost", PORT);
  8640. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8644. }
  8645. #ifdef _WIN32
  8646. // Issue #2435: mmap::open() must succeed even when another handle holds
  8647. // the file open for writing (e.g. an active log file).
  8648. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8649. const char *path = "mmap_concurrent_writer_test.txt";
  8650. const char *content = "hello";
  8651. {
  8652. std::ofstream f(path, std::ios::binary);
  8653. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8654. }
  8655. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8656. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8657. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8658. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8659. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8660. detail::mmap m(path);
  8661. ASSERT_TRUE(m.is_open());
  8662. EXPECT_EQ(strlen(content), m.size());
  8663. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8664. }
  8665. #endif
  8666. #ifndef _WIN32
  8667. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8668. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8669. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8670. TEST(MmapTest, FailedMappingIsNotOpen) {
  8671. const char *path = "./mmap_failed_mapping_test_dir";
  8672. ASSERT_EQ(0, ::mkdir(path, 0755));
  8673. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8674. detail::mmap m(path);
  8675. EXPECT_FALSE(m.is_open());
  8676. EXPECT_EQ(0U, m.size());
  8677. EXPECT_NE(static_cast<const void *>(m.data()),
  8678. static_cast<const void *>(MAP_FAILED));
  8679. }
  8680. #endif
  8681. TEST(KeepAliveTest, ReadTimeout) {
  8682. Server svr;
  8683. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8684. std::this_thread::sleep_for(std::chrono::seconds(2));
  8685. res.set_content("a", "text/plain");
  8686. });
  8687. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8688. res.set_content("b", "text/plain");
  8689. });
  8690. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. listen_thread.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. });
  8696. svr.wait_until_ready();
  8697. Client cli("localhost", PORT);
  8698. cli.set_keep_alive(true);
  8699. cli.set_read_timeout(std::chrono::seconds(1));
  8700. auto resa = cli.Get("/a");
  8701. ASSERT_FALSE(resa);
  8702. EXPECT_EQ(Error::Read, resa.error());
  8703. auto resb = cli.Get("/b");
  8704. ASSERT_TRUE(resb);
  8705. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8706. EXPECT_EQ("b", resb->body);
  8707. }
  8708. TEST(KeepAliveTest, MaxCount) {
  8709. size_t keep_alive_max_count = 3;
  8710. Server svr;
  8711. svr.set_keep_alive_max_count(keep_alive_max_count);
  8712. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8713. res.set_content("Hello World!", "text/plain");
  8714. });
  8715. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8716. auto se = detail::scope_exit([&] {
  8717. svr.stop();
  8718. listen_thread.join();
  8719. ASSERT_FALSE(svr.is_running());
  8720. });
  8721. svr.wait_until_ready();
  8722. Client cli(HOST, PORT);
  8723. cli.set_keep_alive(true);
  8724. for (size_t i = 0; i < 5; i++) {
  8725. auto result = cli.Get("/hi");
  8726. ASSERT_TRUE(result);
  8727. EXPECT_EQ(StatusCode::OK_200, result->status);
  8728. if (i == keep_alive_max_count - 1) {
  8729. EXPECT_EQ("close", result->get_header_value("Connection"));
  8730. } else {
  8731. EXPECT_FALSE(result->has_header("Connection"));
  8732. }
  8733. }
  8734. }
  8735. TEST(KeepAliveTest, Issue1041) {
  8736. Server svr;
  8737. svr.set_keep_alive_timeout(3);
  8738. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8739. res.set_content("Hello World!", "text/plain");
  8740. });
  8741. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8742. auto se = detail::scope_exit([&] {
  8743. svr.stop();
  8744. listen_thread.join();
  8745. ASSERT_FALSE(svr.is_running());
  8746. });
  8747. svr.wait_until_ready();
  8748. Client cli(HOST, PORT);
  8749. cli.set_keep_alive(true);
  8750. auto result = cli.Get("/hi");
  8751. ASSERT_TRUE(result);
  8752. EXPECT_EQ(StatusCode::OK_200, result->status);
  8753. std::this_thread::sleep_for(std::chrono::seconds(5));
  8754. result = cli.Get("/hi");
  8755. ASSERT_TRUE(result);
  8756. EXPECT_EQ(StatusCode::OK_200, result->status);
  8757. }
  8758. TEST(KeepAliveTest, Issue1959) {
  8759. Server svr;
  8760. svr.set_keep_alive_timeout(5);
  8761. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8762. res.set_content("a", "text/plain");
  8763. });
  8764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8765. auto se = detail::scope_exit([&] {
  8766. if (!svr.is_running()) return;
  8767. svr.stop();
  8768. listen_thread.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. Client cli("localhost", PORT);
  8773. cli.set_keep_alive(true);
  8774. using namespace std::chrono;
  8775. auto start = steady_clock::now();
  8776. cli.Get("/a");
  8777. svr.stop();
  8778. listen_thread.join();
  8779. auto end = steady_clock::now();
  8780. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8781. EXPECT_LT(elapsed, 5000);
  8782. }
  8783. #ifdef CPPHTTPLIB_SSL_ENABLED
  8784. TEST(KeepAliveTest, SSLClientReconnection) {
  8785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8786. ASSERT_TRUE(svr.is_valid());
  8787. svr.set_keep_alive_timeout(1);
  8788. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8789. res.set_content("Hello World!", "text/plain");
  8790. });
  8791. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8792. auto se = detail::scope_exit([&] {
  8793. svr.stop();
  8794. listen_thread.join();
  8795. ASSERT_FALSE(svr.is_running());
  8796. });
  8797. svr.wait_until_ready();
  8798. SSLClient cli(HOST, PORT);
  8799. cli.enable_server_certificate_verification(false);
  8800. cli.set_keep_alive(true);
  8801. auto result = cli.Get("/hi");
  8802. ASSERT_TRUE(result);
  8803. EXPECT_EQ(StatusCode::OK_200, result->status);
  8804. result = cli.Get("/hi");
  8805. ASSERT_TRUE(result);
  8806. EXPECT_EQ(StatusCode::OK_200, result->status);
  8807. std::this_thread::sleep_for(std::chrono::seconds(2));
  8808. // Recoonect
  8809. result = cli.Get("/hi");
  8810. ASSERT_TRUE(result);
  8811. EXPECT_EQ(StatusCode::OK_200, result->status);
  8812. result = cli.Get("/hi");
  8813. ASSERT_TRUE(result);
  8814. EXPECT_EQ(StatusCode::OK_200, result->status);
  8815. }
  8816. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8818. ASSERT_TRUE(svr.is_valid());
  8819. svr.set_keep_alive_timeout(1);
  8820. std::string content = "reconnect";
  8821. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8822. res.set_content("Hello World!", "text/plain");
  8823. });
  8824. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. listen_thread.join();
  8828. ASSERT_FALSE(svr.is_running());
  8829. });
  8830. svr.wait_until_ready();
  8831. SSLClient cli(HOST, PORT);
  8832. cli.enable_server_certificate_verification(false);
  8833. cli.set_keep_alive(true);
  8834. auto result = cli.Post(
  8835. "/hi", content.size(),
  8836. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8837. sink.write(content.c_str(), content.size());
  8838. return true;
  8839. },
  8840. "text/plain");
  8841. ASSERT_TRUE(result);
  8842. EXPECT_EQ(200, result->status);
  8843. std::this_thread::sleep_for(std::chrono::seconds(2));
  8844. // Recoonect
  8845. result = cli.Post(
  8846. "/hi", content.size(),
  8847. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8848. sink.write(content.c_str(), content.size());
  8849. return true;
  8850. },
  8851. "text/plain");
  8852. ASSERT_TRUE(result);
  8853. EXPECT_EQ(200, result->status);
  8854. result = cli.Post(
  8855. "/hi", content.size(),
  8856. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8857. sink.write(content.c_str(), content.size());
  8858. return true;
  8859. },
  8860. "text/plain");
  8861. ASSERT_TRUE(result);
  8862. EXPECT_EQ(200, result->status);
  8863. }
  8864. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8865. using namespace httplib::tls;
  8866. {
  8867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8868. ASSERT_TRUE(svr.is_valid());
  8869. svr.Get("/sni", [&](const Request &req, Response &res) {
  8870. std::string expected = req.sni();
  8871. EXPECT_EQ(expected, req.get_param_value("expected"));
  8872. res.set_content("ok", "text/plain");
  8873. });
  8874. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8875. auto se = detail::scope_exit([&] {
  8876. svr.stop();
  8877. listen_thread.join();
  8878. ASSERT_FALSE(svr.is_running());
  8879. });
  8880. svr.wait_until_ready();
  8881. {
  8882. SSLClient cli("localhost", PORT);
  8883. cli.enable_server_certificate_verification(false);
  8884. auto res = cli.Get("/sni?expected=localhost");
  8885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8886. }
  8887. {
  8888. SSLClient cli("::1", PORT);
  8889. cli.enable_server_certificate_verification(false);
  8890. auto res = cli.Get("/sni?expected=");
  8891. // NOTE: This may fail if the server is listening on IPv4 only
  8892. // (e.g., when localhost resolves to 127.0.0.1 only)
  8893. if (res) {
  8894. EXPECT_EQ(StatusCode::OK_200, res->status);
  8895. } else {
  8896. EXPECT_EQ(Error::Connection, res.error());
  8897. }
  8898. }
  8899. }
  8900. }
  8901. #endif
  8902. TEST(ClientProblemDetectionTest, ContentProvider) {
  8903. Server svr;
  8904. size_t content_length = 1024 * 1024;
  8905. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8906. res.set_content_provider(
  8907. content_length, "text/plain",
  8908. [&](size_t offset, size_t length, DataSink &sink) {
  8909. auto out_len = std::min(length, static_cast<size_t>(1024));
  8910. std::string out(out_len, '@');
  8911. sink.write(out.data(), out_len);
  8912. return offset < 4096;
  8913. },
  8914. [](bool success) { ASSERT_FALSE(success); });
  8915. });
  8916. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8917. res.set_content_provider(
  8918. 0, "text/plain",
  8919. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8920. EXPECT_TRUE(false);
  8921. return true;
  8922. },
  8923. [](bool success) { ASSERT_FALSE(success); });
  8924. });
  8925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8926. auto se = detail::scope_exit([&] {
  8927. svr.stop();
  8928. listen_thread.join();
  8929. ASSERT_FALSE(svr.is_running());
  8930. });
  8931. svr.wait_until_ready();
  8932. Client cli("localhost", PORT);
  8933. {
  8934. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8935. size_t /*data_length*/) { return false; });
  8936. ASSERT_FALSE(res);
  8937. }
  8938. {
  8939. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8940. size_t /*data_length*/) { return false; });
  8941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8942. }
  8943. }
  8944. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  8945. // A writer only has to assign `write`. The other three used to be left as
  8946. // empty std::functions, so a provider calling one threw
  8947. // std::bad_function_call out of the thread running it and took the whole
  8948. // process down.
  8949. DataSink sink;
  8950. std::string written;
  8951. sink.write = [&](const char *data, size_t data_len) {
  8952. written.append(data, data_len);
  8953. return true;
  8954. };
  8955. EXPECT_TRUE(sink.is_writable());
  8956. sink.done();
  8957. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  8958. EXPECT_TRUE(written.empty());
  8959. }
  8960. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  8961. // A sink that cannot carry trailers still has to finish.
  8962. DataSink sink;
  8963. auto done_count = 0;
  8964. sink.done = [&]() { done_count++; };
  8965. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  8966. EXPECT_EQ(1, done_count);
  8967. }
  8968. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  8969. Server svr;
  8970. const std::string body(4096, 'x');
  8971. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8972. res.set_content_provider(body.size(), "text/plain",
  8973. [&](size_t offset, size_t length, DataSink &sink) {
  8974. sink.write(body.data() + offset, length);
  8975. sink.done();
  8976. return true;
  8977. });
  8978. });
  8979. auto port = svr.bind_to_any_port(HOST);
  8980. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8981. auto se = detail::scope_exit([&] {
  8982. svr.stop();
  8983. listen_thread.join();
  8984. ASSERT_FALSE(svr.is_running());
  8985. });
  8986. svr.wait_until_ready();
  8987. Client cli(HOST, port);
  8988. auto res = cli.Get("/");
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ(StatusCode::OK_200, res->status);
  8991. EXPECT_EQ(body, res->body);
  8992. }
  8993. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  8994. Server svr;
  8995. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8996. res.set_content_provider(
  8997. 1024, "text/plain",
  8998. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8999. sink.write("hello", 5);
  9000. sink.done(); // short of the 1024 bytes the response promised
  9001. return true;
  9002. });
  9003. });
  9004. auto port = svr.bind_to_any_port(HOST);
  9005. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9006. auto se = detail::scope_exit([&] {
  9007. svr.stop();
  9008. listen_thread.join();
  9009. ASSERT_FALSE(svr.is_running());
  9010. });
  9011. svr.wait_until_ready();
  9012. Client cli(HOST, port);
  9013. cli.set_read_timeout(5, 0);
  9014. // The response is short of its Content-Length, so the client cannot read a
  9015. // complete body. What matters is that this returns at all: a no-op done()
  9016. // would leave the writer looping over a provider that never makes progress.
  9017. auto res = cli.Get("/");
  9018. EXPECT_FALSE(res);
  9019. }
  9020. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9021. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9022. // The compressed path builds the whole body before connecting, so this
  9023. // fails client-side and never reaches a server.
  9024. Client cli(HOST, PORT);
  9025. cli.set_compress(true);
  9026. auto res = cli.Post(
  9027. "/", 1024,
  9028. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9029. sink.write("hello", 5);
  9030. sink.done(); // short of the 1024 bytes the request announced
  9031. return true;
  9032. },
  9033. "text/plain");
  9034. ASSERT_FALSE(res);
  9035. EXPECT_EQ(Error::Write, res.error());
  9036. }
  9037. #endif
  9038. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9039. Server svr;
  9040. svr.set_error_handler([](Request const &, Response &res) -> void {
  9041. res.set_chunked_content_provider(
  9042. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9043. sink.os << "hello";
  9044. sink.os << "world";
  9045. sink.done();
  9046. return true;
  9047. });
  9048. });
  9049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. svr.stop();
  9052. listen_thread.join();
  9053. ASSERT_FALSE(svr.is_running());
  9054. });
  9055. svr.wait_until_ready();
  9056. Client cli("localhost", PORT);
  9057. auto res = cli.Get("/");
  9058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9060. EXPECT_EQ("helloworld", res->body);
  9061. }
  9062. TEST(LongPollingTest, ClientCloseDetection) {
  9063. Server svr;
  9064. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9065. res.set_chunked_content_provider(
  9066. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9067. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9068. sink.os << "hello";
  9069. auto count = 10;
  9070. while (count > 0 && sink.is_writable()) {
  9071. this_thread::sleep_for(chrono::milliseconds(10));
  9072. count--;
  9073. }
  9074. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9075. return true;
  9076. });
  9077. });
  9078. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9079. auto se = detail::scope_exit([&] {
  9080. svr.stop();
  9081. listen_thread.join();
  9082. ASSERT_FALSE(svr.is_running());
  9083. });
  9084. svr.wait_until_ready();
  9085. Client cli("localhost", PORT);
  9086. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9087. EXPECT_EQ("hello", string(data, data_length));
  9088. return false; // close the socket immediately.
  9089. });
  9090. ASSERT_FALSE(res);
  9091. }
  9092. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9093. Server svr;
  9094. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9095. res.set_chunked_content_provider(
  9096. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9097. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9098. sink.os << "hello";
  9099. EXPECT_TRUE(sink.os.good());
  9100. // Wait for the client to close the connection
  9101. auto count = 10;
  9102. while (count > 0 && sink.is_writable()) {
  9103. this_thread::sleep_for(chrono::milliseconds(10));
  9104. count--;
  9105. }
  9106. // After client disconnect, write repeatedly until the socket
  9107. // write actually fails (small writes may be absorbed by the
  9108. // kernel buffer)
  9109. std::string chunk(1024, 'x');
  9110. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9111. sink.os << chunk;
  9112. }
  9113. EXPECT_TRUE(sink.os.fail());
  9114. return true;
  9115. });
  9116. });
  9117. auto port = svr.bind_to_any_port("localhost");
  9118. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9119. auto se = detail::scope_exit([&] {
  9120. svr.stop();
  9121. listen_thread.join();
  9122. ASSERT_FALSE(svr.is_running());
  9123. });
  9124. svr.wait_until_ready();
  9125. Client cli("localhost", port);
  9126. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9127. EXPECT_EQ("hello", string(data, data_length));
  9128. return false; // close the socket immediately.
  9129. });
  9130. ASSERT_FALSE(res);
  9131. }
  9132. TEST(GetWithParametersTest, GetWithParameters) {
  9133. Server svr;
  9134. svr.Get("/", [&](const Request &req, Response &) {
  9135. EXPECT_EQ("world", req.get_param_value("hello"));
  9136. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9137. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9138. });
  9139. svr.Get("/params", [&](const Request &req, Response &) {
  9140. EXPECT_EQ("world", req.get_param_value("hello"));
  9141. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9142. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9143. });
  9144. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9145. EXPECT_EQ("resource-id", req.matches[1]);
  9146. EXPECT_EQ("foo", req.get_param_value("param1"));
  9147. EXPECT_EQ("bar", req.get_param_value("param2"));
  9148. });
  9149. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9150. EXPECT_EQ("user-id", req.path_params.at("id"));
  9151. EXPECT_EQ("foo", req.get_param_value("param1"));
  9152. EXPECT_EQ("bar", req.get_param_value("param2"));
  9153. });
  9154. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9155. auto se = detail::scope_exit([&] {
  9156. svr.stop();
  9157. listen_thread.join();
  9158. ASSERT_FALSE(svr.is_running());
  9159. });
  9160. svr.wait_until_ready();
  9161. {
  9162. Client cli(HOST, PORT);
  9163. Params params;
  9164. params.emplace("hello", "world");
  9165. params.emplace("hello2", "world2");
  9166. params.emplace("hello3", "world3");
  9167. auto res = cli.Get("/", params, Headers{});
  9168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9169. EXPECT_EQ(StatusCode::OK_200, res->status);
  9170. }
  9171. {
  9172. Client cli(HOST, PORT);
  9173. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9175. EXPECT_EQ(StatusCode::OK_200, res->status);
  9176. }
  9177. {
  9178. Client cli(HOST, PORT);
  9179. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9181. EXPECT_EQ(StatusCode::OK_200, res->status);
  9182. }
  9183. {
  9184. Client cli(HOST, PORT);
  9185. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9187. EXPECT_EQ(StatusCode::OK_200, res->status);
  9188. }
  9189. }
  9190. TEST(GetWithParametersTest, GetWithParameters2) {
  9191. Server svr;
  9192. svr.Get("/", [&](const Request &req, Response &res) {
  9193. auto text = req.get_param_value("hello");
  9194. res.set_content(text, "text/plain");
  9195. });
  9196. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9197. auto se = detail::scope_exit([&] {
  9198. svr.stop();
  9199. listen_thread.join();
  9200. ASSERT_FALSE(svr.is_running());
  9201. });
  9202. svr.wait_until_ready();
  9203. Client cli("localhost", PORT);
  9204. Params params;
  9205. params.emplace("hello", "world");
  9206. std::string body;
  9207. auto res = cli.Get("/", params, Headers{},
  9208. [&](const char *data, size_t data_length) {
  9209. body.append(data, data_length);
  9210. return true;
  9211. });
  9212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9213. EXPECT_EQ(StatusCode::OK_200, res->status);
  9214. EXPECT_EQ("world", body);
  9215. }
  9216. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9217. Server svr;
  9218. svr.Get("/search", [&](const Request &req, Response &res) {
  9219. auto q = req.get_param_value("q");
  9220. res.set_content(q, "text/plain");
  9221. });
  9222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9223. auto se = detail::scope_exit([&] {
  9224. svr.stop();
  9225. listen_thread.join();
  9226. ASSERT_FALSE(svr.is_running());
  9227. });
  9228. svr.wait_until_ready();
  9229. Client cli("localhost", PORT);
  9230. // Verify that Get(path, params) works without requiring Headers argument
  9231. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ(StatusCode::OK_200, res->status);
  9234. EXPECT_EQ("cpp-httplib", res->body);
  9235. }
  9236. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9237. auto host = "httpbingo.org";
  9238. auto path = std::string{"/range/32"};
  9239. #ifdef CPPHTTPLIB_SSL_ENABLED
  9240. SSLClient cli(host);
  9241. #else
  9242. Client cli(host);
  9243. #endif
  9244. cli.set_default_headers({make_range_header({{1, 10}})});
  9245. cli.set_connection_timeout(5);
  9246. {
  9247. auto res = cli.Get(path);
  9248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9249. EXPECT_EQ("bcdefghijk", res->body);
  9250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9251. }
  9252. {
  9253. auto res = cli.Get(path);
  9254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9255. EXPECT_EQ("bcdefghijk", res->body);
  9256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9257. }
  9258. }
  9259. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9260. Server svr;
  9261. svr.set_default_headers({{"Hello", "World"}});
  9262. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9263. res.set_content("ok", "text/plain");
  9264. });
  9265. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9266. auto se = detail::scope_exit([&] {
  9267. svr.stop();
  9268. listen_thread.join();
  9269. ASSERT_FALSE(svr.is_running());
  9270. });
  9271. svr.wait_until_ready();
  9272. Client cli("localhost", PORT);
  9273. auto res = cli.Get("/");
  9274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9275. EXPECT_EQ(StatusCode::OK_200, res->status);
  9276. EXPECT_EQ("ok", res->body);
  9277. EXPECT_EQ("World", res->get_header_value("Hello"));
  9278. }
  9279. #ifdef CPPHTTPLIB_SSL_ENABLED
  9280. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9282. ASSERT_TRUE(svr.is_valid());
  9283. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9284. std::this_thread::sleep_for(std::chrono::seconds(2));
  9285. res.set_content("a", "text/plain");
  9286. });
  9287. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9288. res.set_content("b", "text/plain");
  9289. });
  9290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9291. auto se = detail::scope_exit([&] {
  9292. svr.stop();
  9293. listen_thread.join();
  9294. ASSERT_FALSE(svr.is_running());
  9295. });
  9296. svr.wait_until_ready();
  9297. SSLClient cli("localhost", PORT);
  9298. cli.enable_server_certificate_verification(false);
  9299. cli.set_keep_alive(true);
  9300. cli.set_read_timeout(std::chrono::seconds(1));
  9301. auto resa = cli.Get("/a");
  9302. ASSERT_TRUE(!resa);
  9303. EXPECT_EQ(Error::Read, resa.error());
  9304. auto resb = cli.Get("/b");
  9305. ASSERT_TRUE(resb);
  9306. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9307. EXPECT_EQ("b", resb->body);
  9308. }
  9309. #endif
  9310. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9311. protected:
  9312. ServerTestWithAI_PASSIVE()
  9313. : cli_(HOST, PORT)
  9314. #ifdef CPPHTTPLIB_SSL_ENABLED
  9315. ,
  9316. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9317. #endif
  9318. {
  9319. #ifdef CPPHTTPLIB_SSL_ENABLED
  9320. cli_.enable_server_certificate_verification(false);
  9321. #endif
  9322. }
  9323. virtual void SetUp() {
  9324. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9325. res.set_content("Hello World!", "text/plain");
  9326. });
  9327. t_ = thread(
  9328. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9329. svr_.wait_until_ready();
  9330. }
  9331. virtual void TearDown() {
  9332. svr_.stop();
  9333. t_.join();
  9334. }
  9335. #ifdef CPPHTTPLIB_SSL_ENABLED
  9336. SSLClient cli_;
  9337. SSLServer svr_;
  9338. #else
  9339. Client cli_;
  9340. Server svr_;
  9341. #endif
  9342. thread t_;
  9343. };
  9344. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9345. auto res = cli_.Get("/hi");
  9346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9347. EXPECT_EQ(StatusCode::OK_200, res->status);
  9348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9349. EXPECT_EQ("Hello World!", res->body);
  9350. }
  9351. class ServerUpDownTest : public ::testing::Test {
  9352. protected:
  9353. ServerUpDownTest() : cli_(HOST, PORT) {}
  9354. virtual void SetUp() {
  9355. t_ = thread([&]() {
  9356. svr_.bind_to_any_port(HOST);
  9357. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9358. ASSERT_TRUE(svr_.listen_after_bind());
  9359. });
  9360. svr_.wait_until_ready();
  9361. }
  9362. virtual void TearDown() {
  9363. svr_.stop();
  9364. t_.join();
  9365. }
  9366. Client cli_;
  9367. Server svr_;
  9368. thread t_;
  9369. };
  9370. TEST_F(ServerUpDownTest, QuickStartStop) {
  9371. // Should not crash, especially when run with
  9372. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9373. }
  9374. class PayloadMaxLengthTest : public ::testing::Test {
  9375. protected:
  9376. PayloadMaxLengthTest()
  9377. : cli_(HOST, PORT)
  9378. #ifdef CPPHTTPLIB_SSL_ENABLED
  9379. ,
  9380. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9381. #endif
  9382. {
  9383. #ifdef CPPHTTPLIB_SSL_ENABLED
  9384. cli_.enable_server_certificate_verification(false);
  9385. #endif
  9386. }
  9387. virtual void SetUp() {
  9388. svr_.set_payload_max_length(8);
  9389. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9390. res.set_content("test", "text/plain");
  9391. });
  9392. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9393. svr_.wait_until_ready();
  9394. }
  9395. virtual void TearDown() {
  9396. svr_.stop();
  9397. t_.join();
  9398. }
  9399. #ifdef CPPHTTPLIB_SSL_ENABLED
  9400. SSLClient cli_;
  9401. SSLServer svr_;
  9402. #else
  9403. Client cli_;
  9404. Server svr_;
  9405. #endif
  9406. thread t_;
  9407. };
  9408. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9409. auto res = cli_.Post("/test", "123456789", "text/plain");
  9410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9411. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9412. res = cli_.Post("/test", "12345678", "text/plain");
  9413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9414. EXPECT_EQ(StatusCode::OK_200, res->status);
  9415. }
  9416. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9417. // Test chunked encoding with payload exceeding the 8-byte limit
  9418. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9419. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9421. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9422. }
  9423. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9424. // Test chunked encoding with payload within the 8-byte limit
  9425. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9426. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9428. EXPECT_EQ(StatusCode::OK_200, res->status);
  9429. }
  9430. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9431. // Test using send_request to send chunked data exceeding payload limit
  9432. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9433. "Host: " +
  9434. std::string(HOST) + ":" + std::to_string(PORT) +
  9435. "\r\n"
  9436. "Transfer-Encoding: chunked\r\n"
  9437. "Connection: close\r\n"
  9438. "\r\n"
  9439. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9440. "0123456789\r\n"
  9441. "0\r\n" // End chunk
  9442. "\r\n";
  9443. std::string response;
  9444. bool result = send_request(1, chunked_request, &response);
  9445. if (!result) {
  9446. // If send_request fails, it might be because the server closed the
  9447. // connection due to payload limit enforcement, which is acceptable
  9448. SUCCEED()
  9449. << "Server rejected oversized chunked request (connection closed)";
  9450. } else {
  9451. // If we got a response, check if it's an error response or connection was
  9452. // closed early Short response length indicates connection was closed due to
  9453. // payload limit
  9454. if (response.length() <= 10) {
  9455. SUCCEED() << "Server closed connection for oversized chunked request";
  9456. } else {
  9457. // Check for error status codes
  9458. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9459. response.find("Payload Too Large") != std::string::npos ||
  9460. response.find("400") != std::string::npos);
  9461. }
  9462. }
  9463. }
  9464. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9465. // Test request without Content-Length header exceeding payload limit
  9466. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9467. "Host: " +
  9468. std::string(HOST) + ":" +
  9469. std::to_string(PORT) +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. // Add payload exceeding the 8-byte limit
  9474. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9475. request_without_content_length += large_payload;
  9476. std::string response;
  9477. bool result = send_request(1, request_without_content_length, &response);
  9478. if (!result) {
  9479. // If send_request fails, server likely closed connection due to payload
  9480. // limit
  9481. SUCCEED() << "Server rejected oversized request without Content-Length "
  9482. "(connection closed)";
  9483. } else {
  9484. // Check if server responded with error or closed connection early
  9485. if (response.length() <= 10) {
  9486. SUCCEED() << "Server closed connection for oversized request without "
  9487. "Content-Length";
  9488. } else {
  9489. // Check for error status codes
  9490. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9491. response.find("Payload Too Large") != std::string::npos ||
  9492. response.find("400") != std::string::npos);
  9493. }
  9494. }
  9495. }
  9496. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9497. // Test request without Content-Length header within payload limit
  9498. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9499. "Host: " +
  9500. std::string(HOST) + ":" +
  9501. std::to_string(PORT) +
  9502. "\r\n"
  9503. "Connection: close\r\n"
  9504. "\r\n";
  9505. // Add payload within the 8-byte limit
  9506. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9507. request_without_content_length += small_payload;
  9508. std::string response;
  9509. bool result = send_request(1, request_without_content_length, &response);
  9510. // For requests without Content-Length, the server may have different behavior
  9511. // The key is that it should not reject due to payload limit for small
  9512. // payloads
  9513. if (result) {
  9514. // Check for any HTTP response (success or error, but not connection closed)
  9515. if (response.length() > 10) {
  9516. SUCCEED()
  9517. << "Server processed request without Content-Length within limit";
  9518. } else {
  9519. // Short response might indicate connection closed, which is acceptable
  9520. SUCCEED() << "Server closed connection for request without "
  9521. "Content-Length (acceptable behavior)";
  9522. }
  9523. } else {
  9524. // Connection failure might be due to protocol requirements
  9525. SUCCEED() << "Connection issue with request without Content-Length "
  9526. "(environment-specific)";
  9527. }
  9528. }
  9529. class LargePayloadMaxLengthTest : public ::testing::Test {
  9530. protected:
  9531. LargePayloadMaxLengthTest()
  9532. : cli_(HOST, PORT)
  9533. #ifdef CPPHTTPLIB_SSL_ENABLED
  9534. ,
  9535. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9536. #endif
  9537. {
  9538. #ifdef CPPHTTPLIB_SSL_ENABLED
  9539. cli_.enable_server_certificate_verification(false);
  9540. #endif
  9541. }
  9542. virtual void SetUp() {
  9543. // Set 10MB payload limit
  9544. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9545. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9546. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9547. res.set_content("Large payload test", "text/plain");
  9548. });
  9549. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9550. svr_.wait_until_ready();
  9551. }
  9552. virtual void TearDown() {
  9553. svr_.stop();
  9554. t_.join();
  9555. }
  9556. #ifdef CPPHTTPLIB_SSL_ENABLED
  9557. SSLClient cli_;
  9558. SSLServer svr_;
  9559. #else
  9560. Client cli_;
  9561. Server svr_;
  9562. #endif
  9563. thread t_;
  9564. };
  9565. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9566. // Test chunked encoding with payload within 10MB limit
  9567. std::string medium_payload(5 * 1024 * 1024,
  9568. 'A'); // 5MB payload, within 10MB limit
  9569. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9571. EXPECT_EQ(StatusCode::OK_200, res->status);
  9572. }
  9573. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9574. // Test chunked encoding with payload exceeding 10MB limit
  9575. std::string large_payload(12 * 1024 * 1024,
  9576. 'B'); // 12MB payload, exceeds 10MB limit
  9577. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9578. // Server may either return 413 or close the connection
  9579. if (res) {
  9580. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9581. } else {
  9582. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9583. }
  9584. }
  9585. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9586. // Test request without Content-Length header within 10MB limit
  9587. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9588. "Host: " +
  9589. std::string(HOST) + ":" +
  9590. std::to_string(PORT) +
  9591. "\r\n"
  9592. "Connection: close\r\n"
  9593. "\r\n";
  9594. // Add 1MB payload (within 10MB limit)
  9595. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9596. request_without_content_length += medium_payload;
  9597. std::string response;
  9598. bool result = send_request(5, request_without_content_length, &response);
  9599. if (result) {
  9600. // Should get a proper HTTP response for payloads within limit
  9601. if (response.length() > 10) {
  9602. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9603. "10MB limit";
  9604. } else {
  9605. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9606. "Content-Length)";
  9607. }
  9608. } else {
  9609. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9610. }
  9611. }
  9612. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9613. // Test request without Content-Length header exceeding 10MB limit
  9614. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9615. "Host: " +
  9616. std::string(HOST) + ":" +
  9617. std::to_string(PORT) +
  9618. "\r\n"
  9619. "Connection: close\r\n"
  9620. "\r\n";
  9621. // Add 12MB payload (exceeds 10MB limit)
  9622. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9623. request_without_content_length += large_payload;
  9624. std::string response;
  9625. bool result = send_request(10, request_without_content_length, &response);
  9626. if (!result) {
  9627. // Server should close connection due to payload limit
  9628. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9629. "(connection closed)";
  9630. } else {
  9631. // Check for error response
  9632. if (response.length() <= 10) {
  9633. SUCCEED()
  9634. << "Server closed connection for 12MB request exceeding 10MB limit";
  9635. } else {
  9636. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9637. response.find("Payload Too Large") != std::string::npos ||
  9638. response.find("400") != std::string::npos);
  9639. }
  9640. }
  9641. }
  9642. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9643. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9644. // path.
  9645. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9646. Server svr;
  9647. const size_t LIMIT = 64 * 1024; // 64KB
  9648. svr.set_payload_max_length(LIMIT);
  9649. size_t total = 0;
  9650. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9651. const ContentReader &content_reader) {
  9652. content_reader([&](const char * /*data*/, size_t len) {
  9653. total += len;
  9654. return true;
  9655. });
  9656. res.status = 200;
  9657. res.set_content("stream_ok", "text/plain");
  9658. });
  9659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. thread.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. // Prepare 256KB raw data and gzip-compress it
  9667. std::string raw(256 * 1024, 'A');
  9668. std::string gz;
  9669. {
  9670. z_stream zs{};
  9671. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9672. Z_DEFAULT_STRATEGY);
  9673. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9674. zs.avail_in = static_cast<uInt>(raw.size());
  9675. char outbuf[4096];
  9676. int ret;
  9677. do {
  9678. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9679. zs.avail_out = sizeof(outbuf);
  9680. ret = deflate(&zs, Z_FINISH);
  9681. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9682. } while (ret != Z_STREAM_END);
  9683. deflateEnd(&zs);
  9684. }
  9685. Client cli(HOST, PORT);
  9686. cli.set_connection_timeout(std::chrono::seconds(5));
  9687. Headers headers = {{"Content-Encoding", "gzip"}};
  9688. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9689. "application/octet-stream");
  9690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9691. // Server must reject oversized decompressed payloads with 413.
  9692. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9693. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9694. EXPECT_LE(total, LIMIT);
  9695. }
  9696. #ifndef CPPHTTPLIB_SSL_ENABLED
  9697. // For a request with neither Content-Length nor Transfer-Encoding, the
  9698. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9699. // compressed wire bytes straight to the ContentReader without ever routing
  9700. // them through the decompressor, so payload_max_length_ only bounded the
  9701. // compressed size on the wire, not the decompressed size.
  9702. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9703. Server svr;
  9704. const size_t LIMIT = 64 * 1024; // 64KB
  9705. svr.set_payload_max_length(LIMIT);
  9706. size_t total = 0;
  9707. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9708. const ContentReader &content_reader) {
  9709. content_reader([&](const char * /*data*/, size_t len) {
  9710. total += len;
  9711. return true;
  9712. });
  9713. res.status = 200;
  9714. res.set_content("stream_ok", "text/plain");
  9715. });
  9716. auto port = svr.bind_to_any_port(HOST);
  9717. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9718. auto se = detail::scope_exit([&] {
  9719. svr.stop();
  9720. thread.join();
  9721. ASSERT_FALSE(svr.is_running());
  9722. });
  9723. svr.wait_until_ready();
  9724. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9725. // StreamingGzipDecompression test above.
  9726. std::string raw(256 * 1024, 'A');
  9727. std::string gz;
  9728. {
  9729. httplib::detail::gzip_compressor compressor;
  9730. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9731. [&](const char *chunk, size_t len) {
  9732. gz.append(chunk, len);
  9733. return true;
  9734. });
  9735. ASSERT_TRUE(result);
  9736. }
  9737. // Send the gzip body over raw TCP with neither Content-Length nor
  9738. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9739. // kicks in.
  9740. std::string req = "POST /stream HTTP/1.1\r\n"
  9741. "Host: " +
  9742. std::string(HOST) + ":" + std::to_string(port) +
  9743. "\r\n"
  9744. "Content-Encoding: gzip\r\n"
  9745. "Connection: close\r\n"
  9746. "\r\n" +
  9747. gz;
  9748. std::string response;
  9749. ASSERT_TRUE(send_request(5, req, &response, port));
  9750. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9751. EXPECT_LE(total, LIMIT);
  9752. }
  9753. #endif
  9754. #endif
  9755. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9756. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9757. // the payload must be passed through untouched instead of being rejected.
  9758. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9759. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9760. Server svr;
  9761. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9762. res.set_content(body, "image/jpeg");
  9763. res.set_header("Content-Encoding", "UTF-8");
  9764. });
  9765. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9766. res.set_content(body, "image/jpeg");
  9767. res.set_header("Content-Encoding", "identity");
  9768. });
  9769. svr.Post("/echo", [](const Request &req, Response &res) {
  9770. res.set_content(req.body, "image/jpeg");
  9771. });
  9772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9773. auto se = detail::scope_exit([&] {
  9774. svr.stop();
  9775. t.join();
  9776. ASSERT_FALSE(svr.is_running());
  9777. });
  9778. svr.wait_until_ready();
  9779. Client cli(HOST, PORT);
  9780. {
  9781. auto res = cli.Get("/image");
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. EXPECT_EQ(body, res->body);
  9785. }
  9786. {
  9787. auto res = cli.Get("/identity");
  9788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9789. EXPECT_EQ(StatusCode::OK_200, res->status);
  9790. EXPECT_EQ(body, res->body);
  9791. }
  9792. {
  9793. // The same applies to a request body reaching the server.
  9794. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9795. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9797. EXPECT_EQ(StatusCode::OK_200, res->status);
  9798. EXPECT_EQ(body, res->body);
  9799. }
  9800. }
  9801. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9802. // gzip-encoded response even when the build has no zlib support.
  9803. static const char GZIPPED_HELLO_WORLD[] = {
  9804. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9805. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9806. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9807. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9808. // A content coding is a whole token, not something the field value merely
  9809. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9810. // as "fibre" look like Brotli, and turned a multi-coding value like
  9811. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9812. // it was never meant to see.
  9813. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9814. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9815. Server svr;
  9816. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9817. res.set_content(body, "image/jpeg");
  9818. res.set_header("Content-Encoding", "fibre");
  9819. });
  9820. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9821. res.set_content(body, "image/jpeg");
  9822. res.set_header("Content-Encoding", "gzip, br");
  9823. });
  9824. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9825. res.set_content(body, "image/jpeg");
  9826. res.set_header("Content-Encoding", "x-zstd-ish");
  9827. });
  9828. auto port = svr.bind_to_any_port(HOST);
  9829. thread t = thread([&]() { svr.listen_after_bind(); });
  9830. auto se = detail::scope_exit([&] {
  9831. svr.stop();
  9832. t.join();
  9833. ASSERT_FALSE(svr.is_running());
  9834. });
  9835. svr.wait_until_ready();
  9836. Client cli(HOST, port);
  9837. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9838. auto res = cli.Get(path);
  9839. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9840. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9841. // Not a coding we recognize, so the payload comes back untouched
  9842. EXPECT_EQ(body, res->body) << path;
  9843. }
  9844. }
  9845. // A content coding cpp-httplib recognizes but was not built with must be
  9846. // reported as such. Handing the still-compressed payload back to the caller
  9847. // would silently corrupt it.
  9848. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9849. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9850. Server svr;
  9851. // "image/jpeg" keeps the server from applying a content coding of its own,
  9852. // so the hand-crafted Content-Encoding below survives.
  9853. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9854. res.set_content(gzipped, "image/jpeg");
  9855. res.set_header("Content-Encoding", "gzip");
  9856. });
  9857. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9858. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9859. res.set_content(gzipped, "image/jpeg");
  9860. res.set_header("Content-Encoding", "GZIP");
  9861. });
  9862. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9863. auto se = detail::scope_exit([&] {
  9864. svr.stop();
  9865. t.join();
  9866. ASSERT_FALSE(svr.is_running());
  9867. });
  9868. svr.wait_until_ready();
  9869. Client cli(HOST, PORT);
  9870. {
  9871. auto res = cli.Get("/gzipped");
  9872. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ("Hello World!", res->body);
  9875. #else
  9876. ASSERT_FALSE(res);
  9877. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9878. #endif
  9879. }
  9880. {
  9881. // open_stream() must behave the same way.
  9882. auto handle = cli.open_stream("GET", "/gzipped");
  9883. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9884. ASSERT_TRUE(handle.is_valid());
  9885. std::string received;
  9886. char buf[256];
  9887. ssize_t n;
  9888. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9889. received.append(buf, static_cast<size_t>(n));
  9890. }
  9891. EXPECT_EQ("Hello World!", received);
  9892. #else
  9893. EXPECT_FALSE(handle.is_valid());
  9894. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9895. #endif
  9896. }
  9897. {
  9898. // A differently-cased coding must not be mistaken for an unknown one, or
  9899. // the body would be handed back still compressed.
  9900. auto res = cli.Get("/gzipped-uppercase");
  9901. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9903. EXPECT_EQ("Hello World!", res->body);
  9904. #else
  9905. ASSERT_FALSE(res);
  9906. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9907. #endif
  9908. }
  9909. }
  9910. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9911. // the same message as the comma-joined one, so both have to be read the same
  9912. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9913. // single gzip coding, and a body the sender says was encoded twice was handed
  9914. // back after one pass, still compressed but presented as decoded.
  9915. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9916. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9917. Server svr;
  9918. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9919. res.set_content(body, "image/jpeg");
  9920. res.headers.emplace("Content-Encoding", "gzip");
  9921. res.headers.emplace("Content-Encoding", "gzip");
  9922. });
  9923. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9924. res.set_content(body, "image/jpeg");
  9925. res.set_header("Content-Encoding", "gzip, gzip");
  9926. });
  9927. auto port = svr.bind_to_any_port(HOST);
  9928. thread t = thread([&]() { svr.listen_after_bind(); });
  9929. auto se = detail::scope_exit([&] {
  9930. svr.stop();
  9931. t.join();
  9932. ASSERT_FALSE(svr.is_running());
  9933. });
  9934. svr.wait_until_ready();
  9935. Client cli(HOST, port);
  9936. // Two codings is not something cpp-httplib decodes, so both representations
  9937. // take the pass-through path rather than one of them being gunzipped once.
  9938. for (const char *path : {"/split", "/joined"}) {
  9939. auto res = cli.Get(path);
  9940. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9941. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9942. EXPECT_EQ(body, res->body) << path;
  9943. }
  9944. }
  9945. // Regression test for DoS vulnerability: a malicious server sending a response
  9946. // without Content-Length header must not cause unbounded memory consumption on
  9947. // the client side. The client should stop reading after a reasonable limit,
  9948. // similar to the server-side set_payload_max_length protection.
  9949. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9950. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9951. #ifndef _WIN32
  9952. signal(SIGPIPE, SIG_IGN);
  9953. #endif
  9954. auto server_thread = std::thread([] {
  9955. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9956. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9957. default_socket_options(srv);
  9958. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9959. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9960. sockaddr_in addr{};
  9961. addr.sin_family = AF_INET;
  9962. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9963. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9964. int opt = 1;
  9965. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9966. #ifdef _WIN32
  9967. reinterpret_cast<const char *>(&opt),
  9968. #else
  9969. &opt,
  9970. #endif
  9971. sizeof(opt));
  9972. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9973. ::listen(srv, 1);
  9974. sockaddr_in cli_addr{};
  9975. socklen_t cli_len = sizeof(cli_addr);
  9976. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9977. if (cli != INVALID_SOCKET) {
  9978. char buf[4096];
  9979. ::recv(cli, buf, sizeof(buf), 0);
  9980. // Malicious response: no Content-Length, no chunked encoding
  9981. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9982. "Connection: close\r\n"
  9983. "\r\n";
  9984. ::send(cli,
  9985. #ifdef _WIN32
  9986. static_cast<const char *>(response_header.c_str()),
  9987. static_cast<int>(response_header.size()),
  9988. #else
  9989. response_header.c_str(), response_header.size(),
  9990. #endif
  9991. 0);
  9992. // Send 10MB of data
  9993. std::string chunk(64 * 1024, 'A');
  9994. size_t total_sent = 0;
  9995. while (total_sent < MALICIOUS_DATA_SIZE) {
  9996. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9997. auto sent = ::send(cli,
  9998. #ifdef _WIN32
  9999. static_cast<const char *>(chunk.c_str()),
  10000. static_cast<int>(to_send),
  10001. #else
  10002. chunk.c_str(), to_send,
  10003. #endif
  10004. 0);
  10005. if (sent <= 0) break;
  10006. total_sent += static_cast<size_t>(sent);
  10007. }
  10008. detail::close_socket(cli);
  10009. }
  10010. detail::close_socket(srv);
  10011. });
  10012. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10013. size_t total_read = 0;
  10014. {
  10015. Client cli("127.0.0.1", PORT + 2);
  10016. cli.set_read_timeout(5, 0);
  10017. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10018. auto stream = cli.open_stream("GET", "/malicious");
  10019. ASSERT_TRUE(stream.is_valid());
  10020. char buffer[64 * 1024];
  10021. ssize_t n;
  10022. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10023. total_read += static_cast<size_t>(n);
  10024. }
  10025. } // StreamHandle and Client destroyed here, closing the socket
  10026. server_thread.join();
  10027. // With set_payload_max_length, the client must stop reading before consuming
  10028. // all 10MB. The read loop should be cut off at or near the configured limit.
  10029. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10030. << "Client read " << total_read << " bytes, exceeding the configured "
  10031. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10032. }
  10033. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10034. // the entire response body without truncation.
  10035. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10036. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10037. #ifndef _WIN32
  10038. signal(SIGPIPE, SIG_IGN);
  10039. #endif
  10040. auto server_thread = std::thread([] {
  10041. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10042. default_socket_options(srv);
  10043. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10044. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10045. sockaddr_in addr{};
  10046. addr.sin_family = AF_INET;
  10047. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10048. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10049. int opt = 1;
  10050. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10051. #ifdef _WIN32
  10052. reinterpret_cast<const char *>(&opt),
  10053. #else
  10054. &opt,
  10055. #endif
  10056. sizeof(opt));
  10057. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10058. ::listen(srv, 1);
  10059. sockaddr_in cli_addr{};
  10060. socklen_t cli_len = sizeof(cli_addr);
  10061. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10062. if (cli != INVALID_SOCKET) {
  10063. char buf[4096];
  10064. ::recv(cli, buf, sizeof(buf), 0);
  10065. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10066. "Connection: close\r\n"
  10067. "\r\n";
  10068. ::send(cli,
  10069. #ifdef _WIN32
  10070. static_cast<const char *>(response_header.c_str()),
  10071. static_cast<int>(response_header.size()),
  10072. #else
  10073. response_header.c_str(), response_header.size(),
  10074. #endif
  10075. 0);
  10076. std::string chunk(64 * 1024, 'A');
  10077. size_t total_sent = 0;
  10078. while (total_sent < DATA_SIZE) {
  10079. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10080. auto sent = ::send(cli,
  10081. #ifdef _WIN32
  10082. static_cast<const char *>(chunk.c_str()),
  10083. static_cast<int>(to_send),
  10084. #else
  10085. chunk.c_str(), to_send,
  10086. #endif
  10087. 0);
  10088. if (sent <= 0) break;
  10089. total_sent += static_cast<size_t>(sent);
  10090. }
  10091. #ifdef _WIN32
  10092. ::shutdown(cli, SD_SEND);
  10093. #else
  10094. ::shutdown(cli, SHUT_WR);
  10095. #endif
  10096. // Drain until the client closes its end, ensuring all data is delivered
  10097. char drain[1024];
  10098. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10099. detail::close_socket(cli);
  10100. }
  10101. detail::close_socket(srv);
  10102. });
  10103. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10104. size_t total_read = 0;
  10105. {
  10106. Client cli("127.0.0.1", PORT + 2);
  10107. cli.set_read_timeout(5, 0);
  10108. cli.set_payload_max_length(0); // 0 means no limit
  10109. auto stream = cli.open_stream("GET", "/data");
  10110. ASSERT_TRUE(stream.is_valid());
  10111. char buffer[64 * 1024];
  10112. ssize_t n;
  10113. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10114. total_read += static_cast<size_t>(n);
  10115. }
  10116. }
  10117. server_thread.join();
  10118. EXPECT_EQ(total_read, DATA_SIZE)
  10119. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10120. << " bytes without truncation, but only read " << total_read << " bytes.";
  10121. }
  10122. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10123. // enormous Content-Length must not cause the client to pre-allocate a huge
  10124. // response body buffer. The reservation is capped at payload_max_length_, and
  10125. // the read itself fails when the body exceeds the limit.
  10126. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10127. #ifndef _WIN32
  10128. signal(SIGPIPE, SIG_IGN);
  10129. #endif
  10130. auto server_thread = std::thread([] {
  10131. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10132. default_socket_options(srv);
  10133. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10134. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10135. sockaddr_in addr{};
  10136. addr.sin_family = AF_INET;
  10137. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10138. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10139. int opt = 1;
  10140. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10141. #ifdef _WIN32
  10142. reinterpret_cast<const char *>(&opt),
  10143. #else
  10144. &opt,
  10145. #endif
  10146. sizeof(opt));
  10147. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10148. ::listen(srv, 1);
  10149. sockaddr_in cli_addr{};
  10150. socklen_t cli_len = sizeof(cli_addr);
  10151. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10152. if (cli != INVALID_SOCKET) {
  10153. char buf[4096];
  10154. ::recv(cli, buf, sizeof(buf), 0);
  10155. // Malicious response: claim a 20GB body but send only a tiny payload.
  10156. std::string response = "HTTP/1.1 200 OK\r\n"
  10157. "Content-Length: 20000000000\r\n"
  10158. "\r\n"
  10159. "abc";
  10160. ::send(cli,
  10161. #ifdef _WIN32
  10162. static_cast<const char *>(response.c_str()),
  10163. static_cast<int>(response.size()),
  10164. #else
  10165. response.c_str(), response.size(),
  10166. #endif
  10167. 0);
  10168. detail::close_socket(cli);
  10169. }
  10170. detail::close_socket(srv);
  10171. });
  10172. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10173. {
  10174. Client cli("127.0.0.1", PORT + 2);
  10175. cli.set_read_timeout(5, 0);
  10176. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10177. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10178. // (server claims more bytes than payload_max_length permits), but it must
  10179. // not exhaust memory before getting there.
  10180. auto res = cli.Get("/malicious");
  10181. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10182. }
  10183. server_thread.join();
  10184. }
  10185. // Verify that content_receiver bypasses the default payload_max_length,
  10186. // allowing streaming downloads larger than 100MB without requiring an explicit
  10187. // set_payload_max_length call.
  10188. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10189. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10190. #ifndef _WIN32
  10191. signal(SIGPIPE, SIG_IGN);
  10192. #endif
  10193. auto server_thread = std::thread([] {
  10194. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10195. default_socket_options(srv);
  10196. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10197. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10198. sockaddr_in addr{};
  10199. addr.sin_family = AF_INET;
  10200. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10201. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10202. int opt = 1;
  10203. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10204. #ifdef _WIN32
  10205. reinterpret_cast<const char *>(&opt),
  10206. #else
  10207. &opt,
  10208. #endif
  10209. sizeof(opt));
  10210. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10211. ::listen(srv, 1);
  10212. sockaddr_in cli_addr{};
  10213. socklen_t cli_len = sizeof(cli_addr);
  10214. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10215. if (cli != INVALID_SOCKET) {
  10216. char buf[4096];
  10217. ::recv(cli, buf, sizeof(buf), 0);
  10218. // Response with Content-Length larger than default 100MB limit
  10219. auto content_length = std::to_string(DATA_SIZE);
  10220. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10221. "Content-Length: " +
  10222. content_length +
  10223. "\r\n"
  10224. "Connection: close\r\n"
  10225. "\r\n";
  10226. ::send(cli,
  10227. #ifdef _WIN32
  10228. static_cast<const char *>(response_header.c_str()),
  10229. static_cast<int>(response_header.size()),
  10230. #else
  10231. response_header.c_str(), response_header.size(),
  10232. #endif
  10233. 0);
  10234. std::string chunk(64 * 1024, 'A');
  10235. size_t total_sent = 0;
  10236. while (total_sent < DATA_SIZE) {
  10237. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10238. auto sent = ::send(cli,
  10239. #ifdef _WIN32
  10240. static_cast<const char *>(chunk.c_str()),
  10241. static_cast<int>(to_send),
  10242. #else
  10243. chunk.c_str(), to_send,
  10244. #endif
  10245. 0);
  10246. if (sent <= 0) break;
  10247. total_sent += static_cast<size_t>(sent);
  10248. }
  10249. detail::close_socket(cli);
  10250. }
  10251. detail::close_socket(srv);
  10252. });
  10253. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10254. size_t total_received = 0;
  10255. {
  10256. Client cli("127.0.0.1", PORT + 2);
  10257. cli.set_read_timeout(10, 0);
  10258. // Do NOT call set_payload_max_length — use the default 100MB limit
  10259. auto res =
  10260. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10261. total_received += data_length;
  10262. return true;
  10263. });
  10264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10265. EXPECT_EQ(StatusCode::OK_200, res->status);
  10266. }
  10267. server_thread.join();
  10268. EXPECT_EQ(total_received, DATA_SIZE)
  10269. << "With content_receiver, the client should read all " << DATA_SIZE
  10270. << " bytes despite the default 100MB payload_max_length, but only read "
  10271. << total_received << " bytes.";
  10272. }
  10273. // Verify that an explicit set_payload_max_length smaller than the response is
  10274. // enforced even when a content_receiver is used.
  10275. TEST(ClientVulnerabilityTest,
  10276. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10277. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10278. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10279. #ifndef _WIN32
  10280. signal(SIGPIPE, SIG_IGN);
  10281. #endif
  10282. auto server_thread = std::thread([] {
  10283. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10284. default_socket_options(srv);
  10285. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10286. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10287. sockaddr_in addr{};
  10288. addr.sin_family = AF_INET;
  10289. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10290. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10291. int opt = 1;
  10292. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10293. #ifdef _WIN32
  10294. reinterpret_cast<const char *>(&opt),
  10295. #else
  10296. &opt,
  10297. #endif
  10298. sizeof(opt));
  10299. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10300. ::listen(srv, 1);
  10301. sockaddr_in cli_addr{};
  10302. socklen_t cli_len = sizeof(cli_addr);
  10303. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10304. if (cli != INVALID_SOCKET) {
  10305. char buf[4096];
  10306. ::recv(cli, buf, sizeof(buf), 0);
  10307. auto content_length = std::to_string(DATA_SIZE);
  10308. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10309. "Content-Length: " +
  10310. content_length +
  10311. "\r\n"
  10312. "Connection: close\r\n"
  10313. "\r\n";
  10314. ::send(cli,
  10315. #ifdef _WIN32
  10316. static_cast<const char *>(response_header.c_str()),
  10317. static_cast<int>(response_header.size()),
  10318. #else
  10319. response_header.c_str(), response_header.size(),
  10320. #endif
  10321. 0);
  10322. std::string chunk(64 * 1024, 'A');
  10323. size_t total_sent = 0;
  10324. while (total_sent < DATA_SIZE) {
  10325. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10326. auto sent = ::send(cli,
  10327. #ifdef _WIN32
  10328. static_cast<const char *>(chunk.c_str()),
  10329. static_cast<int>(to_send),
  10330. #else
  10331. chunk.c_str(), to_send,
  10332. #endif
  10333. 0);
  10334. if (sent <= 0) break;
  10335. total_sent += static_cast<size_t>(sent);
  10336. }
  10337. detail::close_socket(cli);
  10338. }
  10339. detail::close_socket(srv);
  10340. });
  10341. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10342. size_t total_received = 0;
  10343. {
  10344. Client cli("127.0.0.1", PORT + 2);
  10345. cli.set_read_timeout(10, 0);
  10346. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10347. auto res =
  10348. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10349. total_received += data_length;
  10350. return true;
  10351. });
  10352. // Should fail because 200MB exceeds the explicit 150MB limit
  10353. EXPECT_FALSE(res);
  10354. }
  10355. server_thread.join();
  10356. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10357. << "Client with content_receiver should respect the explicit "
  10358. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10359. << total_received << " bytes.";
  10360. }
  10361. // Verify that an explicit set_payload_max_length larger than the response
  10362. // allows the content_receiver to read all data successfully.
  10363. TEST(ClientVulnerabilityTest,
  10364. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10365. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10366. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10367. #ifndef _WIN32
  10368. signal(SIGPIPE, SIG_IGN);
  10369. #endif
  10370. auto server_thread = std::thread([] {
  10371. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10372. default_socket_options(srv);
  10373. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10374. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10375. sockaddr_in addr{};
  10376. addr.sin_family = AF_INET;
  10377. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10379. int opt = 1;
  10380. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10381. #ifdef _WIN32
  10382. reinterpret_cast<const char *>(&opt),
  10383. #else
  10384. &opt,
  10385. #endif
  10386. sizeof(opt));
  10387. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10388. ::listen(srv, 1);
  10389. sockaddr_in cli_addr{};
  10390. socklen_t cli_len = sizeof(cli_addr);
  10391. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10392. if (cli != INVALID_SOCKET) {
  10393. char buf[4096];
  10394. ::recv(cli, buf, sizeof(buf), 0);
  10395. auto content_length = std::to_string(DATA_SIZE);
  10396. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10397. "Content-Length: " +
  10398. content_length +
  10399. "\r\n"
  10400. "Connection: close\r\n"
  10401. "\r\n";
  10402. ::send(cli,
  10403. #ifdef _WIN32
  10404. static_cast<const char *>(response_header.c_str()),
  10405. static_cast<int>(response_header.size()),
  10406. #else
  10407. response_header.c_str(), response_header.size(),
  10408. #endif
  10409. 0);
  10410. std::string chunk(64 * 1024, 'A');
  10411. size_t total_sent = 0;
  10412. while (total_sent < DATA_SIZE) {
  10413. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10414. auto sent = ::send(cli,
  10415. #ifdef _WIN32
  10416. static_cast<const char *>(chunk.c_str()),
  10417. static_cast<int>(to_send),
  10418. #else
  10419. chunk.c_str(), to_send,
  10420. #endif
  10421. 0);
  10422. if (sent <= 0) break;
  10423. total_sent += static_cast<size_t>(sent);
  10424. }
  10425. #ifdef _WIN32
  10426. ::shutdown(cli, SD_SEND);
  10427. #else
  10428. ::shutdown(cli, SHUT_WR);
  10429. #endif
  10430. char drain[1024];
  10431. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10432. detail::close_socket(cli);
  10433. }
  10434. detail::close_socket(srv);
  10435. });
  10436. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10437. size_t total_received = 0;
  10438. {
  10439. Client cli("127.0.0.1", PORT + 2);
  10440. cli.set_read_timeout(10, 0);
  10441. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10442. auto res =
  10443. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10444. total_received += data_length;
  10445. return true;
  10446. });
  10447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10448. EXPECT_EQ(StatusCode::OK_200, res->status);
  10449. }
  10450. server_thread.join();
  10451. EXPECT_EQ(total_received, DATA_SIZE)
  10452. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10453. << " bytes (larger than " << DATA_SIZE
  10454. << " bytes response), content_receiver should read all data, but only "
  10455. "read "
  10456. << total_received << " bytes.";
  10457. }
  10458. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10459. // Regression test for "zip bomb" attack on the client side: a malicious server
  10460. // sends a small gzip-compressed response that decompresses to a huge payload.
  10461. // The client must enforce payload_max_length on the decompressed size.
  10462. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10463. constexpr size_t DECOMPRESSED_SIZE =
  10464. 10 * 1024 * 1024; // 10MB after decompression
  10465. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10466. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10467. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10468. std::string compressed;
  10469. {
  10470. httplib::detail::gzip_compressor compressor;
  10471. bool ok =
  10472. compressor.compress(uncompressed.data(), uncompressed.size(),
  10473. /*last=*/true, [&](const char *buf, size_t len) {
  10474. compressed.append(buf, len);
  10475. return true;
  10476. });
  10477. ASSERT_TRUE(ok);
  10478. }
  10479. // Sanity: compressed data should be much smaller than the decompressed size
  10480. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10481. #ifndef _WIN32
  10482. signal(SIGPIPE, SIG_IGN);
  10483. #endif
  10484. // Set up the listening socket in the main thread so the server is guaranteed
  10485. // to be ready before the client connects (eliminates race condition).
  10486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10487. default_socket_options(srv);
  10488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10489. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10490. sockaddr_in addr{};
  10491. addr.sin_family = AF_INET;
  10492. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10493. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10494. int opt = 1;
  10495. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10496. #ifdef _WIN32
  10497. reinterpret_cast<const char *>(&opt),
  10498. #else
  10499. &opt,
  10500. #endif
  10501. sizeof(opt));
  10502. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10503. ASSERT_EQ(0, ::listen(srv, 1));
  10504. auto server_thread = std::thread([&compressed, srv] {
  10505. sockaddr_in cli_addr{};
  10506. socklen_t cli_len = sizeof(cli_addr);
  10507. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10508. if (cli != INVALID_SOCKET) {
  10509. // Read the full HTTP request (until \r\n\r\n)
  10510. char buf[4096];
  10511. size_t total = 0;
  10512. while (total < sizeof(buf)) {
  10513. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10514. if (n <= 0) break;
  10515. total += static_cast<size_t>(n);
  10516. // Check for end of headers
  10517. if (total >= 4) {
  10518. std::string req(buf, total);
  10519. if (req.find("\r\n\r\n") != std::string::npos) break;
  10520. }
  10521. }
  10522. // Malicious response: gzip-compressed body, no Content-Length
  10523. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10524. "Content-Encoding: gzip\r\n"
  10525. "Connection: close\r\n"
  10526. "\r\n";
  10527. ::send(cli,
  10528. #ifdef _WIN32
  10529. static_cast<const char *>(response_header.c_str()),
  10530. static_cast<int>(response_header.size()),
  10531. #else
  10532. response_header.c_str(), response_header.size(),
  10533. #endif
  10534. 0);
  10535. // Send the compressed payload (small on the wire, huge when decompressed)
  10536. size_t total_sent = 0;
  10537. while (total_sent < compressed.size()) {
  10538. auto to_send = std::min(compressed.size() - total_sent,
  10539. static_cast<size_t>(64 * 1024));
  10540. auto sent =
  10541. ::send(cli,
  10542. #ifdef _WIN32
  10543. static_cast<const char *>(compressed.c_str() + total_sent),
  10544. static_cast<int>(to_send),
  10545. #else
  10546. compressed.c_str() + total_sent, to_send,
  10547. #endif
  10548. 0);
  10549. if (sent <= 0) break;
  10550. total_sent += static_cast<size_t>(sent);
  10551. }
  10552. detail::close_socket(cli);
  10553. }
  10554. });
  10555. auto se = detail::scope_exit([&] {
  10556. detail::close_socket(srv);
  10557. server_thread.join();
  10558. });
  10559. size_t total_decompressed = 0;
  10560. {
  10561. Client cli("127.0.0.1", PORT + 3);
  10562. cli.set_read_timeout(5, 0);
  10563. cli.set_decompress(true);
  10564. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10565. auto stream = cli.open_stream("GET", "/zipbomb");
  10566. ASSERT_TRUE(stream.is_valid());
  10567. char buffer[64 * 1024];
  10568. ssize_t n;
  10569. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10570. total_decompressed += static_cast<size_t>(n);
  10571. }
  10572. }
  10573. // The decompressed size must be capped by payload_max_length. Without
  10574. // protection, the client would decompress the full 10MB from a tiny
  10575. // compressed payload, enabling a zip bomb DoS attack.
  10576. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10577. << "Client decompressed " << total_decompressed
  10578. << " bytes from a gzip response. The decompressed size should be "
  10579. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10580. }
  10581. #endif
  10582. TEST(HostAndPortPropertiesTest, NoSSL) {
  10583. httplib::Client cli("www.google.com", 1234);
  10584. ASSERT_EQ("www.google.com", cli.host());
  10585. ASSERT_EQ(1234, cli.port());
  10586. }
  10587. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10588. httplib::Client cli("www.google.com:1234");
  10589. ASSERT_EQ("www.google.com", cli.host());
  10590. ASSERT_EQ(1234, cli.port());
  10591. }
  10592. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10593. // Port number that overflows int — should not crash, client becomes invalid
  10594. httplib::Client cli("http://www.google.com:99999999999999999999");
  10595. ASSERT_FALSE(cli.is_valid());
  10596. }
  10597. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10598. // Port 99999 exceeds valid range (1-65535) — should not crash
  10599. httplib::Client cli("http://www.google.com:99999");
  10600. ASSERT_FALSE(cli.is_valid());
  10601. }
  10602. #ifdef CPPHTTPLIB_SSL_ENABLED
  10603. TEST(HostAndPortPropertiesTest, SSL) {
  10604. httplib::SSLClient cli("www.google.com");
  10605. ASSERT_EQ("www.google.com", cli.host());
  10606. ASSERT_EQ(443, cli.port());
  10607. }
  10608. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10609. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10610. std::string cert;
  10611. read_file(CA_CERT_FILE, cert);
  10612. httplib::SSLClient httplib_client("www.google.com");
  10613. // Load CA store first time
  10614. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10615. // Load CA store second time (update)
  10616. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10617. // Verify client is still valid and can make connections
  10618. httplib_client.enable_server_certificate_verification(true);
  10619. auto res = httplib_client.Get("/");
  10620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10621. // Google may return 200 or 301 depending on various factors
  10622. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10623. res->status == StatusCode::MovedPermanently_301);
  10624. }
  10625. TEST(SSLClientTest, ServerNameIndication_Online) {
  10626. auto host = "httpbingo.org";
  10627. auto path = std::string{"/get"};
  10628. SSLClient cli(host, 443);
  10629. auto res = cli.Get(path);
  10630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10631. ASSERT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10634. // Use a site that will cause SSL verification failure due to self-signed cert
  10635. SSLClient cli("self-signed.badssl.com", 443);
  10636. cli.enable_server_certificate_verification(true);
  10637. auto res = cli.Get("/");
  10638. ASSERT_TRUE(!res);
  10639. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10640. // Verify backend error is captured for SSLServerVerification
  10641. // This occurs when certificate verification fails
  10642. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10643. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10644. EXPECT_NE(0UL, res.ssl_backend_error());
  10645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10646. // For OpenSSL, ssl_error is 0 for verification errors
  10647. EXPECT_EQ(0, res.ssl_error());
  10648. #if !defined(_WIN32) || \
  10649. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10650. // On non-Windows or when Windows Schannel is disabled, the error comes
  10651. // from OpenSSL's verification
  10652. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10653. res.ssl_backend_error());
  10654. #endif
  10655. #endif
  10656. }
  10657. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10658. // Use a site where hostname doesn't match the certificate
  10659. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10660. SSLClient cli("wrong.host.badssl.com", 443);
  10661. cli.enable_server_certificate_verification(true);
  10662. cli.enable_server_hostname_verification(true);
  10663. auto res = cli.Get("/");
  10664. ASSERT_TRUE(!res);
  10665. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10666. // Verify backend error is captured for hostname verification failure
  10667. EXPECT_NE(0UL, res.ssl_backend_error());
  10668. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10669. // For OpenSSL, ssl_error is 0 for verification errors
  10670. EXPECT_EQ(0, res.ssl_error());
  10671. #if !defined(_WIN32) || \
  10672. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10673. // On non-Windows or when Windows Schannel is disabled, the error comes
  10674. // from OpenSSL's hostname verification
  10675. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10676. res.ssl_backend_error());
  10677. #endif
  10678. #endif
  10679. }
  10680. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10681. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10682. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10683. SSLClient cli("www.google.com", 443);
  10684. cli.enable_server_certificate_verification(true);
  10685. auto res = cli.Get("/");
  10686. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10687. }
  10688. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10689. SSLClient cli("www.google.com", 443);
  10690. cli.enable_server_certificate_verification(true);
  10691. cli.enable_windows_certificate_verification(false);
  10692. auto res = cli.Get("/");
  10693. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10694. }
  10695. #endif
  10696. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10697. Client cli("https://google.com");
  10698. auto res = cli.Get("/");
  10699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10700. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10701. }
  10702. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10703. SSLClient cli("google.com");
  10704. cli.set_ca_cert_path(CA_CERT_FILE);
  10705. auto res = cli.Get("/");
  10706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10707. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10708. }
  10709. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10710. SSLClient cli("google.com");
  10711. cli.enable_server_certificate_verification(true);
  10712. cli.set_ca_cert_path("hello");
  10713. auto res = cli.Get("/");
  10714. ASSERT_TRUE(!res);
  10715. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10716. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10717. // should be set
  10718. EXPECT_EQ(0, res.ssl_error());
  10719. // Verify backend error is captured for SSLLoadingCerts
  10720. // This error occurs when loading CA certificates fails
  10721. EXPECT_NE(0UL, res.ssl_backend_error());
  10722. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10723. // OpenSSL specific error codes:
  10724. // > openssl errstr 0x80000002
  10725. // error:80000002:system library::No such file or directory
  10726. // > openssl errstr 0xA000126
  10727. // error:0A000126:SSL routines::unexpected eof while reading
  10728. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10729. res.ssl_backend_error() == 0xA000126);
  10730. #endif
  10731. }
  10732. TEST(SSLClientTest, ServerCertificateVerification4) {
  10733. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10734. ASSERT_TRUE(svr.is_valid());
  10735. svr.Get("/test", [&](const Request &, Response &res) {
  10736. res.set_content("test", "text/plain");
  10737. svr.stop();
  10738. ASSERT_TRUE(true);
  10739. });
  10740. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10741. auto se = detail::scope_exit([&] {
  10742. t.join();
  10743. ASSERT_FALSE(svr.is_running());
  10744. });
  10745. svr.wait_until_ready();
  10746. SSLClient cli("127.0.0.1", PORT);
  10747. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10748. cli.enable_server_certificate_verification(true);
  10749. cli.set_connection_timeout(30);
  10750. auto res = cli.Get("/test");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. ASSERT_EQ(StatusCode::OK_200, res->status);
  10753. }
  10754. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10755. std::string cert;
  10756. read_file(CA_CERT_FILE, cert);
  10757. SSLClient cli("google.com");
  10758. cli.load_ca_cert_store(cert.data(), cert.size());
  10759. const auto res = cli.Get("/");
  10760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10761. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10762. }
  10763. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10764. // clang-format off
  10765. static constexpr char cert[] =
  10766. "GlobalSign Root CA\n"
  10767. "==================\n"
  10768. "-----BEGIN CERTIFICATE-----\n"
  10769. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10770. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10771. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10772. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10773. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10774. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10775. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10776. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10777. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10778. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10779. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10780. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10781. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10782. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10783. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10784. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10785. "-----END CERTIFICATE-----\n";
  10786. // clang-format on
  10787. SSLClient cli("google.com");
  10788. cli.load_ca_cert_store(cert, sizeof(cert));
  10789. const auto res = cli.Get("/");
  10790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10791. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10792. }
  10793. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10794. SSLClient cli("www.youtube.com");
  10795. cli.set_ca_cert_path(CA_CERT_FILE);
  10796. cli.enable_server_certificate_verification(true);
  10797. cli.set_follow_location(true);
  10798. auto res = cli.Get("/");
  10799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10800. ASSERT_EQ(StatusCode::OK_200, res->status);
  10801. }
  10802. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10803. SSLClient cli("wWw.YouTube.Com");
  10804. cli.set_ca_cert_path(CA_CERT_FILE);
  10805. cli.enable_server_certificate_verification(true);
  10806. cli.enable_server_hostname_verification(true);
  10807. cli.set_follow_location(true);
  10808. auto res = cli.Get("/");
  10809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10810. ASSERT_EQ(StatusCode::OK_200, res->status);
  10811. }
  10812. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10813. SSLClient cli("gOoGlE.COm");
  10814. cli.enable_server_certificate_verification(true);
  10815. cli.enable_server_hostname_verification(true);
  10816. cli.set_follow_location(true);
  10817. auto res = cli.Get("/");
  10818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10819. ASSERT_EQ(StatusCode::OK_200, res->status);
  10820. }
  10821. TEST(SSLClientTest, Issue2004_Online) {
  10822. Client client("https://google.com");
  10823. client.set_follow_location(true);
  10824. auto res = client.Get("/");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. ASSERT_EQ(StatusCode::OK_200, res->status);
  10827. auto body = res->body;
  10828. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10829. }
  10830. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10831. // Create SSLClient with invalid cert/key to make is_valid() return false
  10832. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10833. "nonexistent_key.pem");
  10834. // is_valid() should be false due to cert loading failure
  10835. ASSERT_FALSE(cli.is_valid());
  10836. auto res = cli.Get("/");
  10837. ASSERT_FALSE(res);
  10838. EXPECT_EQ(Error::SSLConnection, res.error());
  10839. }
  10840. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10841. // Test for Issue #2251: SSL error not properly reported when client cert
  10842. // and key paths are swapped or mismatched
  10843. // This simulates the scenario where user accidentally swaps the cert and key
  10844. // files
  10845. // Using client cert file as private key and vice versa (completely wrong)
  10846. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10847. // Should fail validation due to cert/key mismatch
  10848. ASSERT_FALSE(cli.is_valid());
  10849. // Attempt to make a request should fail with proper error
  10850. auto res = cli.Get("/");
  10851. ASSERT_FALSE(res);
  10852. EXPECT_EQ(Error::SSLConnection, res.error());
  10853. // SSL error should be recorded in the Result object (this is the key fix for
  10854. // Issue #2251)
  10855. auto backend_error = res.ssl_backend_error();
  10856. EXPECT_NE(0u, backend_error);
  10857. }
  10858. // Tests cert/key mismatch detection at the TLS context level
  10859. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10860. // Test that using mismatched cert/key causes connection failure.
  10861. // We verify this at the SSLClient level rather than through internal
  10862. // TLS API functions.
  10863. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10864. cli.enable_server_certificate_verification(false);
  10865. cli.set_connection_timeout(2);
  10866. // The mismatch should cause a connection or handshake error
  10867. auto res = cli.Get("/test");
  10868. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10869. // Either way, the request should fail
  10870. EXPECT_FALSE(res);
  10871. }
  10872. #endif
  10873. #if 0
  10874. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10875. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10876. ASSERT_TRUE(cli != nullptr);
  10877. cli->set_address_family(AF_INET6);
  10878. cli->set_interface("en0");
  10879. auto res = cli->Get("/get");
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. ASSERT_EQ(StatusCode::OK_200, res->status);
  10882. }
  10883. #endif
  10884. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10885. #ifdef CPPHTTPLIB_SSL_ENABLED
  10886. void ClientCertPresent(
  10887. const std::string &client_cert_file,
  10888. const std::string &client_private_key_file,
  10889. const std::string &client_encrypted_private_key_pass = std::string()) {
  10890. using namespace httplib::tls;
  10891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10892. CLIENT_CA_CERT_DIR);
  10893. ASSERT_TRUE(svr.is_valid());
  10894. svr.Get("/test", [&](const Request &req, Response &res) {
  10895. res.set_content("test", "text/plain");
  10896. auto cert = req.peer_cert();
  10897. ASSERT_TRUE(static_cast<bool>(cert));
  10898. std::string common_name = cert.subject_cn();
  10899. EXPECT_EQ("Common Name", common_name);
  10900. });
  10901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. t.join();
  10905. ASSERT_FALSE(svr.is_running());
  10906. });
  10907. svr.wait_until_ready();
  10908. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10909. client_encrypted_private_key_pass);
  10910. cli.enable_server_certificate_verification(false);
  10911. cli.set_connection_timeout(30);
  10912. auto res = cli.Get("/test");
  10913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10914. ASSERT_EQ(StatusCode::OK_200, res->status);
  10915. }
  10916. TEST(SSLClientServerTest, ClientCertPresent) {
  10917. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10918. }
  10919. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10920. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10921. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10922. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10923. }
  10924. // PEM memory-based constructor tests (works with all TLS backends)
  10925. void PemMemoryClientCertPresent(
  10926. const std::string &client_cert_file,
  10927. const std::string &client_private_key_file,
  10928. const std::string &client_encrypted_private_key_pass = std::string()) {
  10929. // Read PEM files into memory
  10930. std::string server_cert_pem, server_key_pem;
  10931. std::string client_ca_pem;
  10932. std::string client_cert_pem, client_key_pem;
  10933. read_file(SERVER_CERT_FILE, server_cert_pem);
  10934. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10935. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10936. read_file(client_cert_file, client_cert_pem);
  10937. read_file(client_private_key_file, client_key_pem);
  10938. // Create server with PEM memory
  10939. SSLServer::PemMemory server_pem = {
  10940. server_cert_pem.c_str(),
  10941. server_cert_pem.size(),
  10942. server_key_pem.c_str(),
  10943. server_key_pem.size(),
  10944. client_ca_pem.c_str(),
  10945. client_ca_pem.size(),
  10946. nullptr // no password for server key
  10947. };
  10948. SSLServer svr(server_pem);
  10949. ASSERT_TRUE(svr.is_valid());
  10950. svr.Get("/test", [&](const Request &, Response &res) {
  10951. res.set_content("test", "text/plain");
  10952. });
  10953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10954. auto se = detail::scope_exit([&] {
  10955. svr.stop();
  10956. t.join();
  10957. ASSERT_FALSE(svr.is_running());
  10958. });
  10959. svr.wait_until_ready();
  10960. // Create client with PEM memory
  10961. const char *password = client_encrypted_private_key_pass.empty()
  10962. ? nullptr
  10963. : client_encrypted_private_key_pass.c_str();
  10964. SSLClient::PemMemory client_pem = {
  10965. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10966. client_key_pem.size(), password};
  10967. SSLClient cli(HOST, PORT, client_pem);
  10968. cli.enable_server_certificate_verification(false);
  10969. cli.set_connection_timeout(30);
  10970. auto res = cli.Get("/test");
  10971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10972. ASSERT_EQ(StatusCode::OK_200, res->status);
  10973. }
  10974. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10975. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10976. }
  10977. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10978. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10979. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10980. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10981. }
  10982. TEST(SSLClientServerTest, ClientCertMissing) {
  10983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10984. CLIENT_CA_CERT_DIR);
  10985. ASSERT_TRUE(svr.is_valid());
  10986. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10988. auto se = detail::scope_exit([&] {
  10989. svr.stop();
  10990. t.join();
  10991. ASSERT_FALSE(svr.is_running());
  10992. });
  10993. svr.wait_until_ready();
  10994. SSLClient cli(HOST, PORT);
  10995. cli.set_connection_timeout(30);
  10996. auto res = cli.Get("/test");
  10997. ASSERT_TRUE(!res);
  10998. // When client cert is missing and server requires it, connection fails
  10999. // Error type depends on backend implementation
  11000. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11001. res.error() == Error::SSLConnection);
  11002. // Verify backend error is captured
  11003. // Note: This test may have different error codes depending on the exact
  11004. // verification failure
  11005. EXPECT_NE(0UL, res.ssl_backend_error());
  11006. }
  11007. TEST(SSLClientServerTest, TrustDirOptional) {
  11008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11009. ASSERT_TRUE(svr.is_valid());
  11010. svr.Get("/test", [&](const Request &, Response &res) {
  11011. res.set_content("test", "text/plain");
  11012. });
  11013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11014. auto se = detail::scope_exit([&] {
  11015. svr.stop();
  11016. t.join();
  11017. ASSERT_FALSE(svr.is_running());
  11018. });
  11019. svr.wait_until_ready();
  11020. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11021. cli.enable_server_certificate_verification(false);
  11022. cli.set_connection_timeout(30);
  11023. auto res = cli.Get("/test");
  11024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11025. ASSERT_EQ(StatusCode::OK_200, res->status);
  11026. }
  11027. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11028. class NoListenSSLServer : public SSLServer {
  11029. public:
  11030. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11031. const char *client_ca_cert_file_path,
  11032. const char *client_ca_cert_dir_path = nullptr)
  11033. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11034. client_ca_cert_dir_path),
  11035. stop_(false) {}
  11036. std::atomic_bool stop_;
  11037. private:
  11038. bool process_and_close_socket(socket_t /*sock*/) override {
  11039. // Don't create SSL context
  11040. while (!stop_.load()) {
  11041. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11042. }
  11043. return true;
  11044. }
  11045. };
  11046. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11047. CLIENT_CA_CERT_FILE);
  11048. ASSERT_TRUE(svr.is_valid());
  11049. svr.Get("/test", [&](const Request &, Response &res) {
  11050. res.set_content("test", "text/plain");
  11051. });
  11052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11053. auto se = detail::scope_exit([&] {
  11054. svr.stop_ = true;
  11055. svr.stop();
  11056. t.join();
  11057. ASSERT_FALSE(svr.is_running());
  11058. });
  11059. svr.wait_until_ready();
  11060. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11061. cli.enable_server_certificate_verification(false);
  11062. cli.set_connection_timeout(1);
  11063. auto res = cli.Get("/test");
  11064. ASSERT_TRUE(!res);
  11065. EXPECT_EQ(Error::SSLConnection, res.error());
  11066. // Timeout results in WantRead error code (maps to backend-specific value)
  11067. EXPECT_NE(0, res.ssl_error());
  11068. }
  11069. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11070. // Test SSLServer with client certificate verification using the standard
  11071. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11073. CLIENT_CA_CERT_DIR);
  11074. ASSERT_TRUE(svr.is_valid());
  11075. svr.Get("/test", [&](const Request &req, Response &res) {
  11076. res.set_content("test", "text/plain");
  11077. auto cert = req.peer_cert();
  11078. ASSERT_TRUE(static_cast<bool>(cert));
  11079. auto common_name = cert.subject_cn();
  11080. EXPECT_EQ("Common Name", common_name);
  11081. });
  11082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11083. auto se = detail::scope_exit([&] {
  11084. svr.stop();
  11085. t.join();
  11086. ASSERT_FALSE(svr.is_running());
  11087. });
  11088. svr.wait_until_ready();
  11089. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11090. cli.enable_server_certificate_verification(false);
  11091. cli.set_connection_timeout(30);
  11092. auto res = cli.Get("/test");
  11093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11094. ASSERT_EQ(StatusCode::OK_200, res->status);
  11095. }
  11096. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11097. // Verifies that wildcard matching and exact matching work consistently
  11098. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11099. using namespace httplib::tls;
  11100. // We need a running server to test against
  11101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11102. ASSERT_TRUE(svr.is_valid());
  11103. svr.Get("/test", [](const Request &, Response &res) {
  11104. res.set_content("ok", "text/plain");
  11105. });
  11106. thread t([&]() { svr.listen(HOST, PORT); });
  11107. auto se = detail::scope_exit([&] {
  11108. svr.stop();
  11109. t.join();
  11110. });
  11111. svr.wait_until_ready();
  11112. bool verify_callback_called = false;
  11113. bool verify_result_wrong = false;
  11114. SSLClient cli(HOST, PORT);
  11115. cli.enable_server_certificate_verification(true);
  11116. cli.set_ca_cert_path(CA_CERT_FILE);
  11117. cli.set_connection_timeout(5);
  11118. // Note: Test certificate has CN="Common Name", not "localhost"
  11119. bool verify_result_cn = false;
  11120. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11121. verify_callback_called = true;
  11122. if (!ctx.cert) return false;
  11123. // Test 1: "Common Name" should match (our test server cert CN)
  11124. verify_result_cn = ctx.check_hostname("Common Name");
  11125. // Test 2: wrong hostname should not match
  11126. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11127. return true; // Accept for the purpose of this test
  11128. });
  11129. auto res = cli.Get("/test");
  11130. // The request may succeed or fail depending on cert configuration
  11131. // but the callback should have been called
  11132. ASSERT_TRUE(verify_callback_called)
  11133. << "Verify callback should have been called";
  11134. // CN="Common Name" should match our test certificate
  11135. //
  11136. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11137. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11138. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11139. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11140. // <openssl/base.h>, which is included transitively when
  11141. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11142. #if defined(OPENSSL_IS_BORINGSSL)
  11143. EXPECT_FALSE(verify_result_cn)
  11144. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11145. #else
  11146. EXPECT_TRUE(verify_result_cn)
  11147. << "verify_hostname should match 'Common Name' (certificate CN)";
  11148. #endif
  11149. // Wrong hostname should not match
  11150. EXPECT_FALSE(verify_result_wrong)
  11151. << "verify_hostname should not match 'wronghost.example.com'";
  11152. }
  11153. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11154. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11155. // X509_check_ip behavior and must hold for every backend.
  11156. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11157. using namespace httplib::tls;
  11158. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11159. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11160. ASSERT_TRUE(svr.is_valid());
  11161. svr.Get("/test", [](const Request &, Response &res) {
  11162. res.set_content("ok", "text/plain");
  11163. });
  11164. thread t([&]() { svr.listen(HOST, PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. });
  11169. svr.wait_until_ready();
  11170. bool verify_callback_called = false;
  11171. bool ip_matched_via_cn = true;
  11172. SSLClient cli(HOST, PORT);
  11173. cli.enable_server_certificate_verification(true);
  11174. cli.set_ca_cert_path(CA_CERT_FILE);
  11175. cli.set_connection_timeout(5);
  11176. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11177. verify_callback_called = true;
  11178. if (!ctx.cert) return false;
  11179. // The IP appears only in the CN, so it must NOT be accepted.
  11180. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11181. return true; // Accept for the purpose of this test
  11182. });
  11183. cli.Get("/test");
  11184. ASSERT_TRUE(verify_callback_called)
  11185. << "Verify callback should have been called";
  11186. EXPECT_FALSE(ip_matched_via_cn)
  11187. << "An IP host must not be authenticated via the certificate CN";
  11188. }
  11189. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11190. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11191. using namespace httplib::tls;
  11192. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11193. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11194. ASSERT_TRUE(svr.is_valid());
  11195. svr.Get("/test", [](const Request &, Response &res) {
  11196. res.set_content("ok", "text/plain");
  11197. });
  11198. thread t([&]() { svr.listen(HOST, PORT); });
  11199. auto se = detail::scope_exit([&] {
  11200. svr.stop();
  11201. t.join();
  11202. });
  11203. svr.wait_until_ready();
  11204. bool verify_callback_called = false;
  11205. bool san_matched = false;
  11206. bool wrong_ipv6_matched = true;
  11207. bool cn_ipv6_matched = true;
  11208. SSLClient cli(HOST, PORT);
  11209. cli.enable_server_certificate_verification(true);
  11210. cli.set_ca_cert_path(CA_CERT_FILE);
  11211. cli.set_connection_timeout(5);
  11212. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11213. verify_callback_called = true;
  11214. if (!ctx.cert) return false;
  11215. // Matches the IPv6 iPAddress SAN.
  11216. san_matched = ctx.check_hostname("2001:db8::1");
  11217. // A different IPv6 address must not match.
  11218. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11219. // "::1" lives only in the CN, so it must not be accepted.
  11220. cn_ipv6_matched = ctx.check_hostname("::1");
  11221. return true; // Accept for the purpose of this test
  11222. });
  11223. cli.Get("/test");
  11224. ASSERT_TRUE(verify_callback_called)
  11225. << "Verify callback should have been called";
  11226. EXPECT_TRUE(san_matched)
  11227. << "verify_hostname should match an IPv6 iPAddress SAN";
  11228. EXPECT_FALSE(wrong_ipv6_matched)
  11229. << "verify_hostname should not match a non-matching IPv6 address";
  11230. EXPECT_FALSE(cn_ipv6_matched)
  11231. << "An IPv6 host must not be authenticated via the certificate CN";
  11232. }
  11233. #endif
  11234. // mbedTLS-specific callback constructor test
  11235. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11236. #ifdef CPPHTTPLIB_SSL_ENABLED
  11237. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11239. ASSERT_TRUE(svr.is_valid());
  11240. // Set up a handler to verify client certificate is present
  11241. bool client_cert_verified = false;
  11242. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11243. // Verify that client certificate was provided
  11244. client_cert_verified = true;
  11245. res.set_content("success", "text/plain");
  11246. });
  11247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11248. auto se = detail::scope_exit([&] {
  11249. svr.stop();
  11250. t.join();
  11251. ASSERT_FALSE(svr.is_running());
  11252. });
  11253. svr.wait_until_ready();
  11254. // Client with certificate
  11255. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11256. cli.enable_server_certificate_verification(false);
  11257. cli.set_connection_timeout(30);
  11258. auto res = cli.Get("/test");
  11259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11260. ASSERT_EQ(StatusCode::OK_200, res->status);
  11261. ASSERT_TRUE(client_cert_verified);
  11262. EXPECT_EQ("success", res->body);
  11263. }
  11264. #endif
  11265. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11266. // backends
  11267. #ifdef CPPHTTPLIB_SSL_ENABLED
  11268. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11269. using namespace httplib::tls;
  11270. // Test that when client CA cert file is provided,
  11271. // the server properly requests and validates client certificates
  11272. // Create a server with client authentication
  11273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11274. ASSERT_TRUE(svr.is_valid());
  11275. bool handler_called = false;
  11276. svr.Get("/test", [&](const Request &req, Response &res) {
  11277. handler_called = true;
  11278. // Verify that a client certificate was provided
  11279. auto cert = req.peer_cert();
  11280. ASSERT_TRUE(static_cast<bool>(cert));
  11281. // Get the issuer name
  11282. std::string issuer_str = cert.issuer_name();
  11283. ASSERT_FALSE(issuer_str.empty());
  11284. // The client certificate should be issued by our test CA
  11285. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11286. res.set_content("authenticated", "text/plain");
  11287. });
  11288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. t.join();
  11292. ASSERT_FALSE(svr.is_running());
  11293. });
  11294. svr.wait_until_ready();
  11295. // Connect with a client certificate issued by the CA
  11296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11297. cli.enable_server_certificate_verification(false);
  11298. cli.set_connection_timeout(30);
  11299. auto res = cli.Get("/test");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. ASSERT_EQ(StatusCode::OK_200, res->status);
  11302. ASSERT_TRUE(handler_called);
  11303. EXPECT_EQ("authenticated", res->body);
  11304. }
  11305. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11306. using namespace httplib::tls;
  11307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11308. ASSERT_TRUE(svr.is_valid());
  11309. svr.Get("/test", [](const Request &, Response &res) {
  11310. res.set_content("ok", "text/plain");
  11311. });
  11312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11313. auto se = detail::scope_exit([&] {
  11314. svr.stop();
  11315. t.join();
  11316. });
  11317. svr.wait_until_ready();
  11318. SSLClient cli(HOST, PORT);
  11319. cli.enable_server_certificate_verification(false);
  11320. cli.set_connection_timeout(30);
  11321. bool cert_checked = false;
  11322. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11323. if (ctx.cert) {
  11324. auto sans = ctx.sans();
  11325. // Test certificate may or may not have SANs - just verify the API
  11326. // works If SANs exist, verify the types are valid
  11327. for (const auto &san : sans) {
  11328. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11329. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11330. san.type == SanType::OTHER);
  11331. EXPECT_FALSE(san.value.empty());
  11332. }
  11333. cert_checked = true;
  11334. }
  11335. return true;
  11336. });
  11337. auto res = cli.Get("/test");
  11338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11339. EXPECT_TRUE(cert_checked);
  11340. }
  11341. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11342. using namespace httplib::tls;
  11343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11344. ASSERT_TRUE(svr.is_valid());
  11345. svr.Get("/test", [](const Request &, Response &res) {
  11346. res.set_content("ok", "text/plain");
  11347. });
  11348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11349. auto se = detail::scope_exit([&] {
  11350. svr.stop();
  11351. t.join();
  11352. });
  11353. svr.wait_until_ready();
  11354. SSLClient cli(HOST, PORT);
  11355. cli.enable_server_certificate_verification(false);
  11356. cli.set_connection_timeout(30);
  11357. bool validity_checked = false;
  11358. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11359. if (ctx.cert) {
  11360. time_t not_before = 0, not_after = 0;
  11361. bool result = ctx.validity(not_before, not_after);
  11362. EXPECT_TRUE(result);
  11363. // Verify that not_before < now < not_after for a valid cert
  11364. time_t now = time(nullptr);
  11365. EXPECT_LT(not_before, now);
  11366. EXPECT_GT(not_after, now);
  11367. validity_checked = true;
  11368. }
  11369. return true;
  11370. });
  11371. auto res = cli.Get("/test");
  11372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11373. EXPECT_TRUE(validity_checked);
  11374. }
  11375. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11376. using namespace httplib::tls;
  11377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11378. ASSERT_TRUE(svr.is_valid());
  11379. svr.Get("/test", [](const Request &, Response &res) {
  11380. res.set_content("ok", "text/plain");
  11381. });
  11382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11383. auto se = detail::scope_exit([&] {
  11384. svr.stop();
  11385. t.join();
  11386. });
  11387. svr.wait_until_ready();
  11388. SSLClient cli(HOST, PORT);
  11389. cli.enable_server_certificate_verification(false);
  11390. cli.set_connection_timeout(30);
  11391. bool serial_checked = false;
  11392. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11393. if (ctx.cert) {
  11394. std::string serial = ctx.serial();
  11395. EXPECT_FALSE(serial.empty());
  11396. // Serial should be a hex string
  11397. for (char c : serial) {
  11398. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11399. (c >= 'a' && c <= 'f'));
  11400. }
  11401. serial_checked = true;
  11402. }
  11403. return true;
  11404. });
  11405. auto res = cli.Get("/test");
  11406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11407. EXPECT_TRUE(serial_checked);
  11408. }
  11409. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11410. // Test 1: Valid CA file - no error should be recorded
  11411. {
  11412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11413. CLIENT_CA_CERT_FILE);
  11414. ASSERT_TRUE(svr.is_valid());
  11415. // With valid setup, last_ssl_error should be 0
  11416. EXPECT_EQ(0, svr.ssl_last_error());
  11417. }
  11418. // Test 2: Invalid CA file content
  11419. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11420. {
  11421. // Create a temporary file with completely invalid content
  11422. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11423. {
  11424. std::ofstream ofs(temp_invalid_ca);
  11425. ofs << "This is not a certificate file at all\n";
  11426. ofs << "Just plain text content\n";
  11427. }
  11428. // Create server with invalid CA file
  11429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11430. // Clean up temporary file
  11431. std::remove(temp_invalid_ca);
  11432. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11433. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11434. // Note: SSL_CTX_load_verify_locations typically fails first,
  11435. // but our error handling code path is still exercised
  11436. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11437. }
  11438. }
  11439. TEST(VerifyCallbackTest, VerifyContextFields) {
  11440. using namespace httplib::tls;
  11441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11442. ASSERT_TRUE(svr.is_valid());
  11443. svr.Get("/test", [](const Request &, Response &res) {
  11444. res.set_content("ok", "text/plain");
  11445. });
  11446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. });
  11451. svr.wait_until_ready();
  11452. SSLClient cli(HOST, PORT);
  11453. cli.enable_server_certificate_verification(false);
  11454. cli.set_connection_timeout(30);
  11455. int callback_count = 0;
  11456. bool saw_leaf_cert = false;
  11457. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11458. if (ctx.cert) {
  11459. callback_count++;
  11460. // We should see at least one certificate (the leaf)
  11461. std::string cn = ctx.subject_cn();
  11462. if (!cn.empty()) { saw_leaf_cert = true; }
  11463. // Verify context fields are populated
  11464. EXPECT_NE(ctx.session, nullptr);
  11465. EXPECT_GE(ctx.depth, 0);
  11466. }
  11467. return true;
  11468. });
  11469. auto res = cli.Get("/test");
  11470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11471. EXPECT_GT(callback_count, 0);
  11472. EXPECT_TRUE(saw_leaf_cert);
  11473. }
  11474. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11475. using httplib::tls::TlsError;
  11476. // Test that verify_error_to_string returns empty for success
  11477. std::string success_str = TlsError::verify_error_to_string(0);
  11478. EXPECT_TRUE(success_str.empty());
  11479. // Test that verify_error_to_string returns non-empty for error codes
  11480. // Using a common error code (certificate expired)
  11481. std::string error_str =
  11482. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11483. EXPECT_FALSE(error_str.empty());
  11484. }
  11485. TEST(SessionVerifierTest, CertificateAccepted) {
  11486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11487. ASSERT_TRUE(svr.is_valid());
  11488. svr.Get("/test", [](const Request &, Response &res) {
  11489. res.set_content("ok", "text/plain");
  11490. });
  11491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11492. auto se = detail::scope_exit([&] {
  11493. svr.stop();
  11494. t.join();
  11495. });
  11496. svr.wait_until_ready();
  11497. SSLClient cli(HOST, PORT);
  11498. cli.enable_server_certificate_verification(false);
  11499. cli.set_connection_timeout(30);
  11500. bool callback_called = false;
  11501. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11502. EXPECT_NE(session, nullptr);
  11503. callback_called = true;
  11504. return SSLVerifierResponse::CertificateAccepted;
  11505. });
  11506. auto res = cli.Get("/test");
  11507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11508. EXPECT_EQ(200, res->status);
  11509. EXPECT_TRUE(callback_called);
  11510. }
  11511. TEST(SessionVerifierTest, CertificateRejected) {
  11512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11513. ASSERT_TRUE(svr.is_valid());
  11514. svr.Get("/test", [](const Request &, Response &res) {
  11515. res.set_content("ok", "text/plain");
  11516. });
  11517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11518. auto se = detail::scope_exit([&] {
  11519. svr.stop();
  11520. t.join();
  11521. });
  11522. svr.wait_until_ready();
  11523. SSLClient cli(HOST, PORT);
  11524. cli.enable_server_certificate_verification(false);
  11525. cli.set_connection_timeout(30);
  11526. bool callback_called = false;
  11527. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11528. EXPECT_NE(session, nullptr);
  11529. callback_called = true;
  11530. return SSLVerifierResponse::CertificateRejected;
  11531. });
  11532. auto res = cli.Get("/test");
  11533. EXPECT_FALSE(res);
  11534. EXPECT_TRUE(callback_called);
  11535. }
  11536. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11537. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11538. ASSERT_TRUE(svr.is_valid());
  11539. svr.Get("/test", [](const Request &, Response &res) {
  11540. res.set_content("ok", "text/plain");
  11541. });
  11542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11543. auto se = detail::scope_exit([&] {
  11544. svr.stop();
  11545. t.join();
  11546. });
  11547. svr.wait_until_ready();
  11548. // NoDecisionMade with verification disabled should succeed (no default check)
  11549. SSLClient cli(HOST, PORT);
  11550. cli.enable_server_certificate_verification(false);
  11551. cli.set_connection_timeout(30);
  11552. bool callback_called = false;
  11553. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11554. EXPECT_NE(session, nullptr);
  11555. callback_called = true;
  11556. return SSLVerifierResponse::NoDecisionMade;
  11557. });
  11558. auto res = cli.Get("/test");
  11559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11560. EXPECT_EQ(200, res->status);
  11561. EXPECT_TRUE(callback_called);
  11562. }
  11563. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11565. ASSERT_TRUE(svr.is_valid());
  11566. svr.Get("/test", [](const Request &, Response &res) {
  11567. res.set_content("ok", "text/plain");
  11568. });
  11569. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. });
  11574. svr.wait_until_ready();
  11575. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11576. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11577. // so we only check that the request fails, not whether the callback was
  11578. // called.
  11579. SSLClient cli(HOST, PORT);
  11580. cli.enable_server_certificate_verification(true);
  11581. cli.set_connection_timeout(30);
  11582. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11583. EXPECT_NE(session, nullptr);
  11584. return SSLVerifierResponse::NoDecisionMade;
  11585. });
  11586. auto res = cli.Get("/test");
  11587. EXPECT_FALSE(res);
  11588. }
  11589. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11590. // Test SSL server using PemMemory constructor with client CA certificates
  11591. // Read PEM files
  11592. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11593. read_file(SERVER_CERT_FILE, server_cert_pem);
  11594. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11595. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11596. // Create SSLServer with PemMemory constructor including client CA
  11597. SSLServer::PemMemory server_pem = {
  11598. server_cert_pem.c_str(),
  11599. server_cert_pem.size(),
  11600. server_key_pem.c_str(),
  11601. server_key_pem.size(),
  11602. client_ca_pem.c_str(),
  11603. client_ca_pem.size(),
  11604. nullptr // no password for server key
  11605. };
  11606. SSLServer svr(server_pem);
  11607. ASSERT_TRUE(svr.is_valid());
  11608. // No SSL error should be recorded for valid setup
  11609. EXPECT_EQ(0, svr.ssl_last_error());
  11610. // Set up server endpoints
  11611. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11612. res.set_content("ok", "text/plain");
  11613. });
  11614. // Start server in a thread
  11615. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11616. svr.wait_until_ready();
  11617. // Connect with client certificate (using constructor with paths)
  11618. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11619. cli.enable_server_certificate_verification(false);
  11620. auto res = cli.Get("/test-pem-ca");
  11621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11622. EXPECT_EQ(200, res->status);
  11623. EXPECT_EQ("ok", res->body);
  11624. svr.stop();
  11625. server_thread.join();
  11626. }
  11627. #endif
  11628. #ifdef _WIN32
  11629. TEST(CleanupTest, WSACleanup) {
  11630. int ret = WSACleanup();
  11631. ASSERT_EQ(0, ret);
  11632. }
  11633. #endif
  11634. #ifndef CPPHTTPLIB_SSL_ENABLED
  11635. TEST(NoSSLSupport, SimpleInterface) {
  11636. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11637. }
  11638. #endif
  11639. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11640. TEST(InvalidScheme, SimpleInterface) {
  11641. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11642. }
  11643. #endif
  11644. TEST(NoScheme, SimpleInterface) {
  11645. Client cli("yahoo.com:80");
  11646. ASSERT_TRUE(cli.is_valid());
  11647. }
  11648. TEST(SendAPI, SimpleInterface_Online) {
  11649. Client cli("http://yahoo.com");
  11650. Request req;
  11651. req.method = "GET";
  11652. req.path = "/";
  11653. auto res = cli.send(req);
  11654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11655. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11656. }
  11657. TEST(SendAPI, WithParamsInRequest) {
  11658. Server svr;
  11659. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11660. EXPECT_TRUE(req.has_param("test"));
  11661. EXPECT_EQ("test_value", req.get_param_value("test"));
  11662. });
  11663. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11664. auto se = detail::scope_exit([&] {
  11665. svr.stop();
  11666. t.join();
  11667. ASSERT_FALSE(svr.is_running());
  11668. });
  11669. svr.wait_until_ready();
  11670. Client cli(HOST, PORT);
  11671. {
  11672. Request req;
  11673. req.method = "GET";
  11674. req.path = "/";
  11675. req.params.emplace("test", "test_value");
  11676. auto res = cli.send(req);
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. }
  11679. {
  11680. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11682. }
  11683. }
  11684. TEST(ClientImplMethods, GetSocketTest) {
  11685. httplib::Server svr;
  11686. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11687. res.status = StatusCode::OK_200;
  11688. });
  11689. auto port = svr.bind_to_any_port("127.0.0.1");
  11690. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11691. auto se = detail::scope_exit([&] {
  11692. svr.stop();
  11693. thread.join();
  11694. ASSERT_FALSE(svr.is_running());
  11695. });
  11696. svr.wait_until_ready();
  11697. {
  11698. httplib::Client cli("127.0.0.1", port);
  11699. cli.set_keep_alive(true);
  11700. // Use the behavior of cpp-httplib of opening the connection
  11701. // only when the first request happens. If that changes,
  11702. // this test would be obsolete.
  11703. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11704. // This also implicitly tests the server. But other tests would fail much
  11705. // earlier than this one to be considered.
  11706. auto res = cli.Get("/");
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. EXPECT_EQ(StatusCode::OK_200, res->status);
  11709. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11710. }
  11711. }
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11714. Client cli("http://yahoo.com");
  11715. auto res = cli.Get("/");
  11716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11717. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11718. cli.set_follow_location(true);
  11719. res = cli.Get("/");
  11720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11721. EXPECT_EQ(StatusCode::OK_200, res->status);
  11722. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11723. }
  11724. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11725. Client cli("https://yahoo.com");
  11726. auto res = cli.Get("/");
  11727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11728. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11729. cli.set_follow_location(true);
  11730. res = cli.Get("/");
  11731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11732. EXPECT_EQ(StatusCode::OK_200, res->status);
  11733. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11734. }
  11735. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11736. Client cli("https://yahoo.com");
  11737. auto res = cli.Get("/");
  11738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11739. ASSERT_FALSE(!res);
  11740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11741. ASSERT_FALSE(res == nullptr);
  11742. ASSERT_TRUE(res != nullptr);
  11743. EXPECT_EQ(Error::Success, res.error());
  11744. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11745. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11746. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11747. cli.set_follow_location(true);
  11748. res = cli.Get("/");
  11749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11750. EXPECT_EQ(Error::Success, res.error());
  11751. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11752. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11753. EXPECT_EQ(StatusCode::OK_200, res->status);
  11754. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11755. }
  11756. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11757. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11758. Client cli("https://cdnjs.cloudflare.com");
  11759. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11760. Headers{{"Accept-Encoding", "br"}});
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status);
  11763. EXPECT_EQ(287630U, res->body.size());
  11764. EXPECT_EQ("application/javascript; charset=utf-8",
  11765. res->get_header_value("Content-Type"));
  11766. }
  11767. #endif
  11768. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11769. #undef REDIR_HOST // Silence compiler warning
  11770. #define REDIR_HOST "https://httpbingo.org"
  11771. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11772. Client cli(REDIR_HOST);
  11773. cli.set_follow_location(true);
  11774. auto res =
  11775. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11777. EXPECT_EQ(StatusCode::OK_200, res->status);
  11778. }
  11779. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11780. Client cli(REDIR_HOST);
  11781. cli.set_follow_location(true);
  11782. Params params;
  11783. params.emplace("url", "http://example.com");
  11784. params.emplace("status_code", "302");
  11785. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11790. Client cli(REDIR_HOST);
  11791. cli.set_follow_location(true);
  11792. Params params;
  11793. params.emplace("url", "http://example.com");
  11794. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11796. EXPECT_EQ(StatusCode::OK_200, res->status);
  11797. }
  11798. TEST(HttpToHttpsRedirectTest, CertFile) {
  11799. auto ssl_port = PORT + 1;
  11800. Server svr;
  11801. ASSERT_TRUE(svr.is_valid());
  11802. svr.Get("/index", [&](const Request &, Response &res) {
  11803. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11804. "/index");
  11805. svr.stop();
  11806. });
  11807. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11808. ASSERT_TRUE(ssl_svr.is_valid());
  11809. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11810. res.set_content("test", "text/plain");
  11811. ssl_svr.stop();
  11812. });
  11813. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11814. thread t2 =
  11815. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11816. auto se = detail::scope_exit([&] {
  11817. t2.join();
  11818. t.join();
  11819. ASSERT_FALSE(svr.is_running());
  11820. });
  11821. svr.wait_until_ready();
  11822. ssl_svr.wait_until_ready();
  11823. Client cli("127.0.0.1", PORT);
  11824. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11825. cli.enable_server_certificate_verification(true);
  11826. cli.set_follow_location(true);
  11827. cli.set_connection_timeout(30);
  11828. auto res = cli.Get("/index");
  11829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11830. ASSERT_EQ(StatusCode::OK_200, res->status);
  11831. }
  11832. TEST(SSLClientRedirectTest, CertFile) {
  11833. auto ssl_port = PORT + 1;
  11834. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11835. ASSERT_TRUE(ssl_svr1.is_valid());
  11836. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11837. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11838. "/index");
  11839. ssl_svr1.stop();
  11840. });
  11841. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11842. ASSERT_TRUE(ssl_svr2.is_valid());
  11843. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11844. res.set_content("test", "text/plain");
  11845. ssl_svr2.stop();
  11846. });
  11847. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11848. thread t2 =
  11849. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11850. auto se = detail::scope_exit([&] {
  11851. t2.join();
  11852. t.join();
  11853. ASSERT_FALSE(ssl_svr1.is_running());
  11854. });
  11855. ssl_svr1.wait_until_ready();
  11856. ssl_svr2.wait_until_ready();
  11857. SSLClient cli("127.0.0.1", PORT);
  11858. std::string cert;
  11859. read_file(SERVER_CERT2_FILE, cert);
  11860. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11861. cli.enable_server_certificate_verification(true);
  11862. cli.set_follow_location(true);
  11863. cli.set_connection_timeout(30);
  11864. auto res = cli.Get("/index");
  11865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11866. ASSERT_EQ(StatusCode::OK_200, res->status);
  11867. }
  11868. #endif
  11869. #ifdef CPPHTTPLIB_SSL_ENABLED
  11870. // Test that set_ca_cert_store() skips system certs (consistent with
  11871. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11872. // should be trusted - system certs should NOT be loaded.
  11873. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11874. // Load a specific cert that is NOT a system CA cert
  11875. std::string cert;
  11876. read_file(SERVER_CERT2_FILE, cert);
  11877. SSLClient cli("google.com");
  11878. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11879. cli.enable_server_certificate_verification(true);
  11880. // This should FAIL because:
  11881. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11882. // 2. System certs should NOT be loaded when custom store is set
  11883. // If system certs WERE loaded, this would succeed
  11884. auto res = cli.Get("/");
  11885. ASSERT_FALSE(res);
  11886. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11887. }
  11888. // Same as above, but through the native store handle path. Regression test:
  11889. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11890. // merged system certs into the user-provided store.
  11891. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11892. std::string cert;
  11893. read_file(SERVER_CERT2_FILE, cert);
  11894. SSLClient cli("google.com");
  11895. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11896. cli.enable_server_certificate_verification(true);
  11897. auto res = cli.Get("/");
  11898. ASSERT_FALSE(res);
  11899. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11900. }
  11901. // A custom store set via the native handle must still verify a server whose
  11902. // cert it does contain.
  11903. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11904. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11905. ASSERT_TRUE(svr.is_valid());
  11906. svr.Get("/test", [&](const Request &, Response &res) {
  11907. res.set_content("test", "text/plain");
  11908. });
  11909. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11910. auto se = detail::scope_exit([&] {
  11911. svr.stop();
  11912. t.join();
  11913. ASSERT_FALSE(svr.is_running());
  11914. });
  11915. svr.wait_until_ready();
  11916. SSLClient cli("127.0.0.1", PORT);
  11917. std::string cert;
  11918. read_file(SERVER_CERT2_FILE, cert);
  11919. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11920. cli.enable_server_certificate_verification(true);
  11921. cli.set_connection_timeout(30);
  11922. auto res = cli.Get("/test");
  11923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11924. ASSERT_EQ(StatusCode::OK_200, res->status);
  11925. }
  11926. // CA certs loaded through the universal Client must be transferred to the
  11927. // client created internally for following an HTTPS redirect. Regression test:
  11928. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11929. // the CA data for redirect transfer.
  11930. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11931. auto ssl_port = PORT + 1;
  11932. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11933. ASSERT_TRUE(ssl_svr1.is_valid());
  11934. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11935. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11936. "/index");
  11937. });
  11938. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11939. ASSERT_TRUE(ssl_svr2.is_valid());
  11940. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11941. res.set_content("test", "text/plain");
  11942. });
  11943. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11944. thread t2 =
  11945. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11946. auto se = detail::scope_exit([&] {
  11947. ssl_svr2.stop();
  11948. ssl_svr1.stop();
  11949. t2.join();
  11950. t.join();
  11951. ASSERT_FALSE(ssl_svr1.is_running());
  11952. });
  11953. ssl_svr1.wait_until_ready();
  11954. ssl_svr2.wait_until_ready();
  11955. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11956. std::string cert;
  11957. read_file(SERVER_CERT2_FILE, cert);
  11958. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11959. cli.enable_server_certificate_verification(true);
  11960. cli.set_follow_location(true);
  11961. cli.set_connection_timeout(30);
  11962. auto res = cli.Get("/index");
  11963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11964. ASSERT_EQ(StatusCode::OK_200, res->status);
  11965. }
  11966. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11967. // so a host signed by a system CA verifies even though a custom CA is set
  11968. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11969. std::string cert;
  11970. read_file(SERVER_CERT2_FILE, cert);
  11971. SSLClient cli("google.com");
  11972. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11973. cli.enable_system_ca(true);
  11974. cli.enable_server_certificate_verification(true);
  11975. auto res = cli.Get("/");
  11976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11977. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11978. }
  11979. // The custom CA remains effective when combined with the system CA
  11980. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11981. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11982. ASSERT_TRUE(svr.is_valid());
  11983. svr.Get("/test", [&](const Request &, Response &res) {
  11984. res.set_content("test", "text/plain");
  11985. });
  11986. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11987. auto se = detail::scope_exit([&] {
  11988. svr.stop();
  11989. t.join();
  11990. ASSERT_FALSE(svr.is_running());
  11991. });
  11992. svr.wait_until_ready();
  11993. SSLClient cli("127.0.0.1", PORT);
  11994. std::string cert;
  11995. read_file(SERVER_CERT2_FILE, cert);
  11996. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11997. cli.enable_system_ca(true);
  11998. cli.enable_server_certificate_verification(true);
  11999. cli.set_connection_timeout(30);
  12000. auto res = cli.Get("/test");
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. ASSERT_EQ(StatusCode::OK_200, res->status);
  12003. }
  12004. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12005. // skip chain verification entirely (only the certificate identity was
  12006. // checked), so a server presenting an untrusted certificate with a matching
  12007. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12008. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12009. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12010. ASSERT_TRUE(svr.is_valid());
  12011. svr.Get("/test", [&](const Request &, Response &res) {
  12012. res.set_content("test", "text/plain");
  12013. });
  12014. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12015. auto se = detail::scope_exit([&] {
  12016. svr.stop();
  12017. t.join();
  12018. ASSERT_FALSE(svr.is_running());
  12019. });
  12020. svr.wait_until_ready();
  12021. SSLClient cli("127.0.0.1", PORT);
  12022. std::string cert;
  12023. // A trusted CA that did not sign the server certificate. The server cert
  12024. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12025. // this connection.
  12026. read_file(CLIENT_CA_CERT_FILE, cert);
  12027. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12028. cli.enable_server_certificate_verification(true);
  12029. cli.set_connection_timeout(30);
  12030. auto res = cli.Get("/test");
  12031. ASSERT_FALSE(res);
  12032. }
  12033. // enable_system_ca(false) prevents system CA loading entirely
  12034. TEST(SSLClientTest, DisableSystemCa_Online) {
  12035. SSLClient cli("google.com");
  12036. cli.enable_system_ca(false);
  12037. cli.enable_server_certificate_verification(true);
  12038. auto res = cli.Get("/");
  12039. ASSERT_FALSE(res);
  12040. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12041. // itself when the CA chain is empty
  12042. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12043. res.error() == Error::SSLConnection);
  12044. }
  12045. // The universal Client forwards enable_system_ca()
  12046. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12047. std::string cert;
  12048. read_file(SERVER_CERT2_FILE, cert);
  12049. Client cli("https://google.com");
  12050. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12051. cli.enable_system_ca(true);
  12052. cli.enable_server_certificate_verification(true);
  12053. auto res = cli.Get("/");
  12054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12055. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12056. }
  12057. // The system CA policy must carry over to the client created internally for
  12058. // following a cross-host HTTPS redirect
  12059. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12060. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12061. ASSERT_TRUE(svr.is_valid());
  12062. svr.Get("/index", [&](const Request &, Response &res) {
  12063. res.set_redirect("https://www.google.com/");
  12064. });
  12065. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12066. auto se = detail::scope_exit([&] {
  12067. svr.stop();
  12068. t.join();
  12069. ASSERT_FALSE(svr.is_running());
  12070. });
  12071. svr.wait_until_ready();
  12072. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12073. std::string cert;
  12074. read_file(SERVER_CERT2_FILE, cert);
  12075. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12076. cli.enable_system_ca(true);
  12077. cli.enable_server_certificate_verification(true);
  12078. cli.set_follow_location(true);
  12079. cli.set_connection_timeout(30);
  12080. // Receiving any response proves the redirect client completed the TLS
  12081. // handshake with a system-CA-signed host
  12082. auto res = cli.Get("/index");
  12083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12084. }
  12085. TEST(MultipartFormDataTest, LargeData) {
  12086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12087. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12088. const ContentReader &content_reader) {
  12089. if (req.is_multipart_form_data()) {
  12090. std::vector<FormData> items;
  12091. content_reader(
  12092. [&](const FormData &file) {
  12093. items.push_back(file);
  12094. return true;
  12095. },
  12096. [&](const char *data, size_t data_length) {
  12097. items.back().content.append(data, data_length);
  12098. return true;
  12099. });
  12100. EXPECT_TRUE(std::string(items[0].name) == "document");
  12101. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12102. EXPECT_TRUE(items[0].filename == "2MB_data");
  12103. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12104. EXPECT_TRUE(items[1].name == "hello");
  12105. EXPECT_TRUE(items[1].content == "world");
  12106. EXPECT_TRUE(items[1].filename == "");
  12107. EXPECT_TRUE(items[1].content_type == "");
  12108. } else {
  12109. std::string body;
  12110. content_reader([&](const char *data, size_t data_length) {
  12111. body.append(data, data_length);
  12112. return true;
  12113. });
  12114. }
  12115. });
  12116. auto port = svr.bind_to_any_port(HOST);
  12117. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12118. auto se = detail::scope_exit([&] {
  12119. svr.stop();
  12120. t.join();
  12121. ASSERT_FALSE(svr.is_running());
  12122. });
  12123. svr.wait_until_ready();
  12124. {
  12125. std::string data(1024 * 1024 * 2, '.');
  12126. std::stringstream buffer;
  12127. buffer << data;
  12128. SSLClient cli(HOST, port);
  12129. cli.enable_server_certificate_verification(false);
  12130. UploadFormDataItems items{
  12131. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12132. {"hello", "world", "", ""},
  12133. };
  12134. auto res = cli.Post("/post", items);
  12135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12136. ASSERT_EQ(StatusCode::OK_200, res->status);
  12137. }
  12138. }
  12139. TEST(MultipartFormDataTest, DataProviderItems) {
  12140. std::random_device seed_gen;
  12141. std::mt19937 random(seed_gen());
  12142. std::string rand1;
  12143. rand1.resize(1000);
  12144. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12145. std::string rand2;
  12146. rand2.resize(3000);
  12147. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12149. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12150. const ContentReader &content_reader) {
  12151. ASSERT_FALSE(req.is_multipart_form_data());
  12152. std::string body;
  12153. content_reader([&](const char *data, size_t data_length) {
  12154. body.append(data, data_length);
  12155. return true;
  12156. });
  12157. EXPECT_EQ(body, "");
  12158. });
  12159. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12160. const ContentReader &content_reader) {
  12161. ASSERT_TRUE(req.is_multipart_form_data());
  12162. std::vector<FormData> items;
  12163. content_reader(
  12164. [&](const FormData &file) {
  12165. items.push_back(file);
  12166. return true;
  12167. },
  12168. [&](const char *data, size_t data_length) {
  12169. items.back().content.append(data, data_length);
  12170. return true;
  12171. });
  12172. ASSERT_TRUE(items.size() == 2);
  12173. EXPECT_EQ(std::string(items[0].name), "name1");
  12174. EXPECT_EQ(items[0].content, "Testing123");
  12175. EXPECT_EQ(items[0].filename, "filename1");
  12176. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12177. EXPECT_EQ(items[1].name, "name2");
  12178. EXPECT_EQ(items[1].content, "Testing456");
  12179. EXPECT_EQ(items[1].filename, "");
  12180. EXPECT_EQ(items[1].content_type, "");
  12181. });
  12182. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12183. const ContentReader &content_reader) {
  12184. ASSERT_TRUE(req.is_multipart_form_data());
  12185. std::vector<FormData> items;
  12186. content_reader(
  12187. [&](const FormData &file) {
  12188. items.push_back(file);
  12189. return true;
  12190. },
  12191. [&](const char *data, size_t data_length) {
  12192. items.back().content.append(data, data_length);
  12193. return true;
  12194. });
  12195. ASSERT_TRUE(items.size() == 2);
  12196. EXPECT_EQ(items[0].name, "name3");
  12197. EXPECT_EQ(items[0].content, rand1);
  12198. EXPECT_EQ(items[0].filename, "filename3");
  12199. EXPECT_EQ(items[0].content_type, "");
  12200. EXPECT_EQ(items[1].name, "name4");
  12201. EXPECT_EQ(items[1].content, rand2);
  12202. EXPECT_EQ(items[1].filename, "filename4");
  12203. EXPECT_EQ(items[1].content_type, "");
  12204. });
  12205. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12206. const ContentReader &content_reader) {
  12207. ASSERT_TRUE(req.is_multipart_form_data());
  12208. std::vector<FormData> items;
  12209. content_reader(
  12210. [&](const FormData &file) {
  12211. items.push_back(file);
  12212. return true;
  12213. },
  12214. [&](const char *data, size_t data_length) {
  12215. items.back().content.append(data, data_length);
  12216. return true;
  12217. });
  12218. ASSERT_TRUE(items.size() == 4);
  12219. EXPECT_EQ(std::string(items[0].name), "name1");
  12220. EXPECT_EQ(items[0].content, "Testing123");
  12221. EXPECT_EQ(items[0].filename, "filename1");
  12222. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12223. EXPECT_EQ(items[1].name, "name2");
  12224. EXPECT_EQ(items[1].content, "Testing456");
  12225. EXPECT_EQ(items[1].filename, "");
  12226. EXPECT_EQ(items[1].content_type, "");
  12227. EXPECT_EQ(items[2].name, "name3");
  12228. EXPECT_EQ(items[2].content, rand1);
  12229. EXPECT_EQ(items[2].filename, "filename3");
  12230. EXPECT_EQ(items[2].content_type, "");
  12231. EXPECT_EQ(items[3].name, "name4");
  12232. EXPECT_EQ(items[3].content, rand2);
  12233. EXPECT_EQ(items[3].filename, "filename4");
  12234. EXPECT_EQ(items[3].content_type, "");
  12235. });
  12236. auto port = svr.bind_to_any_port("localhost");
  12237. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. {
  12245. SSLClient cli("localhost", port);
  12246. cli.enable_server_certificate_verification(false);
  12247. UploadFormDataItems items{
  12248. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12249. {"name2", "Testing456", "", ""}, // not a file
  12250. };
  12251. {
  12252. auto res = cli.Post("/post-none", {}, {}, {});
  12253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12254. ASSERT_EQ(StatusCode::OK_200, res->status);
  12255. }
  12256. FormDataProviderItems providers;
  12257. {
  12258. auto res =
  12259. cli.Post("/post-items", {}, items, providers); // empty providers
  12260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12261. ASSERT_EQ(StatusCode::OK_200, res->status);
  12262. }
  12263. providers.push_back({"name3",
  12264. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12265. // test the offset is given correctly at each step
  12266. if (!offset)
  12267. sink.os.write(rand1.data(), 30);
  12268. else if (offset == 30)
  12269. sink.os.write(rand1.data() + 30, 300);
  12270. else if (offset == 330)
  12271. sink.os.write(rand1.data() + 330, 670);
  12272. else if (offset == rand1.size())
  12273. sink.done();
  12274. return true;
  12275. },
  12276. "filename3",
  12277. {}});
  12278. providers.push_back({"name4",
  12279. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12280. // test the offset is given correctly at each step
  12281. if (!offset)
  12282. sink.os.write(rand2.data(), 2000);
  12283. else if (offset == 2000)
  12284. sink.os.write(rand2.data() + 2000, 1);
  12285. else if (offset == 2001)
  12286. sink.os.write(rand2.data() + 2001, 999);
  12287. else if (offset == rand2.size())
  12288. sink.done();
  12289. return true;
  12290. },
  12291. "filename4",
  12292. {}});
  12293. {
  12294. auto res = cli.Post("/post-providers", {}, {}, providers);
  12295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12296. ASSERT_EQ(StatusCode::OK_200, res->status);
  12297. }
  12298. {
  12299. auto res = cli.Post("/post-both", {}, items, providers);
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. ASSERT_EQ(StatusCode::OK_200, res->status);
  12302. }
  12303. }
  12304. }
  12305. TEST(MultipartFormDataTest, BadHeader) {
  12306. Server svr;
  12307. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12308. res.set_content("ok", "text/plain");
  12309. });
  12310. thread t = thread([&] { svr.listen(HOST, PORT); });
  12311. auto se = detail::scope_exit([&] {
  12312. svr.stop();
  12313. t.join();
  12314. ASSERT_FALSE(svr.is_running());
  12315. });
  12316. svr.wait_until_ready();
  12317. const std::string body =
  12318. "This is the preamble. It is to be ignored, though it\r\n"
  12319. "is a handy place for composition agents to include an\r\n"
  12320. "explanatory note to non-MIME conformant readers.\r\n"
  12321. "\r\n"
  12322. "\r\n"
  12323. "--simple boundary\r\n"
  12324. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12325. ": BAD...\r\n"
  12326. "\r\n"
  12327. "value1\r\n"
  12328. "--simple boundary\r\n"
  12329. "Content-Disposition: form-data; name=\"field2\"; "
  12330. "filename=\"example.txt\"\r\n"
  12331. "\r\n"
  12332. "value2\r\n"
  12333. "--simple boundary--\r\n"
  12334. "This is the epilogue. It is also to be ignored.\r\n";
  12335. std::string content_type =
  12336. R"(multipart/form-data; boundary="simple boundary")";
  12337. Client cli(HOST, PORT);
  12338. auto res = cli.Post("/post", body, content_type.c_str());
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12341. }
  12342. TEST(MultipartFormDataTest, WithPreamble) {
  12343. Server svr;
  12344. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12345. res.set_content("ok", "text/plain");
  12346. });
  12347. thread t = thread([&] { svr.listen(HOST, PORT); });
  12348. auto se = detail::scope_exit([&] {
  12349. svr.stop();
  12350. t.join();
  12351. ASSERT_FALSE(svr.is_running());
  12352. });
  12353. svr.wait_until_ready();
  12354. const std::string body =
  12355. "This is the preamble. It is to be ignored, though it\r\n"
  12356. "is a handy place for composition agents to include an\r\n"
  12357. "explanatory note to non-MIME conformant readers.\r\n"
  12358. "\r\n"
  12359. "\r\n"
  12360. "--simple boundary\r\n"
  12361. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12362. "\r\n"
  12363. "value1\r\n"
  12364. "--simple boundary\r\n"
  12365. "Content-Disposition: form-data; name=\"field2\"; "
  12366. "filename=\"example.txt\"\r\n"
  12367. "\r\n"
  12368. "value2\r\n"
  12369. "--simple boundary--\r\n"
  12370. "This is the epilogue. It is also to be ignored.\r\n";
  12371. std::string content_type =
  12372. R"(multipart/form-data; boundary="simple boundary")";
  12373. Client cli(HOST, PORT);
  12374. auto res = cli.Post("/post", body, content_type.c_str());
  12375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12376. EXPECT_EQ(StatusCode::OK_200, res->status);
  12377. }
  12378. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12380. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12381. const ContentReader &content_reader) {
  12382. if (req.is_multipart_form_data()) {
  12383. std::vector<FormData> items;
  12384. content_reader(
  12385. [&](const FormData &file) {
  12386. items.push_back(file);
  12387. return true;
  12388. },
  12389. [&](const char *data, size_t data_length) {
  12390. items.back().content.append(data, data_length);
  12391. return true;
  12392. });
  12393. EXPECT_TRUE(std::string(items[0].name) == "document");
  12394. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12395. EXPECT_TRUE(items[0].filename == "2MB_data");
  12396. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12397. EXPECT_TRUE(items[1].name == "hello");
  12398. EXPECT_TRUE(items[1].content == "world");
  12399. EXPECT_TRUE(items[1].filename == "");
  12400. EXPECT_TRUE(items[1].content_type == "");
  12401. } else {
  12402. std::string body;
  12403. content_reader([&](const char *data, size_t data_length) {
  12404. body.append(data, data_length);
  12405. return true;
  12406. });
  12407. }
  12408. });
  12409. auto port = svr.bind_to_any_port("localhost");
  12410. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12411. auto se = detail::scope_exit([&] {
  12412. svr.stop();
  12413. t.join();
  12414. ASSERT_FALSE(svr.is_running());
  12415. });
  12416. svr.wait_until_ready();
  12417. {
  12418. std::string data(1024 * 1024 * 2, '.');
  12419. std::stringstream buffer;
  12420. buffer << data;
  12421. SSLClient cli("localhost", port);
  12422. cli.enable_server_certificate_verification(false);
  12423. UploadFormDataItems items{
  12424. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12425. {"hello", "world", "", ""},
  12426. };
  12427. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12429. ASSERT_EQ(StatusCode::OK_200, res->status);
  12430. }
  12431. }
  12432. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12433. std::string data(1024 * 1024 * 2, '&');
  12434. std::stringstream buffer;
  12435. buffer << data;
  12436. Client cli("https://localhost:8080");
  12437. UploadFormDataItems items{
  12438. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12439. {"hello", "world", "", ""},
  12440. };
  12441. for (const char &c : " \t\r\n") {
  12442. auto res =
  12443. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12444. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12445. ASSERT_FALSE(res);
  12446. }
  12447. }
  12448. TEST(MultipartFormDataTest, PutFormData) {
  12449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12450. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12451. const ContentReader &content_reader) {
  12452. if (req.is_multipart_form_data()) {
  12453. std::vector<FormData> items;
  12454. content_reader(
  12455. [&](const FormData &file) {
  12456. items.push_back(file);
  12457. return true;
  12458. },
  12459. [&](const char *data, size_t data_length) {
  12460. items.back().content.append(data, data_length);
  12461. return true;
  12462. });
  12463. EXPECT_TRUE(std::string(items[0].name) == "document");
  12464. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12465. EXPECT_TRUE(items[0].filename == "2MB_data");
  12466. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12467. EXPECT_TRUE(items[1].name == "hello");
  12468. EXPECT_TRUE(items[1].content == "world");
  12469. EXPECT_TRUE(items[1].filename == "");
  12470. EXPECT_TRUE(items[1].content_type == "");
  12471. } else {
  12472. std::string body;
  12473. content_reader([&](const char *data, size_t data_length) {
  12474. body.append(data, data_length);
  12475. return true;
  12476. });
  12477. }
  12478. });
  12479. auto port = svr.bind_to_any_port("localhost");
  12480. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12481. auto se = detail::scope_exit([&] {
  12482. svr.stop();
  12483. t.join();
  12484. ASSERT_FALSE(svr.is_running());
  12485. });
  12486. svr.wait_until_ready();
  12487. {
  12488. std::string data(1024 * 1024 * 2, '&');
  12489. std::stringstream buffer;
  12490. buffer << data;
  12491. SSLClient cli("localhost", port);
  12492. cli.enable_server_certificate_verification(false);
  12493. UploadFormDataItems items{
  12494. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12495. {"hello", "world", "", ""},
  12496. };
  12497. auto res = cli.Put("/put", items);
  12498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12499. ASSERT_EQ(StatusCode::OK_200, res->status);
  12500. }
  12501. }
  12502. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12504. svr.Put("/put_customboundary",
  12505. [&](const Request &req, const Response & /*res*/,
  12506. const ContentReader &content_reader) {
  12507. if (req.is_multipart_form_data()) {
  12508. std::vector<FormData> items;
  12509. content_reader(
  12510. [&](const FormData &file) {
  12511. items.push_back(file);
  12512. return true;
  12513. },
  12514. [&](const char *data, size_t data_length) {
  12515. items.back().content.append(data, data_length);
  12516. return true;
  12517. });
  12518. EXPECT_TRUE(std::string(items[0].name) == "document");
  12519. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12520. EXPECT_TRUE(items[0].filename == "2MB_data");
  12521. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12522. EXPECT_TRUE(items[1].name == "hello");
  12523. EXPECT_TRUE(items[1].content == "world");
  12524. EXPECT_TRUE(items[1].filename == "");
  12525. EXPECT_TRUE(items[1].content_type == "");
  12526. } else {
  12527. std::string body;
  12528. content_reader([&](const char *data, size_t data_length) {
  12529. body.append(data, data_length);
  12530. return true;
  12531. });
  12532. }
  12533. });
  12534. auto port = svr.bind_to_any_port("localhost");
  12535. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12536. auto se = detail::scope_exit([&] {
  12537. svr.stop();
  12538. t.join();
  12539. ASSERT_FALSE(svr.is_running());
  12540. });
  12541. svr.wait_until_ready();
  12542. {
  12543. std::string data(1024 * 1024 * 2, '&');
  12544. std::stringstream buffer;
  12545. buffer << data;
  12546. SSLClient cli("localhost", port);
  12547. cli.enable_server_certificate_verification(false);
  12548. UploadFormDataItems items{
  12549. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12550. {"hello", "world", "", ""},
  12551. };
  12552. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12554. ASSERT_EQ(StatusCode::OK_200, res->status);
  12555. }
  12556. }
  12557. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12558. std::string data(1024 * 1024 * 2, '&');
  12559. std::stringstream buffer;
  12560. buffer << data;
  12561. Client cli("https://localhost:8080");
  12562. cli.enable_server_certificate_verification(false);
  12563. UploadFormDataItems items{
  12564. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12565. {"hello", "world", "", ""},
  12566. };
  12567. for (const char &c : " \t\r\n") {
  12568. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12569. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12570. ASSERT_FALSE(res);
  12571. }
  12572. }
  12573. TEST(MultipartFormDataTest, AlternateFilename) {
  12574. auto handled = false;
  12575. Server svr;
  12576. svr.Post("/test", [&](const Request &req, Response &res) {
  12577. ASSERT_EQ(2u, req.form.files.size());
  12578. ASSERT_EQ(1u, req.form.fields.size());
  12579. // Test files
  12580. const auto &file1 = req.form.get_file("file1");
  12581. ASSERT_EQ("file1", file1.name);
  12582. ASSERT_EQ("A.txt", file1.filename);
  12583. ASSERT_EQ("text/plain", file1.content_type);
  12584. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12585. const auto &file2 = req.form.get_file("file2");
  12586. ASSERT_EQ("file2", file2.name);
  12587. ASSERT_EQ("a.html", file2.filename);
  12588. ASSERT_EQ("text/html", file2.content_type);
  12589. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12590. file2.content);
  12591. // Test text field
  12592. const auto &text = req.form.get_field("text");
  12593. ASSERT_EQ("text default", text);
  12594. res.set_content("ok", "text/plain");
  12595. handled = true;
  12596. });
  12597. thread t = thread([&] { svr.listen(HOST, PORT); });
  12598. auto se = detail::scope_exit([&] {
  12599. svr.stop();
  12600. t.join();
  12601. ASSERT_FALSE(svr.is_running());
  12602. ASSERT_TRUE(handled);
  12603. });
  12604. svr.wait_until_ready();
  12605. auto req = "POST /test HTTP/1.1\r\n"
  12606. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12607. "Content-Length: 399\r\n"
  12608. "\r\n"
  12609. "----------\r\n"
  12610. "Content-Disposition: form-data; name=\"text\"\r\n"
  12611. "\r\n"
  12612. "text default\r\n"
  12613. "----------\r\n"
  12614. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12615. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12616. "Content-Type: text/plain\r\n"
  12617. "\r\n"
  12618. "Content of a.txt.\r\n"
  12619. "\r\n"
  12620. "----------\r\n"
  12621. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12622. "\"a.html\"\r\n"
  12623. "Content-Type: text/html\r\n"
  12624. "\r\n"
  12625. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12626. "\r\n"
  12627. "------------\r\n";
  12628. ASSERT_TRUE(send_request(1, req));
  12629. }
  12630. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12631. auto handled = false;
  12632. Server svr;
  12633. svr.Post("/test", [&](const Request &req, Response &res) {
  12634. // Case-insensitive "utf-8''" prefix with a long value
  12635. const auto &file = req.form.get_file("file1");
  12636. ASSERT_EQ("file1", file.name);
  12637. // 8000 chars exercises both the Content-Disposition parser and the
  12638. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12639. // Prior to the fix, std::regex_match on this header would cause O(N)
  12640. // stack recursion in libstdc++, leading to SIGSEGV.
  12641. std::string expected_filename(8000, 'A');
  12642. ASSERT_EQ(expected_filename, file.filename);
  12643. res.set_content("ok", "text/plain");
  12644. handled = true;
  12645. });
  12646. thread t = thread([&] { svr.listen(HOST, PORT); });
  12647. auto se = detail::scope_exit([&] {
  12648. svr.stop();
  12649. t.join();
  12650. ASSERT_FALSE(svr.is_running());
  12651. ASSERT_TRUE(handled);
  12652. });
  12653. svr.wait_until_ready();
  12654. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12655. // Regression test for GHSA-qq6v-r583-3h69
  12656. std::string long_filename(8000, 'A');
  12657. std::string body = "----------\r\n"
  12658. "Content-Disposition: form-data; name=\"file1\"; "
  12659. "filename*=\"Utf-8''" +
  12660. long_filename +
  12661. "\"\r\n"
  12662. "\r\n"
  12663. "hello\r\n"
  12664. "------------\r\n";
  12665. auto req = "POST /test HTTP/1.1\r\n"
  12666. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12667. "Content-Length: " +
  12668. std::to_string(body.size()) + "\r\n\r\n" + body;
  12669. ASSERT_TRUE(send_request(1, req));
  12670. }
  12671. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12672. auto handled = false;
  12673. Server svr;
  12674. svr.Post("/test", [&](const Request &req, Response &) {
  12675. ASSERT_EQ(2u, req.form.fields.size());
  12676. const auto &text1 = req.form.get_field("text1");
  12677. ASSERT_EQ("text1", text1);
  12678. const auto &text2 = req.form.get_field("text2");
  12679. ASSERT_EQ("text2", text2);
  12680. handled = true;
  12681. });
  12682. thread t = thread([&] { svr.listen(HOST, PORT); });
  12683. auto se = detail::scope_exit([&] {
  12684. svr.stop();
  12685. t.join();
  12686. ASSERT_FALSE(svr.is_running());
  12687. ASSERT_TRUE(handled);
  12688. });
  12689. svr.wait_until_ready();
  12690. auto req = "POST /test HTTP/1.1\r\n"
  12691. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12692. "Content-Length: 146\r\n"
  12693. "\r\n----------\r\n"
  12694. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12695. "\r\n"
  12696. "text1"
  12697. "\r\n----------\r\n"
  12698. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12699. "\r\n"
  12700. "text2"
  12701. "\r\n------------";
  12702. std::string response;
  12703. ASSERT_TRUE(send_request(1, req, &response));
  12704. ASSERT_EQ("200", response.substr(9, 3));
  12705. }
  12706. TEST(MultipartFormDataTest, ContentLength) {
  12707. auto handled = false;
  12708. Server svr;
  12709. svr.Post("/test", [&](const Request &req, Response &) {
  12710. ASSERT_EQ(2u, req.form.fields.size());
  12711. const auto &text1 = req.form.get_field("text1");
  12712. ASSERT_EQ("text1", text1);
  12713. const auto &text2 = req.form.get_field("text2");
  12714. ASSERT_EQ("text2", text2);
  12715. handled = true;
  12716. });
  12717. thread t = thread([&] { svr.listen(HOST, PORT); });
  12718. auto se = detail::scope_exit([&] {
  12719. svr.stop();
  12720. t.join();
  12721. ASSERT_FALSE(svr.is_running());
  12722. ASSERT_TRUE(handled);
  12723. });
  12724. svr.wait_until_ready();
  12725. auto req = "POST /test HTTP/1.1\r\n"
  12726. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12727. "Content-Length: 167\r\n"
  12728. "\r\n----------\r\n"
  12729. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12730. "Content-Length: 5\r\n"
  12731. "\r\n"
  12732. "text1"
  12733. "\r\n----------\r\n"
  12734. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12735. "\r\n"
  12736. "text2"
  12737. "\r\n------------\r\n";
  12738. std::string response;
  12739. ASSERT_TRUE(send_request(1, req, &response));
  12740. ASSERT_EQ("200", response.substr(9, 3));
  12741. }
  12742. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12743. auto handled = false;
  12744. Server svr;
  12745. svr.Post("/test", [&](const Request &req, Response &) {
  12746. ASSERT_EQ(2u, req.form.fields.size());
  12747. const auto &text1 = req.form.get_field("text1");
  12748. ASSERT_EQ("text1", text1);
  12749. // TODO: Add header access for text fields if needed
  12750. const auto &text2 = req.form.get_field("text2");
  12751. ASSERT_EQ("text2", text2);
  12752. // TODO: Header access for text fields needs to be implemented
  12753. // auto &headers = it->second.headers;
  12754. // ASSERT_EQ(3U, headers.size());
  12755. // auto custom_header = headers.find("x-whatever");
  12756. // ASSERT_TRUE(custom_header != headers.end());
  12757. // ASSERT_NE("customvalue", custom_header->second);
  12758. // ASSERT_EQ("CustomValue", custom_header->second);
  12759. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12760. handled = true;
  12761. });
  12762. thread t = thread([&] { svr.listen(HOST, PORT); });
  12763. auto se = detail::scope_exit([&] {
  12764. svr.stop();
  12765. t.join();
  12766. ASSERT_FALSE(svr.is_running());
  12767. ASSERT_TRUE(handled);
  12768. });
  12769. svr.wait_until_ready();
  12770. auto req = "POST /test HTTP/1.1\r\n"
  12771. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12772. "Content-Length: 232\r\n"
  12773. "\r\n----------\r\n"
  12774. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12775. "Content-Length: 5\r\n"
  12776. "X-Test: 1\r\n"
  12777. "\r\n"
  12778. "text1"
  12779. "\r\n----------\r\n"
  12780. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12781. "Content-Type: text/plain\r\n"
  12782. "X-Whatever: CustomValue\r\n"
  12783. "\r\n"
  12784. "text2"
  12785. "\r\n------------\r\n"
  12786. "That should be disregarded. Not even read";
  12787. std::string response;
  12788. ASSERT_TRUE(send_request(1, req, &response));
  12789. ASSERT_EQ("200", response.substr(9, 3));
  12790. }
  12791. TEST(MultipartFormDataTest, LargeHeader) {
  12792. auto handled = false;
  12793. Server svr;
  12794. svr.Post("/test", [&](const Request &req, Response &) {
  12795. ASSERT_EQ(1u, req.form.fields.size());
  12796. const auto &text = req.form.get_field("name1");
  12797. ASSERT_EQ("text1", text);
  12798. handled = true;
  12799. });
  12800. thread t = thread([&] { svr.listen(HOST, PORT); });
  12801. auto se = detail::scope_exit([&] {
  12802. svr.stop();
  12803. t.join();
  12804. ASSERT_FALSE(svr.is_running());
  12805. ASSERT_TRUE(handled);
  12806. });
  12807. svr.wait_until_ready();
  12808. auto boundary = std::string("cpp-httplib-multipart-data");
  12809. std::string content = "--" + boundary +
  12810. "\r\n"
  12811. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12812. "\r\n"
  12813. "text1\r\n"
  12814. "--" +
  12815. boundary + "--\r\n";
  12816. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12817. "Content-Type: multipart/form-data;boundary=" +
  12818. boundary +
  12819. "\r\n"
  12820. "Content-Length: " +
  12821. std::to_string(content.size()) +
  12822. "\r\n"
  12823. "Dummy-Header: ";
  12824. std::string header_suffix = "\r\n"
  12825. "\r\n";
  12826. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12827. size_t header_dummy_size =
  12828. read_buff_size -
  12829. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12830. auto header_dummy = std::string(header_dummy_size, '@');
  12831. auto req = header_prefix + header_dummy + header_suffix + content;
  12832. std::string response;
  12833. ASSERT_TRUE(send_request(1, req, &response));
  12834. ASSERT_EQ("200", response.substr(9, 3));
  12835. }
  12836. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12837. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12838. // (not chunked Transfer-Encoding) after the streaming refactor.
  12839. auto handled = false;
  12840. Server svr;
  12841. svr.Post("/upload", [&](const Request &req, Response &res) {
  12842. auto cl_it = req.headers.find("Content-Length");
  12843. EXPECT_TRUE(cl_it != req.headers.end());
  12844. auto te_it = req.headers.find("Transfer-Encoding");
  12845. EXPECT_TRUE(te_it == req.headers.end());
  12846. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12847. res.set_content("ok", "text/plain");
  12848. handled = true;
  12849. });
  12850. auto port = svr.bind_to_any_port(HOST);
  12851. auto t = thread([&] { svr.listen_after_bind(); });
  12852. auto se = detail::scope_exit([&] {
  12853. svr.stop();
  12854. t.join();
  12855. ASSERT_FALSE(svr.is_running());
  12856. ASSERT_TRUE(handled);
  12857. });
  12858. svr.wait_until_ready();
  12859. UploadFormDataItems items = {
  12860. {"field1", "hello", "", "text/plain"},
  12861. {"file1", "world", "test.txt", "application/octet-stream"},
  12862. };
  12863. Client cli(HOST, port);
  12864. auto res = cli.Post("/upload", {}, items);
  12865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12866. EXPECT_EQ(StatusCode::OK_200, res->status);
  12867. }
  12868. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12869. // Verify that make_multipart_content_provider coalesces many small segments
  12870. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12871. constexpr size_t kItemCount = 1000;
  12872. UploadFormDataItems items;
  12873. items.reserve(kItemCount);
  12874. for (size_t i = 0; i < kItemCount; i++) {
  12875. items.push_back(
  12876. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12877. }
  12878. const std::string boundary = "----test-boundary";
  12879. auto content_length = detail::get_multipart_content_length(items, boundary);
  12880. auto provider = detail::make_multipart_content_provider(items, boundary);
  12881. // Drive the provider the same way write_content_with_progress does
  12882. size_t write_count = 0;
  12883. size_t total_bytes = 0;
  12884. DataSink sink;
  12885. size_t offset = 0;
  12886. sink.write = [&](const char *d, size_t l) -> bool {
  12887. (void)d;
  12888. write_count++;
  12889. total_bytes += l;
  12890. offset += l;
  12891. return true;
  12892. };
  12893. sink.is_writable = []() -> bool { return true; };
  12894. while (offset < content_length) {
  12895. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12896. }
  12897. EXPECT_EQ(content_length, total_bytes);
  12898. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12899. // With buffering into 64KB blocks, write_count should be much smaller.
  12900. auto segment_count = 3 * kItemCount + 1;
  12901. EXPECT_LT(write_count, segment_count / 10);
  12902. }
  12903. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12904. // Integration test: send many UploadFormDataItems and verify the server
  12905. // receives all of them correctly (#2410).
  12906. constexpr size_t kItemCount = 500;
  12907. auto handled = false;
  12908. Server svr;
  12909. svr.Post("/upload", [&](const Request &req, Response &res) {
  12910. EXPECT_EQ(kItemCount, req.form.fields.size());
  12911. for (size_t i = 0; i < kItemCount; i++) {
  12912. auto key = "field" + std::to_string(i);
  12913. auto val = "value" + std::to_string(i);
  12914. auto it = req.form.fields.find(key);
  12915. if (it != req.form.fields.end()) {
  12916. EXPECT_EQ(val, it->second.content);
  12917. } else {
  12918. ADD_FAILURE() << "Missing field: " << key;
  12919. }
  12920. }
  12921. res.set_content("ok", "text/plain");
  12922. handled = true;
  12923. });
  12924. auto port = svr.bind_to_any_port(HOST);
  12925. auto t = thread([&] { svr.listen_after_bind(); });
  12926. auto se = detail::scope_exit([&] {
  12927. svr.stop();
  12928. t.join();
  12929. ASSERT_FALSE(svr.is_running());
  12930. ASSERT_TRUE(handled);
  12931. });
  12932. svr.wait_until_ready();
  12933. UploadFormDataItems items;
  12934. items.reserve(kItemCount);
  12935. for (size_t i = 0; i < kItemCount; i++) {
  12936. items.push_back(
  12937. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12938. }
  12939. Client cli(HOST, port);
  12940. auto res = cli.Post("/upload", items);
  12941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12942. EXPECT_EQ(StatusCode::OK_200, res->status);
  12943. }
  12944. TEST(MultipartFormDataTest, MakeFileProvider) {
  12945. // Verify make_file_provider sends a file's contents correctly.
  12946. const std::string file_content(4096, 'Z');
  12947. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12948. {
  12949. std::ofstream ofs(tmp_path, std::ios::binary);
  12950. ofs.write(file_content.data(),
  12951. static_cast<std::streamsize>(file_content.size()));
  12952. }
  12953. auto handled = false;
  12954. Server svr;
  12955. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12956. const ContentReader &content_reader) {
  12957. ASSERT_TRUE(req.is_multipart_form_data());
  12958. std::vector<FormData> items;
  12959. content_reader(
  12960. [&](const FormData &file) {
  12961. items.push_back(file);
  12962. return true;
  12963. },
  12964. [&](const char *data, size_t data_length) {
  12965. items.back().content.append(data, data_length);
  12966. return true;
  12967. });
  12968. ASSERT_EQ(1u, items.size());
  12969. EXPECT_EQ("myfile", items[0].name);
  12970. EXPECT_EQ("data.bin", items[0].filename);
  12971. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12972. EXPECT_EQ(file_content, items[0].content);
  12973. handled = true;
  12974. });
  12975. auto port = svr.bind_to_any_port(HOST);
  12976. auto t = thread([&] { svr.listen_after_bind(); });
  12977. auto se = detail::scope_exit([&] {
  12978. svr.stop();
  12979. t.join();
  12980. ASSERT_FALSE(svr.is_running());
  12981. ASSERT_TRUE(handled);
  12982. std::remove(tmp_path.c_str());
  12983. });
  12984. svr.wait_until_ready();
  12985. FormDataProviderItems providers;
  12986. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12987. "application/octet-stream"));
  12988. Client cli(HOST, port);
  12989. auto res = cli.Post("/upload", {}, {}, providers);
  12990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12991. EXPECT_EQ(StatusCode::OK_200, res->status);
  12992. }
  12993. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12994. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12995. // (100) headers is rejected with a 400 Bad Request response.
  12996. Server svr;
  12997. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12998. res.set_content("ok", "text/plain");
  12999. });
  13000. thread t = thread([&] { svr.listen(HOST, PORT); });
  13001. auto se = detail::scope_exit([&] {
  13002. svr.stop();
  13003. t.join();
  13004. ASSERT_FALSE(svr.is_running());
  13005. });
  13006. svr.wait_until_ready();
  13007. // Build a multipart part with 101 custom headers (exceeding
  13008. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13009. std::stringstream body;
  13010. body << "--simpleboundary\r\n"
  13011. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13012. for (int i = 0; i < 101; i++) {
  13013. body << "X-Custom-Header-" << i << ": value\r\n";
  13014. }
  13015. body << "\r\n"
  13016. << "value1\r\n"
  13017. << "--simpleboundary--\r\n";
  13018. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13019. Client cli(HOST, PORT);
  13020. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13022. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13023. }
  13024. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13025. // A body that never contains the declared boundary must not be accumulated
  13026. // while the parser waits for it. Buffering it would also make every read
  13027. // rescan everything seen so far, which is quadratic in the body size.
  13028. Server svr;
  13029. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13030. res.set_content("ok", "text/plain");
  13031. });
  13032. auto port = svr.bind_to_any_port(HOST);
  13033. thread t = thread([&] { svr.listen_after_bind(); });
  13034. auto se = detail::scope_exit([&] {
  13035. svr.stop();
  13036. t.join();
  13037. ASSERT_FALSE(svr.is_running());
  13038. });
  13039. svr.wait_until_ready();
  13040. Client cli(HOST, port);
  13041. cli.set_read_timeout(60, 0);
  13042. cli.set_write_timeout(60, 0);
  13043. // '-' is the worst case: it matches the first character of the boundary, so
  13044. // every position has to be checked against it.
  13045. auto post_dashes = [&](size_t size) {
  13046. const std::string body(size, '-');
  13047. auto start = std::chrono::steady_clock::now();
  13048. auto res =
  13049. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13050. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13051. std::chrono::steady_clock::now() - start)
  13052. .count();
  13053. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13054. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13055. return ms;
  13056. };
  13057. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13058. // Windows.
  13059. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13060. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13061. // Comparing the two sizes rather than checking an absolute duration keeps
  13062. // this meaningful across build types and CI load, both of which move the
  13063. // absolute numbers by more than an order of magnitude. Four times the bytes
  13064. // costs about four times the time when parsing is linear, and about sixteen
  13065. // times when the body is buffered and rescanned.
  13066. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13067. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13068. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13069. << "ms, which suggests the body is being buffered and rescanned";
  13070. }
  13071. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13072. // A boundary can only be followed by CRLF or by "--", so anything else is
  13073. // malformed no matter what comes next. The parser must say so right away
  13074. // instead of buffering the rest of the declared body.
  13075. Server svr;
  13076. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13077. res.set_content("ok", "text/plain");
  13078. });
  13079. auto port = svr.bind_to_any_port(HOST);
  13080. thread t = thread([&] { svr.listen_after_bind(); });
  13081. auto se = detail::scope_exit([&] {
  13082. svr.stop();
  13083. t.join();
  13084. ASSERT_FALSE(svr.is_running());
  13085. });
  13086. svr.wait_until_ready();
  13087. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13088. // buffers instead of failing would still be waiting for the remaining bytes.
  13089. const std::string body = "--zzzz\r\n"
  13090. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13091. "\r\n"
  13092. "text1"
  13093. "\r\n--zzzzXX";
  13094. const std::string req = "POST /post HTTP/1.1\r\n"
  13095. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13096. "Content-Length: 1048576\r\n"
  13097. "\r\n" +
  13098. body;
  13099. std::string response;
  13100. ASSERT_TRUE(send_request(3, req, &response, port));
  13101. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13102. EXPECT_EQ("400", response.substr(9, 3));
  13103. }
  13104. // Posts a multipart body split into two writes, so that the server sees the
  13105. // split at whatever offset the caller chose, and expects the single "text1"
  13106. // field to come through.
  13107. static void expect_split_multipart_ok(const std::string &body1,
  13108. const std::string &body2) {
  13109. auto handled = false;
  13110. Server svr;
  13111. svr.Post("/post", [&](const Request &req, Response &) {
  13112. EXPECT_EQ(1u, req.form.fields.size());
  13113. EXPECT_EQ("text1", req.form.get_field("text1"));
  13114. handled = true;
  13115. });
  13116. auto port = svr.bind_to_any_port(HOST);
  13117. thread t = thread([&] { svr.listen_after_bind(); });
  13118. auto se = detail::scope_exit([&] {
  13119. svr.stop();
  13120. t.join();
  13121. ASSERT_FALSE(svr.is_running());
  13122. ASSERT_TRUE(handled);
  13123. });
  13124. svr.wait_until_ready();
  13125. // "Connection: close" makes the server close once it has answered, so the
  13126. // response drain ends immediately instead of idling until the read timeout.
  13127. const std::string head =
  13128. "POST /post HTTP/1.1\r\n"
  13129. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13130. "Connection: close\r\n"
  13131. "Content-Length: " +
  13132. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13133. std::string response;
  13134. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13135. ASSERT_GE(response.size(), 12u) << "no response";
  13136. EXPECT_EQ("200", response.substr(9, 3));
  13137. }
  13138. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13139. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13140. // ignored, including when it does not arrive in the same read as the
  13141. // close-delimiter itself.
  13142. expect_split_multipart_ok("--zzzz\r\n"
  13143. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13144. "\r\n"
  13145. "text1"
  13146. "\r\n--zzzz--",
  13147. "\r\nthis epilogue must be ignored\r\n");
  13148. }
  13149. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13150. // The initial boundary may be preceded by a preamble of any length and may
  13151. // straddle a read boundary. Discarding data while waiting for it must not
  13152. // throw away a partial boundary sitting at the end of the buffer.
  13153. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13154. "zz\r\n"
  13155. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13156. "\r\n"
  13157. "text1"
  13158. "\r\n--zzzz--\r\n");
  13159. }
  13160. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13161. // The received boundary was only checked for being non-empty, so it could be
  13162. // as long as a header is allowed to be. The parser scans the body for
  13163. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13164. // costs a nearly full comparison at nearly every position, making the
  13165. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13166. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13167. Server svr;
  13168. svr.Post("/post", [](const Request &req, Response &res) {
  13169. EXPECT_EQ(1u, req.form.fields.size());
  13170. EXPECT_EQ("text1", req.form.get_field("text1"));
  13171. res.set_content("ok", "text/plain");
  13172. });
  13173. auto port = svr.bind_to_any_port(HOST);
  13174. thread t = thread([&] { svr.listen_after_bind(); });
  13175. auto se = detail::scope_exit([&] {
  13176. svr.stop();
  13177. t.join();
  13178. ASSERT_FALSE(svr.is_running());
  13179. });
  13180. svr.wait_until_ready();
  13181. Client cli(HOST, port);
  13182. auto post_with_boundary_of_length = [&](size_t len) {
  13183. const std::string boundary(len, 'a');
  13184. const std::string body =
  13185. "--" + boundary +
  13186. "\r\n"
  13187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13188. "\r\n"
  13189. "text1"
  13190. "\r\n--" +
  13191. boundary + "--\r\n";
  13192. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13193. };
  13194. auto res = post_with_boundary_of_length(70);
  13195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13196. EXPECT_EQ(StatusCode::OK_200, res->status);
  13197. res = post_with_boundary_of_length(71);
  13198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13199. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13200. }
  13201. TEST(MakeFileBodyTest, Basic) {
  13202. const std::string file_content(4096, 'Z');
  13203. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13204. {
  13205. std::ofstream ofs(tmp_path, std::ios::binary);
  13206. ofs.write(file_content.data(),
  13207. static_cast<std::streamsize>(file_content.size()));
  13208. }
  13209. auto handled = false;
  13210. Server svr;
  13211. svr.Post("/upload", [&](const Request &req, Response &res) {
  13212. EXPECT_EQ(file_content, req.body);
  13213. handled = true;
  13214. res.status = StatusCode::OK_200;
  13215. });
  13216. auto port = svr.bind_to_any_port(HOST);
  13217. auto t = thread([&] { svr.listen_after_bind(); });
  13218. auto se = detail::scope_exit([&] {
  13219. svr.stop();
  13220. t.join();
  13221. ASSERT_FALSE(svr.is_running());
  13222. ASSERT_TRUE(handled);
  13223. std::remove(tmp_path.c_str());
  13224. });
  13225. svr.wait_until_ready();
  13226. auto fb = make_file_body(tmp_path);
  13227. ASSERT_GT(fb.first, 0u);
  13228. Client cli(HOST, port);
  13229. auto res =
  13230. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13232. EXPECT_EQ(StatusCode::OK_200, res->status);
  13233. }
  13234. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13235. static constexpr unsigned int number_of_tasks{1000000};
  13236. std::atomic_uint count{0};
  13237. std::unique_ptr<TaskQueue> task_queue{
  13238. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13239. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13240. auto queued = task_queue->enqueue(
  13241. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13242. EXPECT_TRUE(queued);
  13243. }
  13244. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13245. task_queue->shutdown();
  13246. #else
  13247. EXPECT_NO_THROW(task_queue->shutdown());
  13248. #endif
  13249. EXPECT_EQ(number_of_tasks, count.load());
  13250. }
  13251. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13252. static constexpr unsigned int number_of_tasks{1000000};
  13253. static constexpr unsigned int qlimit{2};
  13254. unsigned int queued_count{0};
  13255. std::atomic_uint count{0};
  13256. std::unique_ptr<TaskQueue> task_queue{
  13257. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13258. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13259. if (task_queue->enqueue(
  13260. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13261. queued_count++;
  13262. }
  13263. }
  13264. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13265. task_queue->shutdown();
  13266. #else
  13267. EXPECT_NO_THROW(task_queue->shutdown());
  13268. #endif
  13269. EXPECT_EQ(queued_count, count.load());
  13270. EXPECT_TRUE(queued_count <= number_of_tasks);
  13271. EXPECT_TRUE(queued_count >= qlimit);
  13272. }
  13273. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13274. // Use a short idle timeout so a dynamic thread spawns, times out and
  13275. // exits during the test, and the pool keeps working afterwards.
  13276. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13277. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13278. /*idle_timeout_sec=*/1}};
  13279. std::atomic_uint count{0};
  13280. std::condition_variable cv;
  13281. std::mutex mtx;
  13282. bool release = false;
  13283. // Block the base thread so the second task spawns a dynamic thread.
  13284. EXPECT_TRUE(task_queue->enqueue([&] {
  13285. std::unique_lock<std::mutex> lock(mtx);
  13286. while (!release) {
  13287. cv.wait(lock);
  13288. }
  13289. count++;
  13290. }));
  13291. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13292. // Let the dynamic thread finish its task and exceed the idle timeout.
  13293. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13294. {
  13295. std::unique_lock<std::mutex> lock(mtx);
  13296. release = true;
  13297. }
  13298. cv.notify_all();
  13299. // The pool must still accept and run tasks after the dynamic thread exited.
  13300. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13301. task_queue->shutdown();
  13302. EXPECT_EQ(3u, count.load());
  13303. }
  13304. TEST(TaskQueueTest, MaxQueuedRequests) {
  13305. static constexpr unsigned int qlimit{3};
  13306. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13307. std::condition_variable sem_cv;
  13308. std::mutex sem_mtx;
  13309. int credits = 0;
  13310. bool queued;
  13311. /* Fill up the queue with tasks that will block until we give them credits to
  13312. * complete. */
  13313. for (unsigned int n = 0; n <= qlimit;) {
  13314. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13315. std::unique_lock<std::mutex> lock(sem_mtx);
  13316. while (credits <= 0) {
  13317. sem_cv.wait(lock);
  13318. }
  13319. /* Consume the credit and signal the test code if they are all gone. */
  13320. if (--credits == 0) { sem_cv.notify_one(); }
  13321. });
  13322. if (n < qlimit) {
  13323. /* The first qlimit enqueues must succeed. */
  13324. EXPECT_TRUE(queued);
  13325. } else {
  13326. /* The last one will succeed only when the worker thread
  13327. * starts and dequeues the first blocking task. Although
  13328. * not necessary for the correctness of this test, we sleep for
  13329. * a short while to avoid busy waiting. */
  13330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13331. }
  13332. if (queued) { n++; }
  13333. }
  13334. /* Further enqueues must fail since the queue is full. */
  13335. for (auto i = 0; i < 4; i++) {
  13336. queued = task_queue->enqueue([] {});
  13337. EXPECT_FALSE(queued);
  13338. }
  13339. /* Give the credits to allow the previous tasks to complete. */
  13340. {
  13341. std::unique_lock<std::mutex> lock(sem_mtx);
  13342. credits += qlimit + 1;
  13343. }
  13344. sem_cv.notify_all();
  13345. /* Wait for all the credits to be consumed. */
  13346. {
  13347. std::unique_lock<std::mutex> lock(sem_mtx);
  13348. while (credits > 0) {
  13349. sem_cv.wait(lock);
  13350. }
  13351. }
  13352. /* Check that we are able again to enqueue at least qlimit tasks. */
  13353. for (unsigned int i = 0; i < qlimit; i++) {
  13354. queued = task_queue->enqueue([] {});
  13355. EXPECT_TRUE(queued);
  13356. }
  13357. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13358. task_queue->shutdown();
  13359. #else
  13360. EXPECT_NO_THROW(task_queue->shutdown());
  13361. #endif
  13362. }
  13363. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13364. Server svr;
  13365. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13366. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13367. });
  13368. svr.Get("/hello", [](const Request &req, Response &res) {
  13369. res.set_content(req.get_param_value("key"), "text/plain");
  13370. });
  13371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13372. auto se = detail::scope_exit([&] {
  13373. svr.stop();
  13374. thread.join();
  13375. ASSERT_FALSE(svr.is_running());
  13376. });
  13377. svr.wait_until_ready();
  13378. {
  13379. Client cli(HOST, PORT);
  13380. cli.set_follow_location(true);
  13381. auto res = cli.Get("/");
  13382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13383. EXPECT_EQ(StatusCode::OK_200, res->status);
  13384. EXPECT_EQ("val&key2=val2", res->body);
  13385. }
  13386. }
  13387. #endif
  13388. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13389. Server svr;
  13390. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13391. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13392. });
  13393. svr.Get("/hello", [](const Request &req, Response &res) {
  13394. res.set_content(req.get_param_value("key"), "text/plain");
  13395. });
  13396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13397. auto se = detail::scope_exit([&] {
  13398. svr.stop();
  13399. thread.join();
  13400. ASSERT_FALSE(svr.is_running());
  13401. });
  13402. svr.wait_until_ready();
  13403. {
  13404. Client cli(HOST, PORT);
  13405. cli.set_follow_location(true);
  13406. auto res = cli.Get("/");
  13407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13408. EXPECT_EQ(StatusCode::OK_200, res->status);
  13409. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13410. }
  13411. }
  13412. TEST(RedirectTest, RedirectWithPlusInPath) {
  13413. Server svr;
  13414. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13415. res.set_redirect("/a+b");
  13416. });
  13417. // Route pattern uses regex; escape + as \\+
  13418. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13419. res.set_content(req.path, "text/plain");
  13420. });
  13421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13422. auto se = detail::scope_exit([&] {
  13423. svr.stop();
  13424. thread.join();
  13425. ASSERT_FALSE(svr.is_running());
  13426. });
  13427. svr.wait_until_ready();
  13428. {
  13429. Client cli(HOST, PORT);
  13430. cli.set_follow_location(true);
  13431. auto res = cli.Get("/");
  13432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13433. EXPECT_EQ(StatusCode::OK_200, res->status);
  13434. EXPECT_EQ("/a+b", res->body);
  13435. }
  13436. }
  13437. #ifdef CPPHTTPLIB_SSL_ENABLED
  13438. TEST(RedirectTest, Issue2185_Online) {
  13439. SSLClient client("github.com");
  13440. client.set_follow_location(true);
  13441. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13442. "Coollab-Windows.zip");
  13443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13444. EXPECT_EQ(StatusCode::OK_200, res->status);
  13445. EXPECT_EQ(9920427U, res->body.size());
  13446. }
  13447. #endif
  13448. TEST(VulnerabilityTest, CRLFInjection) {
  13449. Server svr;
  13450. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13451. res.set_content("Hello 1", "text/plain");
  13452. });
  13453. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13454. res.set_content("Hello 2", "text/plain");
  13455. });
  13456. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13457. res.set_content("Hello 3", "text/plain");
  13458. });
  13459. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13460. res.set_content("Hello 4", "text/plain");
  13461. });
  13462. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13463. for (const auto &x : req.headers) {
  13464. auto key = x.first;
  13465. EXPECT_STRNE("evil", key.c_str());
  13466. }
  13467. });
  13468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13469. auto se = detail::scope_exit([&] {
  13470. svr.stop();
  13471. thread.join();
  13472. ASSERT_FALSE(svr.is_running());
  13473. });
  13474. svr.wait_until_ready();
  13475. {
  13476. Client cli(HOST, PORT);
  13477. cli.Post("/test1", "A=B",
  13478. "application/x-www-form-urlencoded\r\nevil: hello1");
  13479. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13480. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13481. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13482. }
  13483. }
  13484. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13485. auto server_thread = std::thread([] {
  13486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13487. default_socket_options(srv);
  13488. sockaddr_in addr{};
  13489. addr.sin_family = AF_INET;
  13490. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13491. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13492. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13493. ::listen(srv, 1);
  13494. sockaddr_in cli_addr{};
  13495. socklen_t cli_len = sizeof(cli_addr);
  13496. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13497. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13498. std::string buf_all;
  13499. char buf[2048];
  13500. ssize_t n;
  13501. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13502. buf_all.append(buf, static_cast<size_t>(n));
  13503. size_t pos;
  13504. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13505. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13506. auto e = request_block.find("\r\n");
  13507. if (e != std::string::npos) {
  13508. auto request_line = request_block.substr(0, e);
  13509. std::string msg =
  13510. "CRLF injection detected in request line: '" + request_line + "'";
  13511. EXPECT_FALSE(true) << msg;
  13512. }
  13513. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13514. ::send(cli,
  13515. #ifdef _WIN32
  13516. static_cast<const char *>(resp.c_str()),
  13517. static_cast<int>(resp.size()),
  13518. #else
  13519. resp.c_str(), resp.size(),
  13520. #endif
  13521. 0);
  13522. buf_all.erase(0, pos + 4);
  13523. }
  13524. }
  13525. detail::close_socket(cli);
  13526. detail::close_socket(srv);
  13527. });
  13528. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13529. auto cli = Client("127.0.0.1", PORT + 1);
  13530. auto headers = Headers{
  13531. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13532. {"Connection", "keep-alive"}};
  13533. auto res = cli.Get("/hi", headers);
  13534. EXPECT_FALSE(res);
  13535. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13536. server_thread.join();
  13537. }
  13538. TEST(PathParamsTest, StaticMatch) {
  13539. const auto pattern = "/users/all";
  13540. detail::PathParamsMatcher matcher(pattern);
  13541. Request request;
  13542. request.path = "/users/all";
  13543. ASSERT_TRUE(matcher.match(request));
  13544. std::unordered_map<std::string, std::string> expected_params = {};
  13545. EXPECT_EQ(request.path_params, expected_params);
  13546. }
  13547. TEST(PathParamsTest, StaticMismatch) {
  13548. const auto pattern = "/users/all";
  13549. detail::PathParamsMatcher matcher(pattern);
  13550. Request request;
  13551. request.path = "/users/1";
  13552. ASSERT_FALSE(matcher.match(request));
  13553. }
  13554. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13555. const auto pattern = "/users/:id/subscriptions";
  13556. detail::PathParamsMatcher matcher(pattern);
  13557. Request request;
  13558. request.path = "/users/42/subscriptions";
  13559. ASSERT_TRUE(matcher.match(request));
  13560. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13561. EXPECT_EQ(request.path_params, expected_params);
  13562. }
  13563. TEST(PathParamsTest, SingleParamInTheEnd) {
  13564. const auto pattern = "/users/:id";
  13565. detail::PathParamsMatcher matcher(pattern);
  13566. Request request;
  13567. request.path = "/users/24";
  13568. ASSERT_TRUE(matcher.match(request));
  13569. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13570. EXPECT_EQ(request.path_params, expected_params);
  13571. }
  13572. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13573. const auto pattern = "/users/:id/";
  13574. detail::PathParamsMatcher matcher(pattern);
  13575. Request request;
  13576. request.path = "/users/42/";
  13577. ASSERT_TRUE(matcher.match(request));
  13578. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13579. EXPECT_EQ(request.path_params, expected_params);
  13580. }
  13581. TEST(PathParamsTest, EmptyParam) {
  13582. const auto pattern = "/users/:id/";
  13583. detail::PathParamsMatcher matcher(pattern);
  13584. Request request;
  13585. request.path = "/users//";
  13586. ASSERT_TRUE(matcher.match(request));
  13587. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13588. EXPECT_EQ(request.path_params, expected_params);
  13589. }
  13590. TEST(PathParamsTest, FragmentMismatch) {
  13591. const auto pattern = "/users/:id/";
  13592. detail::PathParamsMatcher matcher(pattern);
  13593. Request request;
  13594. request.path = "/admins/24/";
  13595. ASSERT_FALSE(matcher.match(request));
  13596. }
  13597. TEST(PathParamsTest, ExtraFragments) {
  13598. const auto pattern = "/users/:id";
  13599. detail::PathParamsMatcher matcher(pattern);
  13600. Request request;
  13601. request.path = "/users/42/subscriptions";
  13602. ASSERT_FALSE(matcher.match(request));
  13603. }
  13604. TEST(PathParamsTest, MissingTrailingParam) {
  13605. const auto pattern = "/users/:id";
  13606. detail::PathParamsMatcher matcher(pattern);
  13607. Request request;
  13608. request.path = "/users";
  13609. ASSERT_FALSE(matcher.match(request));
  13610. }
  13611. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13612. const auto pattern = "/users/:id/subscriptions";
  13613. detail::PathParamsMatcher matcher(pattern);
  13614. Request request;
  13615. request.path = "/users/subscriptions";
  13616. ASSERT_FALSE(matcher.match(request));
  13617. }
  13618. TEST(PathParamsTest, MultipleParams) {
  13619. const auto pattern = "/users/:userid/subscriptions/:subid";
  13620. detail::PathParamsMatcher matcher(pattern);
  13621. Request request;
  13622. request.path = "/users/42/subscriptions/2";
  13623. ASSERT_TRUE(matcher.match(request));
  13624. std::unordered_map<std::string, std::string> expected_params = {
  13625. {"userid", "42"}, {"subid", "2"}};
  13626. EXPECT_EQ(request.path_params, expected_params);
  13627. }
  13628. TEST(PathParamsTest, SequenceOfParams) {
  13629. const auto pattern = "/values/:x/:y/:z";
  13630. detail::PathParamsMatcher matcher(pattern);
  13631. Request request;
  13632. request.path = "/values/1/2/3";
  13633. ASSERT_TRUE(matcher.match(request));
  13634. std::unordered_map<std::string, std::string> expected_params = {
  13635. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13636. EXPECT_EQ(request.path_params, expected_params);
  13637. }
  13638. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13639. const auto pattern = "/prefix:suffix";
  13640. detail::PathParamsMatcher matcher(pattern);
  13641. Request request;
  13642. request.path = "/prefix:suffix";
  13643. ASSERT_TRUE(matcher.match(request));
  13644. const std::unordered_map<std::string, std::string> expected_params = {};
  13645. EXPECT_EQ(request.path_params, expected_params);
  13646. }
  13647. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13648. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13649. // calling thread's stack on a long enough path for a quantified pattern;
  13650. // RegexMatcher must refuse to run regex matching on paths beyond
  13651. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13652. detail::RegexMatcher matcher("/files/(.*)");
  13653. Request within_limit;
  13654. within_limit.path = "/files/" + std::string(10, 'A');
  13655. EXPECT_TRUE(matcher.match(within_limit));
  13656. Request over_limit;
  13657. over_limit.path =
  13658. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13659. EXPECT_FALSE(matcher.match(over_limit));
  13660. }
  13661. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13662. Server svr;
  13663. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13664. res.set_content("ok", "text/plain");
  13665. });
  13666. auto port = svr.bind_to_any_port(HOST);
  13667. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13668. auto se = detail::scope_exit([&] {
  13669. svr.stop();
  13670. thread.join();
  13671. ASSERT_FALSE(svr.is_running());
  13672. });
  13673. svr.wait_until_ready();
  13674. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13675. // request URI limit; this used to be able to crash the process.
  13676. std::string path =
  13677. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13678. std::string req = "GET " + path +
  13679. " HTTP/1.1\r\n"
  13680. "Host: " +
  13681. std::string(HOST) + ":" + std::to_string(port) +
  13682. "\r\n"
  13683. "Connection: close\r\n"
  13684. "\r\n";
  13685. std::string response;
  13686. ASSERT_TRUE(send_request(5, req, &response, port));
  13687. EXPECT_NE(std::string::npos, response.find("404"));
  13688. }
  13689. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13690. Server svr;
  13691. auto handler = [](const Request & /*req*/, Response &res) {
  13692. res.set_content("hit", "text/plain");
  13693. };
  13694. // No regex metacharacter, so this one is compared literally
  13695. svr.Get("/literal/route", handler);
  13696. // '.' is a regex metacharacter, so this one must keep regex semantics
  13697. svr.Get("/a.c", handler);
  13698. auto port = svr.bind_to_any_port(HOST);
  13699. std::thread t([&]() { svr.listen_after_bind(); });
  13700. auto se = detail::scope_exit([&] {
  13701. svr.stop();
  13702. t.join();
  13703. ASSERT_FALSE(svr.is_running());
  13704. });
  13705. svr.wait_until_ready();
  13706. Client cli(HOST, port);
  13707. struct {
  13708. const char *path;
  13709. int status;
  13710. } cases[] = {
  13711. {"/literal/route", StatusCode::OK_200},
  13712. {"/literal/routes", StatusCode::NotFound_404},
  13713. {"/literal/rout", StatusCode::NotFound_404},
  13714. {"/abc", StatusCode::OK_200},
  13715. {"/a.c", StatusCode::OK_200},
  13716. };
  13717. for (const auto &x : cases) {
  13718. auto res = cli.Get(x.path);
  13719. ASSERT_TRUE(res) << x.path;
  13720. EXPECT_EQ(x.status, res->status) << x.path;
  13721. }
  13722. }
  13723. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13724. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13725. // from exhausting the stack, so it must only constrain routes that actually
  13726. // run a regular expression. A literal route is matched by comparison and
  13727. // stays usable at any length.
  13728. Server svr;
  13729. const std::string pattern =
  13730. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13731. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13732. res.set_content("hit", "text/plain");
  13733. });
  13734. auto port = svr.bind_to_any_port(HOST);
  13735. std::thread t([&]() { svr.listen_after_bind(); });
  13736. auto se = detail::scope_exit([&] {
  13737. svr.stop();
  13738. t.join();
  13739. ASSERT_FALSE(svr.is_running());
  13740. });
  13741. svr.wait_until_ready();
  13742. Client cli(HOST, port);
  13743. auto res = cli.Get(pattern);
  13744. ASSERT_TRUE(res);
  13745. EXPECT_EQ(StatusCode::OK_200, res->status);
  13746. }
  13747. TEST(ParseUrlTest, VariousPatterns) {
  13748. {
  13749. detail::UrlComponents uc;
  13750. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13751. EXPECT_EQ("http", uc.scheme);
  13752. EXPECT_EQ("example.com", uc.host);
  13753. EXPECT_EQ("8080", uc.port);
  13754. EXPECT_EQ("/path", uc.path);
  13755. EXPECT_EQ("?q=1", uc.query);
  13756. }
  13757. {
  13758. detail::UrlComponents uc;
  13759. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13760. EXPECT_EQ("https", uc.scheme);
  13761. EXPECT_EQ("example.com", uc.host);
  13762. EXPECT_TRUE(uc.port.empty());
  13763. EXPECT_EQ("/path", uc.path);
  13764. }
  13765. {
  13766. detail::UrlComponents uc;
  13767. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13768. EXPECT_EQ("::1", uc.host);
  13769. EXPECT_EQ("8080", uc.port);
  13770. EXPECT_EQ("/path", uc.path);
  13771. }
  13772. {
  13773. detail::UrlComponents uc;
  13774. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13775. }
  13776. {
  13777. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13778. // the path while the connection still targets the bracketed host.
  13779. detail::UrlComponents uc;
  13780. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13781. }
  13782. {
  13783. detail::UrlComponents uc;
  13784. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13785. }
  13786. {
  13787. detail::UrlComponents uc;
  13788. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13789. EXPECT_EQ("::1", uc.host);
  13790. EXPECT_TRUE(uc.port.empty());
  13791. EXPECT_EQ("/path", uc.path);
  13792. }
  13793. {
  13794. detail::UrlComponents uc;
  13795. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13796. EXPECT_TRUE(uc.scheme.empty());
  13797. EXPECT_EQ("example.com", uc.host);
  13798. EXPECT_EQ("/path", uc.path);
  13799. EXPECT_EQ("?q=1", uc.query);
  13800. }
  13801. {
  13802. detail::UrlComponents uc;
  13803. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13804. EXPECT_TRUE(uc.host.empty());
  13805. EXPECT_EQ("/path", uc.path);
  13806. EXPECT_EQ("?q=1", uc.query);
  13807. }
  13808. {
  13809. detail::UrlComponents uc;
  13810. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13811. EXPECT_EQ("example.com", uc.host);
  13812. EXPECT_EQ("8080", uc.port);
  13813. }
  13814. {
  13815. // Unix socket path — must not be parsed as host
  13816. detail::UrlComponents uc;
  13817. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13818. EXPECT_TRUE(uc.host.empty());
  13819. }
  13820. {
  13821. detail::UrlComponents uc;
  13822. ASSERT_TRUE(detail::parse_url("", uc));
  13823. EXPECT_TRUE(uc.host.empty());
  13824. EXPECT_TRUE(uc.path.empty());
  13825. }
  13826. {
  13827. detail::UrlComponents uc;
  13828. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13829. }
  13830. {
  13831. detail::UrlComponents uc;
  13832. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13833. }
  13834. {
  13835. // Accepted by parse_url; callers restrict to http/https
  13836. detail::UrlComponents uc;
  13837. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13838. EXPECT_EQ("ftp", uc.scheme);
  13839. }
  13840. {
  13841. detail::UrlComponents uc;
  13842. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13843. }
  13844. {
  13845. detail::UrlComponents uc;
  13846. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13847. }
  13848. }
  13849. TEST(ParseUrlTest, FragmentHandling) {
  13850. {
  13851. detail::UrlComponents uc;
  13852. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13853. EXPECT_EQ("/path", uc.path);
  13854. EXPECT_TRUE(uc.query.empty());
  13855. }
  13856. {
  13857. detail::UrlComponents uc;
  13858. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13859. EXPECT_TRUE(uc.path.empty());
  13860. EXPECT_TRUE(uc.query.empty());
  13861. }
  13862. }
  13863. TEST(ParseUrlTest, UserinfoHandling) {
  13864. // Userinfo with @ but no colon — host includes @
  13865. detail::UrlComponents uc;
  13866. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13867. EXPECT_EQ("user@host.com", uc.host);
  13868. EXPECT_EQ("/path", uc.path);
  13869. }
  13870. TEST(ParseUrlTest, IPv6EdgeCases) {
  13871. {
  13872. detail::UrlComponents uc;
  13873. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13874. EXPECT_TRUE(uc.scheme.empty());
  13875. EXPECT_EQ("::1", uc.host);
  13876. EXPECT_EQ("8080", uc.port);
  13877. }
  13878. {
  13879. // Zone ID '%25' is not in [a-fA-F0-9:]
  13880. detail::UrlComponents uc;
  13881. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13882. }
  13883. }
  13884. TEST(ParseUrlTest, SchemeEdgeCases) {
  13885. {
  13886. detail::UrlComponents uc;
  13887. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13888. }
  13889. {
  13890. detail::UrlComponents uc;
  13891. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13892. }
  13893. {
  13894. detail::UrlComponents uc;
  13895. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13896. }
  13897. }
  13898. TEST(ParseUrlTest, PortEdgeCases) {
  13899. {
  13900. detail::UrlComponents uc;
  13901. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13902. EXPECT_TRUE(uc.port.empty());
  13903. EXPECT_EQ("/path", uc.path);
  13904. }
  13905. {
  13906. // parse_url accepts any port string; validation is done by parse_port
  13907. detail::UrlComponents uc;
  13908. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13909. EXPECT_EQ("abc", uc.port);
  13910. }
  13911. }
  13912. TEST(ParseUrlTest, WebSocketPatterns) {
  13913. {
  13914. detail::UrlComponents uc;
  13915. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13916. EXPECT_EQ("ws", uc.scheme);
  13917. EXPECT_EQ("echo.example.com", uc.host);
  13918. EXPECT_EQ("8080", uc.port);
  13919. EXPECT_EQ("/ws", uc.path);
  13920. }
  13921. {
  13922. detail::UrlComponents uc;
  13923. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13924. EXPECT_EQ("wss", uc.scheme);
  13925. EXPECT_EQ("echo.example.com", uc.host);
  13926. EXPECT_TRUE(uc.port.empty());
  13927. EXPECT_EQ("/ws", uc.path);
  13928. }
  13929. }
  13930. TEST(ParseUrlTest, QueryOnly) {
  13931. detail::UrlComponents uc;
  13932. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13933. EXPECT_TRUE(uc.host.empty());
  13934. EXPECT_TRUE(uc.path.empty());
  13935. EXPECT_EQ("?q=1&r=2", uc.query);
  13936. }
  13937. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13938. detail::UrlComponents uc;
  13939. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13940. EXPECT_TRUE(uc.scheme.empty());
  13941. EXPECT_EQ("example.com", uc.host);
  13942. EXPECT_EQ("443", uc.port);
  13943. EXPECT_EQ("/path", uc.path);
  13944. }
  13945. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13946. // If ipv6 regex working, regex match codepath is taken.
  13947. // else port will default to 80 in Client impl
  13948. int clientImplMagicPort = 80;
  13949. int port = 4321;
  13950. // above ports must be different to avoid false negative
  13951. EXPECT_NE(clientImplMagicPort, port);
  13952. std::string ipV6TestURL = "http://[ff06::c3]";
  13953. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13954. CLIENT_PRIVATE_KEY_FILE);
  13955. EXPECT_EQ(cli.port(), port);
  13956. }
  13957. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13958. auto file_path = "./www/dir/index.html";
  13959. auto dir_path = "./www/dir";
  13960. detail::FileStat stat_file(file_path);
  13961. EXPECT_TRUE(stat_file.is_file());
  13962. EXPECT_FALSE(stat_file.is_dir());
  13963. detail::FileStat stat_dir(dir_path);
  13964. EXPECT_FALSE(stat_dir.is_file());
  13965. EXPECT_TRUE(stat_dir.is_dir());
  13966. }
  13967. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13968. // IPv4 with default HTTP port (80)
  13969. EXPECT_EQ("example.com",
  13970. detail::make_host_and_port_string("example.com", 80, false));
  13971. // IPv4 with default HTTPS port (443)
  13972. EXPECT_EQ("example.com",
  13973. detail::make_host_and_port_string("example.com", 443, true));
  13974. // IPv4 with non-default HTTP port
  13975. EXPECT_EQ("example.com:8080",
  13976. detail::make_host_and_port_string("example.com", 8080, false));
  13977. // IPv4 with non-default HTTPS port
  13978. EXPECT_EQ("example.com:8443",
  13979. detail::make_host_and_port_string("example.com", 8443, true));
  13980. // IPv6 with default HTTP port (80)
  13981. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13982. // IPv6 with default HTTPS port (443)
  13983. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13984. // IPv6 with non-default HTTP port
  13985. EXPECT_EQ("[::1]:8080",
  13986. detail::make_host_and_port_string("::1", 8080, false));
  13987. // IPv6 with non-default HTTPS port
  13988. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13989. // IPv6 full address with default port
  13990. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13991. detail::make_host_and_port_string(
  13992. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13993. // IPv6 full address with non-default port
  13994. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13995. detail::make_host_and_port_string(
  13996. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13997. // IPv6 localhost with non-default port
  13998. EXPECT_EQ("[::1]:3000",
  13999. detail::make_host_and_port_string("::1", 3000, false));
  14000. // IPv6 with zone ID (link-local address) with default port
  14001. EXPECT_EQ("[fe80::1%eth0]",
  14002. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14003. // IPv6 with zone ID (link-local address) with non-default port
  14004. EXPECT_EQ("[fe80::1%eth0]:8080",
  14005. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14006. // Edge case: Port 443 with is_ssl=false (should add port)
  14007. EXPECT_EQ("example.com:443",
  14008. detail::make_host_and_port_string("example.com", 443, false));
  14009. // Edge case: Port 80 with is_ssl=true (should add port)
  14010. EXPECT_EQ("example.com:80",
  14011. detail::make_host_and_port_string("example.com", 80, true));
  14012. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14013. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14014. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14015. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14016. // Security fix: Already bracketed IPv6 should not get double brackets
  14017. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14018. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14019. EXPECT_EQ("[::1]:8080",
  14020. detail::make_host_and_port_string("[::1]", 8080, false));
  14021. EXPECT_EQ("[2001:db8::1]:8080",
  14022. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14023. EXPECT_EQ("[fe80::1%eth0]",
  14024. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14025. EXPECT_EQ("[fe80::1%eth0]:8080",
  14026. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14027. // Edge case: Empty host (should return as-is)
  14028. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14029. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14030. // This is a known limitation but shouldn't crash
  14031. EXPECT_EQ("[host:name]",
  14032. detail::make_host_and_port_string("host:name", 80, false));
  14033. // Port number edge cases (no validation, but should not crash)
  14034. EXPECT_EQ("example.com:0",
  14035. detail::make_host_and_port_string("example.com", 0, false));
  14036. EXPECT_EQ("example.com:-1",
  14037. detail::make_host_and_port_string("example.com", -1, false));
  14038. EXPECT_EQ("example.com:65535",
  14039. detail::make_host_and_port_string("example.com", 65535, false));
  14040. EXPECT_EQ("example.com:65536",
  14041. detail::make_host_and_port_string("example.com", 65536, false));
  14042. }
  14043. #ifdef CPPHTTPLIB_SSL_ENABLED
  14044. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14045. httplib::SSLClient cli("roblox.com", 443);
  14046. cli.set_follow_location(true);
  14047. auto res = cli.Get("/");
  14048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14049. EXPECT_EQ(StatusCode::OK_200, res->status);
  14050. }
  14051. #endif
  14052. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14053. Server svr;
  14054. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14055. EXPECT_EQ(res.status, 400);
  14056. });
  14057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14058. auto se = detail::scope_exit([&] {
  14059. svr.stop();
  14060. thread.join();
  14061. ASSERT_FALSE(svr.is_running());
  14062. });
  14063. svr.wait_until_ready();
  14064. Client cli(HOST, PORT);
  14065. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14066. }
  14067. TEST(InvalidHeaderCharsTest, is_field_name) {
  14068. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14069. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14070. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14071. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14072. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14073. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14074. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14075. EXPECT_FALSE(detail::fields::is_field_name(""));
  14076. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14077. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14078. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14079. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14080. }
  14081. TEST(InvalidHeaderCharsTest, is_field_value) {
  14082. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14083. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14084. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14085. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14086. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14087. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14088. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14089. EXPECT_TRUE(detail::fields::is_field_value(""));
  14090. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14091. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14092. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14093. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14094. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14095. }
  14096. TEST(InvalidHeaderCharsTest, OnServer) {
  14097. Server svr;
  14098. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14099. std::string header = "Not Set";
  14100. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14101. res.set_header(header, "value");
  14102. res.set_content("Page Content Page Content", "text/plain");
  14103. });
  14104. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14105. std::string header = "Not Set";
  14106. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14107. res.set_header("X-Test", header);
  14108. res.set_content("Page Content Page Content", "text/plain");
  14109. });
  14110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14111. auto se = detail::scope_exit([&] {
  14112. svr.stop();
  14113. thread.join();
  14114. ASSERT_FALSE(svr.is_running());
  14115. });
  14116. svr.wait_until_ready();
  14117. Client cli(HOST, PORT);
  14118. {
  14119. auto res = cli.Get(
  14120. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14122. EXPECT_EQ("Page Content Page Content", res->body);
  14123. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14124. }
  14125. {
  14126. auto res = cli.Get(
  14127. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14129. EXPECT_EQ("Page Content Page Content", res->body);
  14130. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14131. }
  14132. }
  14133. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14134. auto handled = false;
  14135. Server svr;
  14136. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14137. thread t = thread([&] { svr.listen(HOST, PORT); });
  14138. auto se = detail::scope_exit([&] {
  14139. svr.stop();
  14140. t.join();
  14141. ASSERT_FALSE(svr.is_running());
  14142. ASSERT_FALSE(handled);
  14143. });
  14144. svr.wait_until_ready();
  14145. auto req = "POST /test HTTP/1.1\r\n"
  14146. "Content-Length: x\r\n"
  14147. "\r\n";
  14148. std::string response;
  14149. ASSERT_TRUE(send_request(1, req, &response));
  14150. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14151. response.substr(0, response.find("\r\n")));
  14152. }
  14153. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14154. // case-insensitive, and a server that receives a 100-continue expectation in
  14155. // an HTTP/1.0 request MUST ignore it.
  14156. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14157. std::string response;
  14158. ASSERT_TRUE(send_request(1, req, &response, port));
  14159. *got_100 = response.find("100 Continue") != std::string::npos;
  14160. }
  14161. class ExpectTokenTest : public ::testing::Test {
  14162. protected:
  14163. void SetUp() override {
  14164. svr_.Post("/p", [](const Request &, Response &res) {
  14165. res.set_content("ok", "text/plain");
  14166. });
  14167. port_ = svr_.bind_to_any_port(HOST);
  14168. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14169. svr_.wait_until_ready();
  14170. }
  14171. void TearDown() override {
  14172. svr_.stop();
  14173. if (thread_.joinable()) { thread_.join(); }
  14174. }
  14175. std::string request(const char *version, const char *expect_value) const {
  14176. return std::string("POST /p ") + version +
  14177. "\r\n"
  14178. "Host: localhost\r\n"
  14179. "Content-Length: 2\r\n"
  14180. "Connection: close\r\n"
  14181. "Expect: " +
  14182. expect_value +
  14183. "\r\n"
  14184. "\r\n"
  14185. "hi";
  14186. }
  14187. Server svr_;
  14188. int port_ = 0;
  14189. thread thread_;
  14190. };
  14191. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14192. bool got_100 = false;
  14193. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14194. EXPECT_TRUE(got_100);
  14195. }
  14196. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14197. bool got_100 = true;
  14198. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14199. EXPECT_FALSE(got_100);
  14200. }
  14201. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14202. bool got_100 = false;
  14203. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14204. EXPECT_TRUE(got_100);
  14205. }
  14206. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14207. bool got_100 = false;
  14208. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14209. EXPECT_TRUE(got_100);
  14210. }
  14211. #ifndef _WIN32
  14212. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14213. static constexpr char reject[] = "Unauthorized";
  14214. static constexpr char accept[] = "Upload accepted";
  14215. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14216. Server svr;
  14217. svr.set_expect_100_continue_handler(
  14218. [](const Request & /*req*/, Response &res) {
  14219. res.status = StatusCode::Unauthorized_401;
  14220. res.set_content(reject, "text/plain");
  14221. return res.status;
  14222. });
  14223. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14224. res.set_content(accept, "text/plain");
  14225. });
  14226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14227. auto se = detail::scope_exit([&] {
  14228. svr.stop();
  14229. thread.join();
  14230. ASSERT_FALSE(svr.is_running());
  14231. });
  14232. svr.wait_until_ready();
  14233. {
  14234. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14235. curl_easy_init(), &curl_easy_cleanup};
  14236. ASSERT_NE(curl, nullptr);
  14237. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14238. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14239. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14240. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14241. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14242. &curl_slist_free_all};
  14243. ASSERT_NE(list, nullptr);
  14244. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14245. struct read_data {
  14246. size_t read_size;
  14247. size_t total_size;
  14248. } data = {0, total_size};
  14249. using read_callback_t =
  14250. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14251. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14252. void *userdata) -> size_t {
  14253. read_data *d = (read_data *)userdata;
  14254. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14255. std::fill_n(ptr, size * nmemb, 'A');
  14256. d->read_size += size * nmemb;
  14257. return size * nmemb;
  14258. };
  14259. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14260. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14261. std::vector<char> buffer;
  14262. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14263. using write_callback_t =
  14264. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14265. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14266. void *userdata) -> size_t {
  14267. std::vector<char> *buf = (std::vector<char> *)userdata;
  14268. buf->reserve(buf->size() + size * nmemb + 1);
  14269. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14270. return size * nmemb;
  14271. };
  14272. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14273. {
  14274. const auto res = curl_easy_perform(curl.get());
  14275. ASSERT_EQ(res, CURLE_OK);
  14276. }
  14277. {
  14278. auto response_code = long{};
  14279. const auto res =
  14280. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14281. ASSERT_EQ(res, CURLE_OK);
  14282. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14283. }
  14284. {
  14285. auto dl = curl_off_t{};
  14286. const auto res =
  14287. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14288. ASSERT_EQ(res, CURLE_OK);
  14289. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14290. }
  14291. {
  14292. buffer.push_back('\0');
  14293. ASSERT_STRCASEEQ(buffer.data(), reject);
  14294. }
  14295. }
  14296. }
  14297. #endif
  14298. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14299. // Regression test for #2458.
  14300. //
  14301. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14302. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14303. // ticket can make the client socket spuriously readable during the
  14304. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14305. // the client withholds the body and then blocks reading a response that never
  14306. // comes, failing with `Failed to read connection`.
  14307. //
  14308. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14309. // within the timeout. This raw OpenSSL server deliberately never sends
  14310. // `100 Continue`; the client must still deliver the body and receive 200.
  14311. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14312. signal(SIGPIPE, SIG_IGN);
  14313. const auto port = PORT + 4;
  14314. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14315. ASSERT_NE(srv, INVALID_SOCKET);
  14316. int opt = 1;
  14317. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14318. sockaddr_in addr{};
  14319. addr.sin_family = AF_INET;
  14320. addr.sin_port = htons(static_cast<uint16_t>(port));
  14321. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14322. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14323. ASSERT_EQ(0, ::listen(srv, 1));
  14324. std::atomic<size_t> server_body_bytes{0};
  14325. auto server_thread = std::thread([&] {
  14326. sockaddr_in cli_addr{};
  14327. socklen_t cli_len = sizeof(cli_addr);
  14328. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14329. if (cli == INVALID_SOCKET) { return; }
  14330. // Bound the lifetime of the server side so a buggy client (which never
  14331. // sends the body) cannot make this thread block forever on join.
  14332. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14333. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14334. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14335. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14336. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14337. SSL *ssl = SSL_new(ctx);
  14338. SSL_set_fd(ssl, static_cast<int>(cli));
  14339. if (SSL_accept(ssl) > 0) {
  14340. // Read the request headers. Reading here also flushes the TLS 1.3
  14341. // session tickets to the client. Deliberately do NOT send
  14342. // `100 Continue`.
  14343. std::string buf;
  14344. char tmp[1024];
  14345. while (buf.find("\r\n\r\n") == std::string::npos) {
  14346. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14347. if (n <= 0) { break; }
  14348. buf.append(tmp, static_cast<size_t>(n));
  14349. }
  14350. // A correct client sends the body now; count what arrives.
  14351. auto pos = buf.find("\r\n\r\n");
  14352. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14353. while (body < 4096) {
  14354. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14355. if (n <= 0) { break; }
  14356. body += static_cast<size_t>(n);
  14357. }
  14358. server_body_bytes = body;
  14359. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14360. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14361. SSL_shutdown(ssl);
  14362. }
  14363. SSL_free(ssl);
  14364. detail::close_socket(cli);
  14365. SSL_CTX_free(ctx);
  14366. });
  14367. auto se = detail::scope_exit([&] {
  14368. server_thread.join();
  14369. detail::close_socket(srv);
  14370. });
  14371. SSLClient cli("127.0.0.1", port);
  14372. cli.enable_server_certificate_verification(false);
  14373. cli.set_connection_timeout(5, 0);
  14374. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14375. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14376. std::string body(4096, 'A');
  14377. auto res = cli.Put("/api/test", body, "application/json");
  14378. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14379. EXPECT_EQ(StatusCode::OK_200, res->status);
  14380. EXPECT_EQ(body.size(), server_body_bytes.load());
  14381. }
  14382. #endif
  14383. template <typename S, typename C>
  14384. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14385. svr.Get("/stream", [&](const Request &, Response &res) {
  14386. auto data = new std::string("01234567890123456789");
  14387. res.set_content_provider(
  14388. data->size(), "text/plain",
  14389. [&, data](size_t offset, size_t length, DataSink &sink) {
  14390. const size_t DATA_CHUNK_SIZE = 4;
  14391. const auto &d = *data;
  14392. std::this_thread::sleep_for(std::chrono::seconds(1));
  14393. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14394. return true;
  14395. },
  14396. [data](bool success) {
  14397. EXPECT_FALSE(success);
  14398. delete data;
  14399. });
  14400. });
  14401. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14402. auto i = new size_t(0);
  14403. res.set_content_provider(
  14404. "text/plain",
  14405. [i](size_t, DataSink &sink) {
  14406. if (*i < 5) {
  14407. std::this_thread::sleep_for(std::chrono::seconds(1));
  14408. sink.write("abcd", 4);
  14409. (*i)++;
  14410. } else {
  14411. sink.done();
  14412. }
  14413. return true;
  14414. },
  14415. [i](bool success) {
  14416. EXPECT_FALSE(success);
  14417. delete i;
  14418. });
  14419. });
  14420. svr.Get("/chunked", [&](const Request &, Response &res) {
  14421. auto i = new size_t(0);
  14422. res.set_chunked_content_provider(
  14423. "text/plain",
  14424. [i](size_t, DataSink &sink) {
  14425. if (*i < 5) {
  14426. std::this_thread::sleep_for(std::chrono::seconds(1));
  14427. sink.os << "abcd";
  14428. (*i)++;
  14429. } else {
  14430. sink.done();
  14431. }
  14432. return true;
  14433. },
  14434. [i](bool success) {
  14435. EXPECT_FALSE(success);
  14436. delete i;
  14437. });
  14438. });
  14439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14440. auto se = detail::scope_exit([&] {
  14441. svr.stop();
  14442. listen_thread.join();
  14443. ASSERT_FALSE(svr.is_running());
  14444. });
  14445. svr.wait_until_ready();
  14446. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14447. {
  14448. auto start = std::chrono::steady_clock::now();
  14449. auto res = cli.Get("/stream");
  14450. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14451. std::chrono::steady_clock::now() - start)
  14452. .count();
  14453. ASSERT_FALSE(res);
  14454. EXPECT_EQ(Error::Read, res.error());
  14455. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14456. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14457. }
  14458. {
  14459. auto start = std::chrono::steady_clock::now();
  14460. auto res = cli.Get("/stream_without_length");
  14461. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14462. std::chrono::steady_clock::now() - start)
  14463. .count();
  14464. ASSERT_FALSE(res);
  14465. EXPECT_EQ(Error::Read, res.error());
  14466. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14467. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14468. }
  14469. {
  14470. auto start = std::chrono::steady_clock::now();
  14471. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14472. EXPECT_EQ("abcd", string(data, data_length));
  14473. return true;
  14474. });
  14475. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14476. std::chrono::steady_clock::now() - start)
  14477. .count();
  14478. ASSERT_FALSE(res);
  14479. EXPECT_EQ(Error::Read, res.error());
  14480. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14481. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14482. }
  14483. }
  14484. TEST(MaxTimeoutTest, ContentStream) {
  14485. time_t timeout = 2000;
  14486. time_t threshold = 200;
  14487. Server svr;
  14488. Client cli("localhost", PORT);
  14489. max_timeout_test(svr, cli, timeout, threshold);
  14490. }
  14491. #ifdef CPPHTTPLIB_SSL_ENABLED
  14492. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14493. time_t timeout = 2000;
  14494. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14496. SSLClient cli("localhost", PORT);
  14497. cli.enable_server_certificate_verification(false);
  14498. max_timeout_test(svr, cli, timeout, threshold);
  14499. }
  14500. #endif
  14501. class EventDispatcher {
  14502. public:
  14503. EventDispatcher() {}
  14504. bool wait_event(DataSink *sink) {
  14505. unique_lock<mutex> lk(m_);
  14506. int id = id_;
  14507. // Wait with timeout to prevent hanging if client disconnects
  14508. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14509. [&] { return cid_ == id; })) {
  14510. return false; // Timeout occurred
  14511. }
  14512. sink->write(message_.data(), message_.size());
  14513. return true;
  14514. }
  14515. void send_event(const string &message) {
  14516. lock_guard<mutex> lk(m_);
  14517. cid_ = id_++;
  14518. message_ = message;
  14519. cv_.notify_all();
  14520. }
  14521. private:
  14522. mutex m_;
  14523. condition_variable cv_;
  14524. atomic_int id_{0};
  14525. atomic_int cid_{-1};
  14526. string message_;
  14527. };
  14528. TEST(ClientInThreadTest, Issue2068) {
  14529. EventDispatcher ed;
  14530. Server svr;
  14531. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14532. res.set_chunked_content_provider("text/event-stream",
  14533. [&](size_t /*offset*/, DataSink &sink) {
  14534. return ed.wait_event(&sink);
  14535. });
  14536. });
  14537. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14538. svr.wait_until_ready();
  14539. thread event_thread([&] {
  14540. int id = 0;
  14541. while (svr.is_running()) {
  14542. this_thread::sleep_for(chrono::milliseconds(500));
  14543. std::stringstream ss;
  14544. ss << "data: " << id << "\n\n";
  14545. ed.send_event(ss.str());
  14546. id++;
  14547. }
  14548. });
  14549. auto se = detail::scope_exit([&] {
  14550. svr.stop();
  14551. listen_thread.join();
  14552. event_thread.join();
  14553. ASSERT_FALSE(svr.is_running());
  14554. });
  14555. {
  14556. auto client = detail::make_unique<Client>(HOST, PORT);
  14557. client->set_read_timeout(std::chrono::minutes(10));
  14558. std::atomic<bool> stop{false};
  14559. std::thread t([&] {
  14560. client->Get("/event1",
  14561. [&](const char *, size_t) -> bool { return !stop; });
  14562. });
  14563. std::this_thread::sleep_for(std::chrono::seconds(2));
  14564. stop = true;
  14565. client->stop();
  14566. t.join();
  14567. // Reset client after thread has finished
  14568. client.reset();
  14569. }
  14570. }
  14571. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14572. auto handled = false;
  14573. Server svr;
  14574. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14575. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14576. auto se = detail::scope_exit([&] {
  14577. svr.stop();
  14578. t.join();
  14579. ASSERT_FALSE(svr.is_running());
  14580. ASSERT_FALSE(handled);
  14581. });
  14582. svr.wait_until_ready();
  14583. // Two Content-Length headers with different values — must be rejected
  14584. auto req = "POST /test HTTP/1.1\r\n"
  14585. "Content-Length: 5\r\n"
  14586. "Content-Length: 10\r\n"
  14587. "\r\n"
  14588. "hello";
  14589. std::string response;
  14590. ASSERT_TRUE(send_request(1, req, &response));
  14591. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14592. response.substr(0, response.find("\r\n")));
  14593. }
  14594. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14595. auto handled = false;
  14596. Server svr;
  14597. svr.Post("/test", [&](const Request &, Response &res) {
  14598. handled = true;
  14599. res.set_content("ok", "text/plain");
  14600. });
  14601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14602. auto se = detail::scope_exit([&] {
  14603. svr.stop();
  14604. t.join();
  14605. ASSERT_FALSE(svr.is_running());
  14606. ASSERT_TRUE(handled);
  14607. });
  14608. svr.wait_until_ready();
  14609. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14610. auto req = "POST /test HTTP/1.1\r\n"
  14611. "Content-Length: 5\r\n"
  14612. "Content-Length: 5\r\n"
  14613. "\r\n"
  14614. "hello";
  14615. std::string response;
  14616. ASSERT_TRUE(send_request(1, req, &response));
  14617. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14618. }
  14619. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14620. Server svr;
  14621. svr.Get("/", [](const Request &req, Response &res) {
  14622. EXPECT_EQ(2U, req.trailers.size());
  14623. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14624. // Denied
  14625. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14626. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14627. // Accepted
  14628. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14629. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14630. EXPECT_TRUE(req.has_trailer("X-World"));
  14631. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14632. res.set_content("ok", "text/plain");
  14633. });
  14634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. t.join();
  14638. ASSERT_FALSE(svr.is_running());
  14639. });
  14640. svr.wait_until_ready();
  14641. const std::string req = "GET / HTTP/1.1\r\n"
  14642. "Transfer-Encoding: chunked\r\n"
  14643. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14644. "\r\n"
  14645. "0\r\n"
  14646. "Content-Length: 10\r\n"
  14647. "Host: internal.local\r\n"
  14648. "Content-Type: malicious/content\r\n"
  14649. "Cookie: any\r\n"
  14650. "Set-Cookie: any\r\n"
  14651. "X-Forwarded-For: attacker.com\r\n"
  14652. "X-Real-Ip: 1.1.1.1\r\n"
  14653. "X-Hello: hello\r\n"
  14654. "X-World: world\r\n"
  14655. "\r\n";
  14656. std::string res;
  14657. ASSERT_TRUE(send_request(1, req, &res));
  14658. }
  14659. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14660. // several field lines, and the combined value is what has to be parsed. A
  14661. // Trailer field split across lines therefore declares every name it lists;
  14662. // reading only the first line silently drops the trailers the later lines
  14663. // declare. The prohibited-trailer filter still applies to every line.
  14664. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14665. Server svr;
  14666. size_t observed_trailer_count = 0;
  14667. std::string observed_hello;
  14668. std::string observed_world;
  14669. bool observed_content_length = true;
  14670. svr.Get("/", [&](const Request &req, Response &res) {
  14671. observed_trailer_count = req.trailers.size();
  14672. observed_hello = req.get_trailer_value("X-Hello");
  14673. observed_world = req.get_trailer_value("X-World");
  14674. observed_content_length = req.has_trailer("Content-Length");
  14675. res.set_content("ok", "text/plain");
  14676. });
  14677. auto port = svr.bind_to_any_port(HOST);
  14678. thread t = thread([&]() { svr.listen_after_bind(); });
  14679. auto se = detail::scope_exit([&] {
  14680. svr.stop();
  14681. t.join();
  14682. ASSERT_FALSE(svr.is_running());
  14683. });
  14684. svr.wait_until_ready();
  14685. const std::string req = "GET / HTTP/1.1\r\n"
  14686. "Transfer-Encoding: chunked\r\n"
  14687. "Trailer: X-Hello\r\n"
  14688. "Trailer: X-World, Content-Length\r\n"
  14689. "\r\n"
  14690. "0\r\n"
  14691. "X-Hello: hello\r\n"
  14692. "X-World: world\r\n"
  14693. "Content-Length: 10\r\n"
  14694. "\r\n";
  14695. std::string res;
  14696. ASSERT_TRUE(send_request(1, req, &res, port));
  14697. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14698. // Accepted: both field lines contribute to the declared set
  14699. EXPECT_EQ(2U, observed_trailer_count);
  14700. EXPECT_EQ(observed_hello, "hello");
  14701. EXPECT_EQ(observed_world, "world");
  14702. // Denied: a prohibited name stays prohibited on a later field line
  14703. EXPECT_FALSE(observed_content_length);
  14704. }
  14705. // A direct client that is not listed in trusted_proxies must not be able to
  14706. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14707. // the peer address on the actual TCP connection determines whether the
  14708. // header is honored.
  14709. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14710. Server svr;
  14711. // Deliberately does NOT include the loopback address the test client
  14712. // actually connects from, so the direct connection is not a trusted proxy.
  14713. svr.set_trusted_proxies({"203.0.113.66"});
  14714. std::string observed_remote_addr;
  14715. svr.Get("/ip", [&](const Request &req, Response &res) {
  14716. observed_remote_addr = req.remote_addr;
  14717. res.set_content("ok", "text/plain");
  14718. });
  14719. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. Client cli(HOST, PORT);
  14727. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14729. EXPECT_EQ(StatusCode::OK_200, res->status);
  14730. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14731. // ignored entirely and the real connection-level address retained.
  14732. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14733. observed_remote_addr == "127.0.0.1");
  14734. }
  14735. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14736. Server svr;
  14737. std::string observed_remote_addr;
  14738. std::string observed_xff;
  14739. svr.Get("/ip", [&](const Request &req, Response &res) {
  14740. observed_remote_addr = req.remote_addr;
  14741. observed_xff = req.get_header_value("X-Forwarded-For");
  14742. res.set_content("ok", "text/plain");
  14743. });
  14744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14745. auto se = detail::scope_exit([&] {
  14746. svr.stop();
  14747. t.join();
  14748. ASSERT_FALSE(svr.is_running());
  14749. });
  14750. svr.wait_until_ready();
  14751. Client cli(HOST, PORT);
  14752. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14754. EXPECT_EQ(StatusCode::OK_200, res->status);
  14755. EXPECT_EQ(observed_xff, "203.0.113.66");
  14756. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14757. observed_remote_addr == "127.0.0.1");
  14758. }
  14759. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14760. Server svr;
  14761. svr.set_trusted_proxies({"203.0.113.66"});
  14762. std::string observed_remote_addr;
  14763. std::string observed_xff;
  14764. svr.Get("/ip", [&](const Request &req, Response &res) {
  14765. observed_remote_addr = req.remote_addr;
  14766. observed_xff = req.get_header_value("X-Forwarded-For");
  14767. res.set_content("ok", "text/plain");
  14768. });
  14769. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14770. auto se = detail::scope_exit([&] {
  14771. svr.stop();
  14772. t.join();
  14773. ASSERT_FALSE(svr.is_running());
  14774. });
  14775. svr.wait_until_ready();
  14776. Client cli(HOST, PORT);
  14777. auto res = cli.Get("/ip");
  14778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14779. EXPECT_EQ(StatusCode::OK_200, res->status);
  14780. EXPECT_EQ(observed_xff, "");
  14781. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14782. observed_remote_addr == "127.0.0.1");
  14783. }
  14784. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14785. Server svr;
  14786. // Include the loopback address the test client actually connects from, so
  14787. // the direct connection itself is recognized as the trusted proxy hop.
  14788. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14789. std::string observed_remote_addr;
  14790. std::string observed_xff;
  14791. svr.Get("/ip", [&](const Request &req, Response &res) {
  14792. observed_remote_addr = req.remote_addr;
  14793. observed_xff = req.get_header_value("X-Forwarded-For");
  14794. res.set_content("ok", "text/plain");
  14795. });
  14796. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14797. auto se = detail::scope_exit([&] {
  14798. svr.stop();
  14799. t.join();
  14800. ASSERT_FALSE(svr.is_running());
  14801. });
  14802. svr.wait_until_ready();
  14803. Client cli(HOST, PORT);
  14804. auto res = cli.Get(
  14805. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14807. EXPECT_EQ(StatusCode::OK_200, res->status);
  14808. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14809. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14810. }
  14811. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14812. Server svr;
  14813. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14814. std::string observed_remote_addr;
  14815. std::string observed_xff;
  14816. svr.Get("/ip", [&](const Request &req, Response &res) {
  14817. observed_remote_addr = req.remote_addr;
  14818. observed_xff = req.get_header_value("X-Forwarded-For");
  14819. res.set_content("ok", "text/plain");
  14820. });
  14821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14822. auto se = detail::scope_exit([&] {
  14823. svr.stop();
  14824. t.join();
  14825. ASSERT_FALSE(svr.is_running());
  14826. });
  14827. svr.wait_until_ready();
  14828. Client cli(HOST, PORT);
  14829. auto res = cli.Get(
  14830. "/ip",
  14831. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. EXPECT_EQ(StatusCode::OK_200, res->status);
  14834. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14835. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14836. }
  14837. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14838. Server svr;
  14839. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14840. std::string observed_remote_addr;
  14841. std::string observed_xff;
  14842. svr.Get("/ip", [&](const Request &req, Response &res) {
  14843. observed_remote_addr = req.remote_addr;
  14844. observed_xff = req.get_header_value("X-Forwarded-For");
  14845. res.set_content("ok", "text/plain");
  14846. });
  14847. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14848. auto se = detail::scope_exit([&] {
  14849. svr.stop();
  14850. t.join();
  14851. ASSERT_FALSE(svr.is_running());
  14852. });
  14853. svr.wait_until_ready();
  14854. Client cli(HOST, PORT);
  14855. auto res = cli.Get(
  14856. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14858. EXPECT_EQ(StatusCode::OK_200, res->status);
  14859. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14860. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14861. // and must not be selected.
  14862. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14863. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14864. }
  14865. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14866. Server svr;
  14867. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14868. std::string observed_remote_addr;
  14869. svr.Get("/ip", [&](const Request &req, Response &res) {
  14870. observed_remote_addr = req.remote_addr;
  14871. res.set_content("ok", "text/plain");
  14872. });
  14873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14874. auto se = detail::scope_exit([&] {
  14875. svr.stop();
  14876. t.join();
  14877. ASSERT_FALSE(svr.is_running());
  14878. });
  14879. svr.wait_until_ready();
  14880. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14881. // a forged address and the trusted proxy's own address; the forged value must
  14882. // not win over the address the trusted proxy actually recorded.
  14883. Client cli(HOST, PORT);
  14884. auto res = cli.Get(
  14885. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14887. EXPECT_EQ(StatusCode::OK_200, res->status);
  14888. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14889. }
  14890. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14891. Server svr;
  14892. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14893. std::string observed_remote_addr;
  14894. std::string observed_xff;
  14895. svr.Get("/ip", [&](const Request &req, Response &res) {
  14896. observed_remote_addr = req.remote_addr;
  14897. observed_xff = req.get_header_value("X-Forwarded-For");
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14901. auto se = detail::scope_exit([&] {
  14902. svr.stop();
  14903. t.join();
  14904. ASSERT_FALSE(svr.is_running());
  14905. });
  14906. svr.wait_until_ready();
  14907. Client cli(HOST, PORT);
  14908. auto res = cli.Get(
  14909. "/ip",
  14910. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14912. EXPECT_EQ(StatusCode::OK_200, res->status);
  14913. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14914. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14915. }
  14916. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14917. Server svr;
  14918. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14919. std::string observed_remote_addr;
  14920. std::string observed_xff;
  14921. svr.Get("/ip", [&](const Request &req, Response &res) {
  14922. observed_remote_addr = req.remote_addr;
  14923. observed_xff = req.get_header_value("X-Forwarded-For");
  14924. res.set_content("ok", "text/plain");
  14925. });
  14926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14927. auto se = detail::scope_exit([&] {
  14928. svr.stop();
  14929. t.join();
  14930. ASSERT_FALSE(svr.is_running());
  14931. });
  14932. svr.wait_until_ready();
  14933. std::string raw_req =
  14934. "GET /ip HTTP/1.1\r\n"
  14935. "Host: localhost\r\n"
  14936. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14937. "Connection: close\r\n"
  14938. "\r\n";
  14939. std::string out;
  14940. ASSERT_TRUE(send_request(5, raw_req, &out));
  14941. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14942. // Header parser trims surrounding whitespace of the header value
  14943. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14944. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14945. }
  14946. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14947. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14948. // their own X-Forwarded-For as a separate field line rather than extending the
  14949. // one the client sent, so every occurrence has to be taken into account.
  14950. // Reading only the first one hands back the address the client chose.
  14951. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14952. Server svr;
  14953. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14954. std::string observed_remote_addr;
  14955. size_t observed_xff_count = 0;
  14956. svr.Get("/ip", [&](const Request &req, Response &res) {
  14957. observed_remote_addr = req.remote_addr;
  14958. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14959. res.set_content("ok", "text/plain");
  14960. });
  14961. auto port = svr.bind_to_any_port(HOST);
  14962. thread t = thread([&]() { svr.listen_after_bind(); });
  14963. auto se = detail::scope_exit([&] {
  14964. svr.stop();
  14965. t.join();
  14966. ASSERT_FALSE(svr.is_running());
  14967. });
  14968. svr.wait_until_ready();
  14969. // The client supplies the first field line; the trusted proxy appends the
  14970. // address it observed as a second one.
  14971. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14972. "Host: localhost\r\n"
  14973. "X-Forwarded-For: 1.2.3.4\r\n"
  14974. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14975. "Connection: close\r\n"
  14976. "\r\n";
  14977. std::string out;
  14978. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14979. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14980. EXPECT_EQ(observed_xff_count, 2U);
  14981. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14982. // The same chain spread over one field line per hop derives the same client
  14983. // address, i.e. the split and the comma-joined representations agree.
  14984. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14985. "Host: localhost\r\n"
  14986. "X-Forwarded-For: 1.2.3.4\r\n"
  14987. "X-Forwarded-For: 198.51.100.23\r\n"
  14988. "X-Forwarded-For: 192.0.2.45\r\n"
  14989. "Connection: close\r\n"
  14990. "\r\n";
  14991. out.clear();
  14992. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14993. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14994. EXPECT_EQ(observed_xff_count, 3U);
  14995. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14996. }
  14997. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14998. // crash the server (it used to call front() on an empty vector inside
  14999. // get_client_ip). The connection-level remote address must be retained instead.
  15000. static void run_malformed_xff_test(const std::string &xff_value) {
  15001. Server svr;
  15002. svr.set_trusted_proxies({"192.0.2.45"});
  15003. std::string observed_remote_addr;
  15004. svr.Get("/ip", [&](const Request &req, Response &res) {
  15005. observed_remote_addr = req.remote_addr;
  15006. res.set_content("ok", "text/plain");
  15007. });
  15008. int port = 0;
  15009. thread t = thread([&]() {
  15010. port = svr.bind_to_any_port(HOST);
  15011. svr.listen_after_bind();
  15012. });
  15013. auto se = detail::scope_exit([&] {
  15014. svr.stop();
  15015. t.join();
  15016. ASSERT_FALSE(svr.is_running());
  15017. });
  15018. svr.wait_until_ready();
  15019. Client cli(HOST, port);
  15020. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15022. EXPECT_EQ(StatusCode::OK_200, res->status);
  15023. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15024. observed_remote_addr == "127.0.0.1");
  15025. }
  15026. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15027. run_malformed_xff_test("");
  15028. }
  15029. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15030. run_malformed_xff_test(",");
  15031. }
  15032. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15033. run_malformed_xff_test(", , ,");
  15034. }
  15035. // The same rule applies to Accept: a request whose acceptable types are spread
  15036. // over several field lines must be negotiated against all of them.
  15037. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15038. // case-insensitive connection options. Comparing the whole field value against
  15039. // one option misses a client that sends several of them, and misses every
  15040. // casing but the one written in the comparison.
  15041. //
  15042. // Sends req, reads the response, then reuses the same socket for a second
  15043. // request to find out whether the server kept the connection.
  15044. static void probe_connection_reuse(int port, const std::string &req,
  15045. bool *announced_close, bool *reusable) {
  15046. auto error = Error::Success;
  15047. auto sock = detail::create_client_socket(
  15048. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15049. /*connection_timeout_sec=*/5, 0,
  15050. /*read_timeout_sec=*/1, 0,
  15051. /*write_timeout_sec=*/5, 0, std::string(), error);
  15052. ASSERT_NE(sock, INVALID_SOCKET);
  15053. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15054. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15055. "Host: localhost\r\n"
  15056. "Connection: close\r\n"
  15057. "\r\n";
  15058. std::string first_response;
  15059. std::string second_response;
  15060. detail::process_client_socket(
  15061. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15062. [&](Stream &strm) {
  15063. if (strm.write(req.data(), req.size()) !=
  15064. static_cast<ssize_t>(req.size())) {
  15065. return false;
  15066. }
  15067. char buf[512];
  15068. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15069. // Headers plus the two-byte body of the handler below
  15070. while (reader.getline()) {
  15071. first_response += reader.ptr();
  15072. if (first_response.find("ok") != std::string::npos) { break; }
  15073. }
  15074. if (strm.write(second.data(), second.size()) !=
  15075. static_cast<ssize_t>(second.size())) {
  15076. return true;
  15077. }
  15078. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15079. while (reader2.getline()) {
  15080. second_response += reader2.ptr();
  15081. if (second_response.find("ok") != std::string::npos) { break; }
  15082. }
  15083. return true;
  15084. });
  15085. *announced_close =
  15086. first_response.find("Connection: close") != std::string::npos;
  15087. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15088. }
  15089. class ConnectionTokenTest : public ::testing::Test {
  15090. protected:
  15091. void SetUp() override {
  15092. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15093. res.set_content("ok", "text/plain");
  15094. });
  15095. port_ = svr_.bind_to_any_port(HOST);
  15096. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15097. svr_.wait_until_ready();
  15098. }
  15099. void TearDown() override {
  15100. svr_.stop();
  15101. if (thread_.joinable()) { thread_.join(); }
  15102. }
  15103. Server svr_;
  15104. int port_ = 0;
  15105. thread thread_;
  15106. };
  15107. // "close" alongside another option still closes the connection, and the
  15108. // response says so rather than leaving the peer to discover it.
  15109. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15110. bool announced_close = false;
  15111. bool reusable = true;
  15112. probe_connection_reuse(port_,
  15113. "GET /keepalive HTTP/1.1\r\n"
  15114. "Host: localhost\r\n"
  15115. "Connection: keep-alive, close\r\n"
  15116. "\r\n",
  15117. &announced_close, &reusable);
  15118. EXPECT_TRUE(announced_close);
  15119. EXPECT_FALSE(reusable);
  15120. }
  15121. // "close" split over two field lines is the same list, so it is honored too.
  15122. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15123. bool announced_close = false;
  15124. bool reusable = true;
  15125. probe_connection_reuse(port_,
  15126. "GET /keepalive HTTP/1.1\r\n"
  15127. "Host: localhost\r\n"
  15128. "Connection: keep-alive\r\n"
  15129. "Connection: close\r\n"
  15130. "\r\n",
  15131. &announced_close, &reusable);
  15132. EXPECT_TRUE(announced_close);
  15133. EXPECT_FALSE(reusable);
  15134. }
  15135. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15136. // keep-alive in the spelling everyone actually sends keeps its connection.
  15137. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15138. bool announced_close = false;
  15139. bool reusable = false;
  15140. probe_connection_reuse(port_,
  15141. "GET /keepalive HTTP/1.0\r\n"
  15142. "Host: localhost\r\n"
  15143. "Connection: keep-alive\r\n"
  15144. "\r\n",
  15145. &announced_close, &reusable);
  15146. EXPECT_FALSE(announced_close);
  15147. EXPECT_TRUE(reusable);
  15148. }
  15149. // A token the value merely contains is not the token itself.
  15150. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15151. bool announced_close = false;
  15152. bool reusable = false;
  15153. probe_connection_reuse(port_,
  15154. "GET /keepalive HTTP/1.1\r\n"
  15155. "Host: localhost\r\n"
  15156. "Connection: notclose\r\n"
  15157. "\r\n",
  15158. &announced_close, &reusable);
  15159. EXPECT_FALSE(announced_close);
  15160. EXPECT_TRUE(reusable);
  15161. }
  15162. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15163. Server svr;
  15164. std::vector<std::string> observed_types;
  15165. svr.Get("/", [&](const Request &req, Response &res) {
  15166. observed_types = req.accept_content_types;
  15167. res.set_content("ok", "text/plain");
  15168. });
  15169. auto port = svr.bind_to_any_port(HOST);
  15170. thread t = thread([&]() { svr.listen_after_bind(); });
  15171. auto se = detail::scope_exit([&] {
  15172. svr.stop();
  15173. t.join();
  15174. ASSERT_FALSE(svr.is_running());
  15175. });
  15176. svr.wait_until_ready();
  15177. Client cli(HOST, port);
  15178. Headers headers;
  15179. headers.emplace("Accept", "text/plain;q=0.5");
  15180. headers.emplace("Accept", "application/json");
  15181. auto res = cli.Get("/", headers);
  15182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15183. EXPECT_EQ(StatusCode::OK_200, res->status);
  15184. // Sorted by q-value, so the second field line's type comes first
  15185. ASSERT_EQ(2U, observed_types.size());
  15186. EXPECT_EQ("application/json", observed_types[0]);
  15187. EXPECT_EQ("text/plain", observed_types[1]);
  15188. }
  15189. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15190. // empty field line must not contribute a bare comma to the combined value.
  15191. // parse_accept_header() rejects a leading comma outright, so a stray one would
  15192. // turn a legal request into 400 Bad Request.
  15193. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15194. Server svr;
  15195. std::vector<std::string> observed_types;
  15196. svr.Get("/", [&](const Request &req, Response &res) {
  15197. observed_types = req.accept_content_types;
  15198. res.set_content("ok", "text/plain");
  15199. });
  15200. auto port = svr.bind_to_any_port(HOST);
  15201. thread t = thread([&]() { svr.listen_after_bind(); });
  15202. auto se = detail::scope_exit([&] {
  15203. svr.stop();
  15204. t.join();
  15205. ASSERT_FALSE(svr.is_running());
  15206. });
  15207. svr.wait_until_ready();
  15208. // Empty first field line, then a real one
  15209. std::string raw_req = "GET / HTTP/1.1\r\n"
  15210. "Host: localhost\r\n"
  15211. "Accept:\r\n"
  15212. "Accept: application/json\r\n"
  15213. "Connection: close\r\n"
  15214. "\r\n";
  15215. std::string out;
  15216. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15217. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15218. ASSERT_EQ(1U, observed_types.size());
  15219. EXPECT_EQ("application/json", observed_types[0]);
  15220. }
  15221. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15222. // An encoding offered on a later Accept-Encoding field line is still offered.
  15223. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15224. Server svr;
  15225. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15226. res.set_content(std::string(1024, 'x'), "text/plain");
  15227. });
  15228. auto port = svr.bind_to_any_port(HOST);
  15229. thread t = thread([&]() { svr.listen_after_bind(); });
  15230. auto se = detail::scope_exit([&] {
  15231. svr.stop();
  15232. t.join();
  15233. ASSERT_FALSE(svr.is_running());
  15234. });
  15235. svr.wait_until_ready();
  15236. Client cli(HOST, port);
  15237. cli.set_decompress(false);
  15238. Headers headers;
  15239. headers.emplace("Accept-Encoding", "identity");
  15240. headers.emplace("Accept-Encoding", "gzip");
  15241. auto res = cli.Get("/", headers);
  15242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15243. EXPECT_EQ(StatusCode::OK_200, res->status);
  15244. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15245. }
  15246. #endif
  15247. #ifndef _WIN32
  15248. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15249. Server svr;
  15250. svr.Post("/post", [&](const Request &req, Response &res) {
  15251. res.set_content(req.body, "text/plain");
  15252. });
  15253. svr.Put("/put", [&](const Request &req, Response &res) {
  15254. res.set_content(req.body, "text/plain");
  15255. });
  15256. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15257. res.set_content(req.body, "text/plain");
  15258. });
  15259. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15260. res.set_content(req.body, "text/plain");
  15261. });
  15262. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15263. auto se = detail::scope_exit([&] {
  15264. svr.stop();
  15265. t.join();
  15266. ASSERT_FALSE(svr.is_running());
  15267. });
  15268. svr.wait_until_ready();
  15269. std::string resp;
  15270. // POST without Content-Length
  15271. ASSERT_TRUE(send_request(5,
  15272. "POST /post HTTP/1.1\r\n"
  15273. "Host: localhost\r\n"
  15274. "Connection: close\r\n"
  15275. "\r\n",
  15276. &resp));
  15277. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15278. // PUT without Content-Length
  15279. resp.clear();
  15280. ASSERT_TRUE(send_request(5,
  15281. "PUT /put HTTP/1.1\r\n"
  15282. "Host: localhost\r\n"
  15283. "Connection: close\r\n"
  15284. "\r\n",
  15285. &resp));
  15286. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15287. // PATCH without Content-Length
  15288. resp.clear();
  15289. ASSERT_TRUE(send_request(5,
  15290. "PATCH /patch HTTP/1.1\r\n"
  15291. "Host: localhost\r\n"
  15292. "Connection: close\r\n"
  15293. "\r\n",
  15294. &resp));
  15295. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15296. // DELETE without Content-Length
  15297. resp.clear();
  15298. ASSERT_TRUE(send_request(5,
  15299. "DELETE /delete HTTP/1.1\r\n"
  15300. "Host: localhost\r\n"
  15301. "Connection: close\r\n"
  15302. "\r\n",
  15303. &resp));
  15304. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15305. }
  15306. #endif
  15307. //==============================================================================
  15308. // open_stream() Tests
  15309. //==============================================================================
  15310. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15311. std::string result;
  15312. char buf[8192];
  15313. ssize_t n;
  15314. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15315. result.append(buf, static_cast<size_t>(n));
  15316. }
  15317. return result;
  15318. }
  15319. // Mock stream for unit tests
  15320. class MockStream : public Stream {
  15321. public:
  15322. std::string data;
  15323. size_t pos = 0;
  15324. ssize_t error_after = -1; // -1 = no error
  15325. explicit MockStream(const std::string &d, ssize_t err = -1)
  15326. : data(d), error_after(err) {}
  15327. bool is_readable() const override { return true; }
  15328. bool wait_readable() const override { return true; }
  15329. bool wait_writable() const override { return true; }
  15330. ssize_t read(char *ptr, size_t size) override {
  15331. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15332. if (pos >= data.size()) return 0;
  15333. size_t limit =
  15334. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15335. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15336. std::memcpy(ptr, data.data() + pos, to_read);
  15337. pos += to_read;
  15338. return static_cast<ssize_t>(to_read);
  15339. }
  15340. ssize_t write(const char *, size_t) override { return -1; }
  15341. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15342. ip = "127.0.0.1";
  15343. port = 0;
  15344. }
  15345. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15346. ip = "127.0.0.1";
  15347. port = 0;
  15348. }
  15349. socket_t socket() const override { return INVALID_SOCKET; }
  15350. time_t duration() const override { return 0; }
  15351. };
  15352. TEST(StreamHandleTest, Basic) {
  15353. ClientImpl::StreamHandle handle;
  15354. EXPECT_FALSE(handle.is_valid());
  15355. handle.response = detail::make_unique<Response>();
  15356. handle.error = Error::Connection;
  15357. EXPECT_FALSE(handle.is_valid());
  15358. handle.error = Error::Success;
  15359. EXPECT_TRUE(handle.is_valid());
  15360. }
  15361. TEST(BodyReaderTest, Basic) {
  15362. MockStream stream("Hello, World!");
  15363. detail::BodyReader reader;
  15364. reader.stream = &stream;
  15365. reader.content_length = 13;
  15366. char buf[32];
  15367. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15368. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15369. EXPECT_TRUE(reader.eof);
  15370. }
  15371. TEST(BodyReaderTest, NoStream) {
  15372. detail::BodyReader reader;
  15373. char buf[32];
  15374. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15375. EXPECT_EQ(Error::Connection, reader.last_error);
  15376. }
  15377. TEST(BodyReaderTest, Error) {
  15378. MockStream stream("Hello, World!", 5);
  15379. detail::BodyReader reader;
  15380. reader.stream = &stream;
  15381. reader.content_length = 13;
  15382. char buf[32];
  15383. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15384. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15385. EXPECT_EQ(Error::Read, reader.last_error);
  15386. }
  15387. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15388. // Mock-based StreamHandle tests relying on private internals are removed.
  15389. class OpenStreamTest : public ::testing::Test {
  15390. protected:
  15391. void SetUp() override {
  15392. svr_.Get("/hello", [](const Request &, Response &res) {
  15393. res.set_content("Hello World!", "text/plain");
  15394. });
  15395. svr_.Get("/large", [](const Request &, Response &res) {
  15396. res.set_content(std::string(10000, 'X'), "text/plain");
  15397. });
  15398. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15399. res.set_content("Hello World!", "image/jpeg");
  15400. res.set_header("Content-Encoding", "UTF-8");
  15401. });
  15402. svr_.Get("/chunked", [](const Request &, Response &res) {
  15403. res.set_chunked_content_provider("text/plain",
  15404. [](size_t offset, DataSink &sink) {
  15405. if (offset < 15) {
  15406. sink.write("chunk", 5);
  15407. return true;
  15408. }
  15409. sink.done();
  15410. return true;
  15411. });
  15412. });
  15413. svr_.Get("/compressible", [](const Request &, Response &res) {
  15414. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15415. DataSink &sink) {
  15416. if (offset < 100 * 1024) {
  15417. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15418. sink.write(chunk.data(), chunk.size());
  15419. return true;
  15420. }
  15421. sink.done();
  15422. return true;
  15423. });
  15424. });
  15425. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15426. [](const Request & /*req*/, Response &res) {
  15427. auto i = new int(0);
  15428. res.set_header("Trailer", "Content-Length, X-Allowed");
  15429. res.set_chunked_content_provider(
  15430. "text/plain",
  15431. [i](size_t /*offset*/, DataSink &sink) {
  15432. switch (*i) {
  15433. case 0: sink.os << "123"; break;
  15434. case 1: sink.os << "456"; break;
  15435. case 2: sink.os << "789"; break;
  15436. case 3: {
  15437. sink.done_with_trailer(
  15438. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15439. } break;
  15440. }
  15441. (*i)++;
  15442. return true;
  15443. },
  15444. [i](bool success) {
  15445. EXPECT_TRUE(success);
  15446. delete i;
  15447. });
  15448. });
  15449. // Echo headers endpoint for header-related tests
  15450. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15451. std::string body;
  15452. for (const auto &h : req.headers) {
  15453. body.append(h.first);
  15454. body.push_back(':');
  15455. body.append(h.second);
  15456. body.push_back('\n');
  15457. }
  15458. res.set_content(body, "text/plain");
  15459. });
  15460. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15461. std::string body;
  15462. for (const auto &h : req.headers) {
  15463. body.append(h.first);
  15464. body.push_back(':');
  15465. body.append(h.second);
  15466. body.push_back('\n');
  15467. }
  15468. res.set_content(body, "text/plain");
  15469. });
  15470. port_ = svr_.bind_to_any_port("127.0.0.1");
  15471. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15472. svr_.wait_until_ready();
  15473. }
  15474. void TearDown() override {
  15475. svr_.stop();
  15476. if (thread_.joinable()) thread_.join();
  15477. }
  15478. Server svr_;
  15479. std::thread thread_;
  15480. int port_ = 0;
  15481. };
  15482. TEST_F(OpenStreamTest, Basic) {
  15483. Client cli("127.0.0.1", port_);
  15484. auto handle = cli.open_stream("GET", "/hello");
  15485. EXPECT_TRUE(handle.is_valid());
  15486. EXPECT_EQ("Hello World!", read_all(handle));
  15487. }
  15488. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15489. Client cli("127.0.0.1", port_);
  15490. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15491. ASSERT_TRUE(handle.is_valid());
  15492. EXPECT_EQ("Hello World!", read_all(handle));
  15493. }
  15494. TEST_F(OpenStreamTest, SmallBuffer) {
  15495. Client cli("127.0.0.1", port_);
  15496. auto handle = cli.open_stream("GET", "/hello");
  15497. std::string result;
  15498. char buf[4];
  15499. ssize_t n;
  15500. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15501. result.append(buf, static_cast<size_t>(n));
  15502. EXPECT_EQ("Hello World!", result);
  15503. }
  15504. TEST_F(OpenStreamTest, DefaultHeaders) {
  15505. Client cli("127.0.0.1", port_);
  15506. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15507. {
  15508. auto handle = cli.open_stream("GET", "/echo-headers");
  15509. ASSERT_TRUE(handle.is_valid());
  15510. auto body = read_all(handle);
  15511. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15512. std::string::npos);
  15513. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15514. std::string::npos);
  15515. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15516. }
  15517. // open_stream POST with body and no explicit content_type should NOT add
  15518. // text/plain Content-Type (behavior differs from non-streaming path), but
  15519. // should include Content-Length
  15520. {
  15521. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15522. ASSERT_TRUE(handle.is_valid());
  15523. auto body = read_all(handle);
  15524. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15525. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15526. }
  15527. // open_stream POST with explicit Content-Type should preserve it
  15528. {
  15529. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15530. {{"Content-Type", "application/custom"}},
  15531. "{}", "application/custom");
  15532. ASSERT_TRUE(handle.is_valid());
  15533. auto body = read_all(handle);
  15534. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15535. }
  15536. // User-specified User-Agent must not be overwritten for stream API
  15537. {
  15538. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15539. {{"User-Agent", "MyAgent/1.2"}});
  15540. ASSERT_TRUE(handle.is_valid());
  15541. auto body = read_all(handle);
  15542. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15543. }
  15544. }
  15545. TEST_F(OpenStreamTest, Large) {
  15546. Client cli("127.0.0.1", port_);
  15547. auto handle = cli.open_stream("GET", "/large");
  15548. EXPECT_EQ(10000u, read_all(handle).size());
  15549. }
  15550. TEST_F(OpenStreamTest, ConnectionError) {
  15551. Client cli("127.0.0.1", 9999);
  15552. auto handle = cli.open_stream("GET", "/hello");
  15553. EXPECT_FALSE(handle.is_valid());
  15554. }
  15555. TEST_F(OpenStreamTest, Chunked) {
  15556. Client cli("127.0.0.1", port_);
  15557. auto handle = cli.open_stream("GET", "/chunked");
  15558. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15559. "Transfer-Encoding") == "chunked");
  15560. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15561. }
  15562. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15563. Client cli("127.0.0.1", port_);
  15564. auto handle =
  15565. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15566. ASSERT_TRUE(handle.is_valid());
  15567. // Consume body to allow trailers to be received/parsed
  15568. auto body = read_all(handle);
  15569. // Explicitly parse trailers (ensure trailers are available for assertion)
  15570. handle.parse_trailers_if_needed();
  15571. EXPECT_EQ(std::string("123456789"), body);
  15572. // The response should include a Trailer header declaring both names
  15573. ASSERT_TRUE(handle.response);
  15574. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15575. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15576. handle.response->get_header_value("Trailer"));
  15577. // Prohibited trailer must not be present
  15578. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15579. // Allowed trailer should be present
  15580. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15581. EXPECT_EQ(std::string("yes"),
  15582. handle.response->get_trailer_value("X-Allowed"));
  15583. // Verify trailers are NOT present as regular headers
  15584. EXPECT_EQ(std::string(""),
  15585. handle.response->get_header_value("Content-Length"));
  15586. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15587. }
  15588. static std::thread serve_single_response(std::promise<int> &port_promise,
  15589. const std::string &response) {
  15590. return std::thread([&port_promise, response] {
  15591. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15592. default_socket_options(srv);
  15593. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15594. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15595. sockaddr_in addr{};
  15596. addr.sin_family = AF_INET;
  15597. addr.sin_port = htons(0); // Let OS assign a free port
  15598. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15599. int opt = 1;
  15600. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15601. #ifdef _WIN32
  15602. reinterpret_cast<const char *>(&opt),
  15603. #else
  15604. &opt,
  15605. #endif
  15606. sizeof(opt));
  15607. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15608. ::listen(srv, 1) != 0) {
  15609. port_promise.set_value(-1);
  15610. detail::close_socket(srv);
  15611. return;
  15612. }
  15613. socklen_t addr_len = sizeof(addr);
  15614. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15615. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15616. sockaddr_in cli_addr{};
  15617. socklen_t cli_len = sizeof(cli_addr);
  15618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15619. if (cli != INVALID_SOCKET) {
  15620. // Read the complete HTTP request (until the blank line that terminates
  15621. // headers) before sending the response. If the server closes the socket
  15622. // while the client's request data is still unread in the kernel receive
  15623. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15624. // connection on both sides: it discards the client's receive buffer
  15625. // (which already holds our response) and causes any in-progress write on
  15626. // the client to fail with ECONNRESET. Reading all request data first
  15627. // ensures close() emits a graceful FIN.
  15628. {
  15629. char rbuf[256];
  15630. std::string req;
  15631. while (req.find("\r\n\r\n") == std::string::npos) {
  15632. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15633. if (n <= 0) { break; }
  15634. req.append(rbuf, static_cast<size_t>(n));
  15635. }
  15636. }
  15637. ::send(cli,
  15638. #ifdef _WIN32
  15639. static_cast<const char *>(response.c_str()),
  15640. static_cast<int>(response.size()),
  15641. #else
  15642. response.c_str(), response.size(),
  15643. #endif
  15644. 0);
  15645. detail::close_socket(cli);
  15646. }
  15647. detail::close_socket(srv);
  15648. });
  15649. }
  15650. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15651. #ifndef _WIN32
  15652. signal(SIGPIPE, SIG_IGN);
  15653. #endif
  15654. std::promise<int> port_promise;
  15655. auto port_future = port_promise.get_future();
  15656. auto server_thread =
  15657. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15658. "Content-Type: text/plain\r\n"
  15659. "Content-Length: not-a-number\r\n"
  15660. "Connection: close\r\n"
  15661. "\r\n"
  15662. "hello");
  15663. auto port = port_future.get();
  15664. ASSERT_GT(port, 0);
  15665. Client cli("127.0.0.1", port);
  15666. auto handle = cli.open_stream("GET", "/");
  15667. EXPECT_FALSE(handle.is_valid());
  15668. server_thread.join();
  15669. }
  15670. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15671. #ifndef _WIN32
  15672. signal(SIGPIPE, SIG_IGN);
  15673. #endif
  15674. std::promise<int> port_promise;
  15675. auto port_future = port_promise.get_future();
  15676. auto server_thread = serve_single_response(
  15677. port_promise, "HTTP/1.1 200 OK\r\n"
  15678. "Content-Type: text/plain\r\n"
  15679. "Content-Length: 99999999999999999999999999\r\n"
  15680. "Connection: close\r\n"
  15681. "\r\n"
  15682. "hello");
  15683. auto port = port_future.get();
  15684. ASSERT_GT(port, 0);
  15685. // Historically std::stoull would throw std::out_of_range here and crash
  15686. // the process, then parsing silently clamped to a bogus framing length and
  15687. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15688. // so the stream fails to open, matching the not-a-number case above. The
  15689. // process still must NOT terminate.
  15690. Client cli("127.0.0.1", port);
  15691. auto handle = cli.open_stream("GET", "/");
  15692. EXPECT_FALSE(handle.is_valid());
  15693. server_thread.join();
  15694. }
  15695. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15696. TEST_F(OpenStreamTest, Gzip) {
  15697. Client cli("127.0.0.1", port_);
  15698. auto handle = cli.open_stream("GET", "/compressible", {},
  15699. {{"Accept-Encoding", "gzip"}});
  15700. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15701. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15702. }
  15703. #endif
  15704. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15705. TEST_F(OpenStreamTest, Brotli) {
  15706. Client cli("127.0.0.1", port_);
  15707. auto handle =
  15708. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15709. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15710. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15711. }
  15712. #endif
  15713. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15714. TEST_F(OpenStreamTest, Zstd) {
  15715. Client cli("127.0.0.1", port_);
  15716. auto handle = cli.open_stream("GET", "/compressible", {},
  15717. {{"Accept-Encoding", "zstd"}});
  15718. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15719. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15720. }
  15721. #endif
  15722. #ifdef CPPHTTPLIB_SSL_ENABLED
  15723. class SSLOpenStreamTest : public ::testing::Test {
  15724. protected:
  15725. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15726. void SetUp() override {
  15727. svr_.Get("/hello", [](const Request &, Response &res) {
  15728. res.set_content("Hello SSL World!", "text/plain");
  15729. });
  15730. svr_.Get("/chunked", [](const Request &, Response &res) {
  15731. res.set_chunked_content_provider("text/plain",
  15732. [](size_t offset, DataSink &sink) {
  15733. if (offset < 15) {
  15734. sink.write("chunk", 5);
  15735. return true;
  15736. }
  15737. sink.done();
  15738. return true;
  15739. });
  15740. });
  15741. svr_.Post("/echo", [](const Request &req, Response &res) {
  15742. res.set_content(req.body, req.get_header_value("Content-Type"));
  15743. });
  15744. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15745. std::string body = req.body;
  15746. res.set_chunked_content_provider(
  15747. "text/plain", [body](size_t offset, DataSink &sink) {
  15748. if (offset < body.size()) {
  15749. sink.write(body.data() + offset, body.size() - offset);
  15750. }
  15751. sink.done();
  15752. return true;
  15753. });
  15754. });
  15755. port_ = svr_.bind_to_any_port("127.0.0.1");
  15756. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15757. svr_.wait_until_ready();
  15758. }
  15759. void TearDown() override {
  15760. svr_.stop();
  15761. if (thread_.joinable()) thread_.join();
  15762. }
  15763. SSLServer svr_;
  15764. std::thread thread_;
  15765. int port_ = 0;
  15766. };
  15767. TEST_F(SSLOpenStreamTest, Basic) {
  15768. SSLClient cli("127.0.0.1", port_);
  15769. cli.enable_server_certificate_verification(false);
  15770. auto handle = cli.open_stream("GET", "/hello");
  15771. ASSERT_TRUE(handle.is_valid());
  15772. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15773. }
  15774. TEST_F(SSLOpenStreamTest, Chunked) {
  15775. SSLClient cli("127.0.0.1", port_);
  15776. cli.enable_server_certificate_verification(false);
  15777. auto handle = cli.open_stream("GET", "/chunked");
  15778. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15779. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15780. "Transfer-Encoding") == "chunked");
  15781. auto body = read_all(handle);
  15782. EXPECT_EQ("chunkchunkchunk", body);
  15783. }
  15784. TEST_F(SSLOpenStreamTest, Post) {
  15785. SSLClient cli("127.0.0.1", port_);
  15786. cli.enable_server_certificate_verification(false);
  15787. auto handle =
  15788. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15789. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15790. EXPECT_EQ(200, handle.response->status);
  15791. auto body = read_all(handle);
  15792. EXPECT_EQ("Hello SSL POST", body);
  15793. }
  15794. TEST_F(SSLOpenStreamTest, PostChunked) {
  15795. SSLClient cli("127.0.0.1", port_);
  15796. cli.enable_server_certificate_verification(false);
  15797. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15798. "Chunked SSL Data", "text/plain");
  15799. ASSERT_TRUE(handle.is_valid());
  15800. EXPECT_EQ(200, handle.response->status);
  15801. auto body = read_all(handle);
  15802. EXPECT_EQ("Chunked SSL Data", body);
  15803. }
  15804. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15805. // Content-Length is terminated by the server closing the connection. When the
  15806. // SSL peer sends a close_notify after the body, the client must treat it as a
  15807. // clean EOF and return a successful response rather than an error.
  15808. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15810. ASSERT_TRUE(svr.is_valid());
  15811. svr.set_keep_alive_max_count(1);
  15812. const std::string expected_body = "Hello from connection-close response!";
  15813. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15814. res.set_content_provider("text/plain",
  15815. [&](size_t offset, DataSink &sink) -> bool {
  15816. if (offset < expected_body.size()) {
  15817. sink.write(expected_body.data() + offset,
  15818. expected_body.size() - offset);
  15819. }
  15820. sink.done();
  15821. return true;
  15822. });
  15823. });
  15824. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15825. auto se = detail::scope_exit([&] {
  15826. svr.stop();
  15827. listen_thread.join();
  15828. ASSERT_FALSE(svr.is_running());
  15829. });
  15830. svr.wait_until_ready();
  15831. SSLClient cli(HOST, PORT);
  15832. cli.enable_server_certificate_verification(false);
  15833. auto res = cli.Get("/no-content-length");
  15834. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15835. EXPECT_EQ(StatusCode::OK_200, res->status);
  15836. EXPECT_EQ(expected_body, res->body);
  15837. }
  15838. #endif // CPPHTTPLIB_SSL_ENABLED
  15839. //==============================================================================
  15840. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15841. // results for various scenarios.
  15842. //==============================================================================
  15843. TEST(ParityTest, GetVsOpenStream) {
  15844. Server svr;
  15845. const std::string path = "/parity";
  15846. const std::string content = "Parity test content: hello world";
  15847. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15848. res.set_content(content, "text/plain");
  15849. });
  15850. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15851. auto se = detail::scope_exit([&] {
  15852. svr.stop();
  15853. t.join();
  15854. ASSERT_FALSE(svr.is_running());
  15855. });
  15856. svr.wait_until_ready();
  15857. Client cli(HOST, PORT);
  15858. // Non-stream path
  15859. auto r1 = cli.Get(path);
  15860. ASSERT_TRUE(r1);
  15861. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15862. // Stream path
  15863. auto h = cli.open_stream("GET", path);
  15864. ASSERT_TRUE(h.is_valid());
  15865. EXPECT_EQ(r1->body, read_all(h));
  15866. }
  15867. // Helper to compress data with provided compressor type T
  15868. template <typename Compressor>
  15869. static std::string compress_payload_for_parity(const std::string &in) {
  15870. std::string out;
  15871. Compressor compressor;
  15872. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15873. [&](const char *data, size_t n) {
  15874. out.append(data, n);
  15875. return true;
  15876. });
  15877. EXPECT_TRUE(ok);
  15878. return out;
  15879. }
  15880. // Helper function for compression parity tests
  15881. template <typename Compressor>
  15882. static void test_compression_parity(const std::string &original,
  15883. const std::string &path,
  15884. const std::string &encoding) {
  15885. const std::string compressed =
  15886. compress_payload_for_parity<Compressor>(original);
  15887. Server svr;
  15888. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15889. res.set_content(compressed, "application/octet-stream");
  15890. res.set_header("Content-Encoding", encoding);
  15891. });
  15892. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15893. auto se = detail::scope_exit([&] {
  15894. svr.stop();
  15895. t.join();
  15896. ASSERT_FALSE(svr.is_running());
  15897. });
  15898. svr.wait_until_ready();
  15899. Client cli(HOST, PORT);
  15900. // Non-streaming
  15901. {
  15902. auto res = cli.Get(path);
  15903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15904. EXPECT_EQ(StatusCode::OK_200, res->status);
  15905. EXPECT_EQ(original, res->body);
  15906. }
  15907. // Streaming
  15908. {
  15909. auto h = cli.open_stream("GET", path);
  15910. ASSERT_TRUE(h.is_valid());
  15911. EXPECT_EQ(original, read_all(h));
  15912. }
  15913. }
  15914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15915. TEST(ParityTest, Gzip) {
  15916. test_compression_parity<detail::gzip_compressor>(
  15917. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15918. }
  15919. #endif
  15920. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15921. TEST(ParityTest, Brotli) {
  15922. test_compression_parity<detail::brotli_compressor>(
  15923. "Hello, brotli parity test payload", "/parity-br", "br");
  15924. }
  15925. #endif
  15926. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15927. TEST(ParityTest, Zstd) {
  15928. test_compression_parity<detail::zstd_compressor>(
  15929. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15930. }
  15931. #endif
  15932. //==============================================================================
  15933. // New Stream API Tests
  15934. //==============================================================================
  15935. inline std::string read_body(httplib::stream::Result &result) {
  15936. std::string body;
  15937. while (result.next()) {
  15938. body.append(result.data(), result.size());
  15939. }
  15940. return body;
  15941. }
  15942. TEST(ClientConnectionTest, Basic) {
  15943. httplib::ClientConnection conn;
  15944. EXPECT_FALSE(conn.is_open());
  15945. conn.sock = 1;
  15946. EXPECT_TRUE(conn.is_open());
  15947. httplib::ClientConnection conn2(std::move(conn));
  15948. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15949. conn2.sock = INVALID_SOCKET;
  15950. }
  15951. // Unified test server for all stream::* tests
  15952. class StreamApiTest : public ::testing::Test {
  15953. protected:
  15954. void SetUp() override {
  15955. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15956. res.set_content("Hello World!", "text/plain");
  15957. });
  15958. svr_.Get("/echo-params",
  15959. [](const httplib::Request &req, httplib::Response &res) {
  15960. std::string r;
  15961. for (const auto &p : req.params) {
  15962. if (!r.empty()) r += "&";
  15963. r += p.first + "=" + p.second;
  15964. }
  15965. res.set_content(r, "text/plain");
  15966. });
  15967. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15968. res.set_content(req.body, req.get_header_value("Content-Type"));
  15969. });
  15970. svr_.Post("/echo-headers",
  15971. [](const httplib::Request &req, httplib::Response &res) {
  15972. std::string r;
  15973. for (const auto &h : req.headers)
  15974. r += h.first + ": " + h.second + "\n";
  15975. res.set_content(r, "text/plain");
  15976. });
  15977. svr_.Post("/echo-params",
  15978. [](const httplib::Request &req, httplib::Response &res) {
  15979. std::string r = "params:";
  15980. for (const auto &p : req.params)
  15981. r += p.first + "=" + p.second + ";";
  15982. res.set_content(r + " body:" + req.body, "text/plain");
  15983. });
  15984. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15985. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15986. });
  15987. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15988. res.set_content("PUT:" + req.body, "text/plain");
  15989. });
  15990. svr_.Patch("/echo",
  15991. [](const httplib::Request &req, httplib::Response &res) {
  15992. res.set_content("PATCH:" + req.body, "text/plain");
  15993. });
  15994. svr_.Delete(
  15995. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15996. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15997. "text/plain");
  15998. });
  15999. svr_.Get("/head-test",
  16000. [](const httplib::Request &, httplib::Response &res) {
  16001. res.set_content("body for HEAD", "text/plain");
  16002. });
  16003. svr_.Options("/options",
  16004. [](const httplib::Request &, httplib::Response &res) {
  16005. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16006. });
  16007. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16008. svr_.wait_until_ready();
  16009. }
  16010. void TearDown() override {
  16011. svr_.stop();
  16012. if (thread_.joinable()) thread_.join();
  16013. }
  16014. httplib::Server svr_;
  16015. std::thread thread_;
  16016. };
  16017. // stream::Get tests
  16018. TEST_F(StreamApiTest, GetBasic) {
  16019. httplib::Client cli(HOST, PORT);
  16020. auto result = httplib::stream::Get(cli, "/hello");
  16021. ASSERT_TRUE(result.is_valid());
  16022. EXPECT_EQ(200, result.status());
  16023. EXPECT_EQ("Hello World!", read_body(result));
  16024. }
  16025. TEST_F(StreamApiTest, GetWithParams) {
  16026. httplib::Client cli(HOST, PORT);
  16027. httplib::Params params{{"foo", "bar"}};
  16028. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16029. ASSERT_TRUE(result.is_valid());
  16030. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16031. }
  16032. TEST_F(StreamApiTest, GetConnectionError) {
  16033. httplib::Client cli(HOST, 9999);
  16034. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16035. }
  16036. TEST_F(StreamApiTest, Get404) {
  16037. httplib::Client cli(HOST, PORT);
  16038. auto result = httplib::stream::Get(cli, "/nonexistent");
  16039. EXPECT_TRUE(result.is_valid());
  16040. EXPECT_EQ(404, result.status());
  16041. }
  16042. // stream::Post tests
  16043. TEST_F(StreamApiTest, PostBasic) {
  16044. httplib::Client cli(HOST, PORT);
  16045. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16046. "application/json");
  16047. ASSERT_TRUE(result.is_valid());
  16048. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16049. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16050. }
  16051. TEST_F(StreamApiTest, PostWithHeaders) {
  16052. httplib::Client cli(HOST, PORT);
  16053. httplib::Headers headers{{"X-Custom", "value"}};
  16054. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16055. "text/plain");
  16056. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16057. }
  16058. TEST_F(StreamApiTest, PostWithParams) {
  16059. httplib::Client cli(HOST, PORT);
  16060. httplib::Params params{{"k", "v"}};
  16061. auto result =
  16062. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16063. auto body = read_body(result);
  16064. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16065. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16066. }
  16067. TEST_F(StreamApiTest, PostLarge) {
  16068. httplib::Client cli(HOST, PORT);
  16069. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16070. size_t total = 0;
  16071. while (result.next()) {
  16072. total += result.size();
  16073. }
  16074. EXPECT_EQ(100u * 1024u, total);
  16075. }
  16076. // stream::Put/Patch tests
  16077. TEST_F(StreamApiTest, PutAndPatch) {
  16078. httplib::Client cli(HOST, PORT);
  16079. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16080. EXPECT_EQ("PUT:test", read_body(put));
  16081. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16082. EXPECT_EQ("PATCH:test", read_body(patch));
  16083. }
  16084. // stream::Delete tests
  16085. TEST_F(StreamApiTest, Delete) {
  16086. httplib::Client cli(HOST, PORT);
  16087. auto del1 = httplib::stream::Delete(cli, "/resource");
  16088. EXPECT_EQ("Deleted", read_body(del1));
  16089. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16090. EXPECT_EQ("Deleted:data", read_body(del2));
  16091. }
  16092. // stream::Head/Options tests
  16093. TEST_F(StreamApiTest, HeadAndOptions) {
  16094. httplib::Client cli(HOST, PORT);
  16095. auto head = httplib::stream::Head(cli, "/head-test");
  16096. EXPECT_TRUE(head.is_valid());
  16097. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16098. auto opts = httplib::stream::Options(cli, "/options");
  16099. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16100. }
  16101. // SSL stream::* tests
  16102. #ifdef CPPHTTPLIB_SSL_ENABLED
  16103. class SSLStreamApiTest : public ::testing::Test {
  16104. protected:
  16105. void SetUp() override {
  16106. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16107. res.set_content("Hello SSL!", "text/plain");
  16108. });
  16109. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16110. res.set_content(req.body, "text/plain");
  16111. });
  16112. port_ = svr_.bind_to_any_port("127.0.0.1");
  16113. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16114. svr_.wait_until_ready();
  16115. }
  16116. void TearDown() override {
  16117. svr_.stop();
  16118. if (thread_.joinable()) thread_.join();
  16119. }
  16120. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16121. std::thread thread_;
  16122. int port_ = 0;
  16123. };
  16124. TEST_F(SSLStreamApiTest, GetAndPost) {
  16125. httplib::SSLClient cli("127.0.0.1", port_);
  16126. cli.enable_server_certificate_verification(false);
  16127. auto get = httplib::stream::Get(cli, "/hello");
  16128. EXPECT_EQ("Hello SSL!", read_body(get));
  16129. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16130. EXPECT_EQ("test", read_body(post));
  16131. }
  16132. #endif
  16133. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16134. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16135. // BodyReader
  16136. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16137. // Test that read timeout during streaming is detected
  16138. // Use a large content-length response where server delays mid-stream
  16139. Server svr;
  16140. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16141. // Send a large response with delay in the middle
  16142. res.set_content_provider(
  16143. 1000, // content_length
  16144. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16145. if (offset < 100) {
  16146. // Send first 100 bytes immediately
  16147. std::string data(100, 'A');
  16148. sink.write(data.c_str(), data.size());
  16149. return true;
  16150. }
  16151. // Then delay longer than client timeout
  16152. std::this_thread::sleep_for(std::chrono::seconds(3));
  16153. std::string data(900, 'B');
  16154. sink.write(data.c_str(), data.size());
  16155. return true;
  16156. });
  16157. });
  16158. auto port = 8091;
  16159. std::thread t([&]() { svr.listen("localhost", port); });
  16160. svr.wait_until_ready();
  16161. Client cli("localhost", port);
  16162. cli.set_read_timeout(1, 0); // 1 second timeout
  16163. auto handle = cli.open_stream("GET", "/slow-stream");
  16164. ASSERT_TRUE(handle.is_valid());
  16165. char buf[256];
  16166. ssize_t total = 0;
  16167. ssize_t n;
  16168. bool got_error = false;
  16169. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16170. total += n;
  16171. }
  16172. if (n < 0) {
  16173. got_error = true;
  16174. // Should be timeout or read error
  16175. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16176. handle.get_read_error() == Error::Read)
  16177. << "Actual error: " << to_string(handle.get_read_error());
  16178. }
  16179. // Either we got an error, or we got less data than expected
  16180. EXPECT_TRUE(got_error || total < 1000)
  16181. << "Expected timeout but got all " << total << " bytes";
  16182. svr.stop();
  16183. t.join();
  16184. }
  16185. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16186. // Test connection closed detection via BodyReader
  16187. Server svr;
  16188. std::atomic<bool> close_now{false};
  16189. svr.Get("/will-close", [&](const Request &, Response &res) {
  16190. res.set_content_provider(
  16191. 10000, // Large content_length that we won't fully send
  16192. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16193. if (offset < 100) {
  16194. std::string data(100, 'X');
  16195. sink.write(data.c_str(), data.size());
  16196. return true;
  16197. }
  16198. // Wait for signal then abort
  16199. while (!close_now) {
  16200. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16201. }
  16202. return false; // Abort - server will close connection
  16203. });
  16204. });
  16205. auto port = 8092;
  16206. std::thread t([&]() { svr.listen("localhost", port); });
  16207. svr.wait_until_ready();
  16208. Client cli("localhost", port);
  16209. auto handle = cli.open_stream("GET", "/will-close");
  16210. ASSERT_TRUE(handle.is_valid());
  16211. char buf[256];
  16212. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16213. EXPECT_GT(n, 0) << "First read should succeed";
  16214. // Signal server to close
  16215. close_now = true;
  16216. // Keep reading until error or EOF
  16217. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16218. // Keep reading
  16219. }
  16220. // Should get an error since content_length wasn't satisfied
  16221. if (n < 0) {
  16222. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16223. handle.get_read_error() == Error::Read)
  16224. << "Actual error: " << to_string(handle.get_read_error());
  16225. }
  16226. svr.stop();
  16227. t.join();
  16228. }
  16229. #ifdef CPPHTTPLIB_SSL_ENABLED
  16230. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16231. // Test that read timeout during SSL streaming is detected
  16232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16233. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16234. res.set_content_provider(
  16235. 1000, "text/plain",
  16236. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16237. if (offset < 100) {
  16238. std::string data(100, 'A');
  16239. sink.write(data.c_str(), data.size());
  16240. return true;
  16241. }
  16242. std::this_thread::sleep_for(std::chrono::seconds(3));
  16243. std::string data(900, 'B');
  16244. sink.write(data.c_str(), data.size());
  16245. return true;
  16246. });
  16247. });
  16248. auto port = 8093;
  16249. std::thread t([&]() { svr.listen("localhost", port); });
  16250. svr.wait_until_ready();
  16251. SSLClient cli("localhost", port);
  16252. cli.enable_server_certificate_verification(false);
  16253. cli.set_read_timeout(1, 0); // 1 second timeout
  16254. auto handle = cli.open_stream("GET", "/slow-stream");
  16255. ASSERT_TRUE(handle.is_valid());
  16256. char buf[256];
  16257. ssize_t total = 0;
  16258. ssize_t n;
  16259. bool got_error = false;
  16260. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16261. total += n;
  16262. }
  16263. if (n < 0) {
  16264. got_error = true;
  16265. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16266. handle.get_read_error() == Error::Read)
  16267. << "Actual error: " << to_string(handle.get_read_error());
  16268. }
  16269. EXPECT_TRUE(got_error || total < 1000)
  16270. << "Expected timeout but got all " << total << " bytes";
  16271. svr.stop();
  16272. t.join();
  16273. }
  16274. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16275. // Test SSL connection closed detection
  16276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16277. std::atomic<bool> close_now{false};
  16278. svr.Get("/will-close", [&](const Request &, Response &res) {
  16279. res.set_content_provider(
  16280. 10000, "text/plain",
  16281. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16282. if (offset < 100) {
  16283. std::string data(100, 'X');
  16284. sink.write(data.c_str(), data.size());
  16285. return true;
  16286. }
  16287. while (!close_now) {
  16288. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16289. }
  16290. return false;
  16291. });
  16292. });
  16293. auto port = 8094;
  16294. std::thread t([&]() { svr.listen("localhost", port); });
  16295. svr.wait_until_ready();
  16296. SSLClient cli("localhost", port);
  16297. cli.enable_server_certificate_verification(false);
  16298. auto handle = cli.open_stream("GET", "/will-close");
  16299. ASSERT_TRUE(handle.is_valid());
  16300. char buf[256];
  16301. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16302. EXPECT_GT(n, 0);
  16303. // Signal server to close
  16304. close_now = true;
  16305. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16306. // Keep reading
  16307. }
  16308. if (n < 0) {
  16309. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16310. handle.get_read_error() == Error::Read)
  16311. << "Actual error: " << to_string(handle.get_read_error());
  16312. }
  16313. svr.stop();
  16314. t.join();
  16315. }
  16316. #endif
  16317. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16318. using namespace httplib;
  16319. // Create a test file
  16320. const char *fname = "etag_testfile.txt";
  16321. const char *content = "etag-content";
  16322. {
  16323. std::ofstream ofs(fname);
  16324. ofs << content;
  16325. ASSERT_TRUE(ofs.good());
  16326. }
  16327. Server svr;
  16328. svr.set_mount_point("/static", ".");
  16329. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16330. svr.wait_until_ready();
  16331. Client cli(HOST, PORT);
  16332. // First request: should get 200 with ETag header
  16333. auto res1 = cli.Get("/static/etag_testfile.txt");
  16334. ASSERT_TRUE(res1);
  16335. ASSERT_EQ(200, res1->status);
  16336. ASSERT_TRUE(res1->has_header("ETag"));
  16337. std::string etag = res1->get_header_value("ETag");
  16338. EXPECT_FALSE(etag.empty());
  16339. // Verify ETag format: W/"hex-hex"
  16340. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16341. EXPECT_EQ('W', etag[0]);
  16342. EXPECT_EQ('/', etag[1]);
  16343. EXPECT_EQ('"', etag[2]);
  16344. EXPECT_EQ('"', etag.back());
  16345. // Exact match: expect 304 Not Modified
  16346. Headers h2 = {{"If-None-Match", etag}};
  16347. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16348. ASSERT_TRUE(res2);
  16349. EXPECT_EQ(304, res2->status);
  16350. // Wildcard match: expect 304 Not Modified
  16351. Headers h3 = {{"If-None-Match", "*"}};
  16352. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16353. ASSERT_TRUE(res3);
  16354. EXPECT_EQ(304, res3->status);
  16355. // Non-matching ETag: expect 200
  16356. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16357. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16358. ASSERT_TRUE(res4);
  16359. EXPECT_EQ(200, res4->status);
  16360. // Multiple ETags with one matching: expect 304
  16361. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16362. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16363. ASSERT_TRUE(res5);
  16364. EXPECT_EQ(304, res5->status);
  16365. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16366. // that equivalent to the single comma-separated list above, so the match on
  16367. // the second line must still be found.
  16368. Headers h6;
  16369. h6.emplace("If-None-Match", "W/\"other\"");
  16370. h6.emplace("If-None-Match", etag);
  16371. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16372. ASSERT_TRUE(res6);
  16373. EXPECT_EQ(304, res6->status);
  16374. svr.stop();
  16375. t.join();
  16376. std::remove(fname);
  16377. }
  16378. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16379. using namespace httplib;
  16380. Server svr;
  16381. svr.set_mount_point("/static", ".");
  16382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16383. svr.wait_until_ready();
  16384. Client cli(HOST, PORT);
  16385. // Send If-None-Match: * to a non-existent file
  16386. Headers h = {{"If-None-Match", "*"}};
  16387. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16389. EXPECT_EQ(404, res->status);
  16390. svr.stop();
  16391. t.join();
  16392. }
  16393. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16394. using namespace httplib;
  16395. // Create a test file
  16396. const char *fname = "etag_boundary_testfile.txt";
  16397. const char *content = "boundary-test";
  16398. {
  16399. std::ofstream ofs(fname);
  16400. ofs << content;
  16401. ASSERT_TRUE(ofs.good());
  16402. }
  16403. Server svr;
  16404. svr.set_mount_point("/static", ".");
  16405. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16406. svr.wait_until_ready();
  16407. Client cli(HOST, PORT);
  16408. // Get the actual ETag
  16409. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16410. ASSERT_TRUE(res1);
  16411. ASSERT_EQ(200, res1->status);
  16412. ASSERT_TRUE(res1->has_header("ETag"));
  16413. std::string etag = res1->get_header_value("ETag");
  16414. // Test 1: Very long ETag value (longer than actual ETag)
  16415. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16416. Headers h1 = {{"If-None-Match", "W/"
  16417. "\"very-long-etag-value-that-is-much-longer-"
  16418. "than-the-actual-etag-value\""}};
  16419. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16420. ASSERT_TRUE(res2);
  16421. EXPECT_EQ(200, res2->status); // Should not match
  16422. // Test 2: Long string followed by wildcard
  16423. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16424. // string)
  16425. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16426. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16427. ASSERT_TRUE(res3);
  16428. EXPECT_EQ(304, res3->status); // Should match on "*"
  16429. // Test 3: Wildcard followed by long string
  16430. // Should match on "*" immediately and return 304
  16431. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16432. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16433. ASSERT_TRUE(res4);
  16434. EXPECT_EQ(304, res4->status); // Should match on "*"
  16435. // Test 4: Multiple long non-matching values
  16436. // Should NOT match and return 200 (test that all comparisons are safe)
  16437. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16438. "W/\"second-long-non-matching-value\", "
  16439. "W/\"third-long-non-matching-value\""}};
  16440. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16441. ASSERT_TRUE(res5);
  16442. EXPECT_EQ(200, res5->status); // Should not match
  16443. // Test 5: Single character that is not "*" (edge case)
  16444. Headers h5 = {{"If-None-Match", "X"}};
  16445. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16446. ASSERT_TRUE(res6);
  16447. EXPECT_EQ(200, res6->status); // Should not match
  16448. svr.stop();
  16449. t.join();
  16450. std::remove(fname);
  16451. }
  16452. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16453. using namespace httplib;
  16454. // Create a test file
  16455. const char *fname = "ims_testfile.txt";
  16456. const char *content = "if-modified-since-test";
  16457. {
  16458. std::ofstream ofs(fname);
  16459. ofs << content;
  16460. ASSERT_TRUE(ofs.good());
  16461. }
  16462. Server svr;
  16463. svr.set_mount_point("/static", ".");
  16464. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16465. svr.wait_until_ready();
  16466. Client cli(HOST, PORT);
  16467. // First request: should get 200 with Last-Modified header
  16468. auto res1 = cli.Get("/static/ims_testfile.txt");
  16469. ASSERT_TRUE(res1);
  16470. ASSERT_EQ(200, res1->status);
  16471. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16472. std::string last_modified = res1->get_header_value("Last-Modified");
  16473. EXPECT_FALSE(last_modified.empty());
  16474. // If-Modified-Since with same time: expect 304
  16475. Headers h2 = {{"If-Modified-Since", last_modified}};
  16476. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16477. ASSERT_TRUE(res2);
  16478. EXPECT_EQ(304, res2->status);
  16479. // If-Modified-Since with future time: expect 304
  16480. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16481. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16482. ASSERT_TRUE(res3);
  16483. EXPECT_EQ(304, res3->status);
  16484. // If-Modified-Since with past time: expect 200
  16485. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16486. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16487. ASSERT_TRUE(res4);
  16488. EXPECT_EQ(200, res4->status);
  16489. // If-None-Match takes precedence over If-Modified-Since
  16490. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16491. ASSERT_TRUE(res1->has_header("ETag"));
  16492. std::string etag = res1->get_header_value("ETag");
  16493. Headers h5 = {{"If-None-Match", etag},
  16494. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16495. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16496. ASSERT_TRUE(res5);
  16497. EXPECT_EQ(304, res5->status);
  16498. svr.stop();
  16499. t.join();
  16500. std::remove(fname);
  16501. }
  16502. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16503. using namespace httplib;
  16504. Server svr;
  16505. // Endpoint that returns compressible content
  16506. svr.Get("/compressible", [](const Request &, Response &res) {
  16507. // Return a large enough body to trigger compression
  16508. std::string body(1000, 'a');
  16509. res.set_content(body, "text/plain");
  16510. });
  16511. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16512. svr.wait_until_ready();
  16513. Client cli(HOST, PORT);
  16514. // Request with gzip support: should get Vary header when compressed
  16515. cli.set_compress(true);
  16516. auto res1 = cli.Get("/compressible");
  16517. ASSERT_TRUE(res1);
  16518. EXPECT_EQ(200, res1->status);
  16519. // If Content-Encoding is set, Vary should also be set
  16520. if (res1->has_header("Content-Encoding")) {
  16521. EXPECT_TRUE(res1->has_header("Vary"));
  16522. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16523. }
  16524. // Request without Accept-Encoding header: should not have compression
  16525. Headers h_no_compress;
  16526. auto res2 = cli.Get("/compressible", h_no_compress);
  16527. ASSERT_TRUE(res2);
  16528. EXPECT_EQ(200, res2->status);
  16529. // Verify Vary header is present when compression is applied
  16530. // (the exact behavior depends on server configuration)
  16531. svr.stop();
  16532. t.join();
  16533. }
  16534. TEST(ETagTest, IfRangeWithETag) {
  16535. using namespace httplib;
  16536. // Create a test file with known content
  16537. const char *fname = "if_range_testfile.txt";
  16538. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16539. {
  16540. std::ofstream ofs(fname);
  16541. ofs << content;
  16542. ASSERT_TRUE(ofs.good());
  16543. }
  16544. Server svr;
  16545. svr.set_mount_point("/static", ".");
  16546. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16547. svr.wait_until_ready();
  16548. Client cli(HOST, PORT);
  16549. // First request: get ETag
  16550. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16551. ASSERT_TRUE(res1);
  16552. ASSERT_EQ(200, res1->status);
  16553. ASSERT_TRUE(res1->has_header("ETag"));
  16554. std::string etag = res1->get_header_value("ETag");
  16555. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16556. // Since our server generates weak ETags (W/"..."), If-Range with our
  16557. // ETag should NOT result in partial content - it should return full content.
  16558. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16559. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16560. ASSERT_TRUE(res2);
  16561. // Weak ETag in If-Range -> full content (200), not partial (206)
  16562. EXPECT_EQ(200, res2->status);
  16563. EXPECT_EQ(content, res2->body);
  16564. EXPECT_FALSE(res2->has_header("Content-Range"));
  16565. // Range request with non-matching If-Range (ETag): should get 200 (full
  16566. // content)
  16567. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16568. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16569. ASSERT_TRUE(res3);
  16570. EXPECT_EQ(200, res3->status);
  16571. EXPECT_EQ(content, res3->body);
  16572. EXPECT_FALSE(res3->has_header("Content-Range"));
  16573. // Range request with strong ETag (hypothetical - our server doesn't generate
  16574. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16575. // should return full content)
  16576. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16577. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16578. ASSERT_TRUE(res4);
  16579. EXPECT_EQ(200, res4->status);
  16580. EXPECT_EQ(content, res4->body);
  16581. EXPECT_FALSE(res4->has_header("Content-Range"));
  16582. svr.stop();
  16583. t.join();
  16584. std::remove(fname);
  16585. }
  16586. TEST(ETagTest, IfRangeWithDate) {
  16587. using namespace httplib;
  16588. // Create a test file
  16589. const char *fname = "if_range_date_testfile.txt";
  16590. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16591. {
  16592. std::ofstream ofs(fname);
  16593. ofs << content;
  16594. ASSERT_TRUE(ofs.good());
  16595. }
  16596. Server svr;
  16597. svr.set_mount_point("/static", ".");
  16598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16599. svr.wait_until_ready();
  16600. Client cli(HOST, PORT);
  16601. // First request: get Last-Modified
  16602. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16603. ASSERT_TRUE(res1);
  16604. ASSERT_EQ(200, res1->status);
  16605. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16606. std::string last_modified = res1->get_header_value("Last-Modified");
  16607. // Range request with matching If-Range (date): should get 206
  16608. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16609. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16610. ASSERT_TRUE(res2);
  16611. EXPECT_EQ(206, res2->status);
  16612. EXPECT_EQ("FGHIJ", res2->body);
  16613. // Range request with old If-Range date: should get 200 (full content)
  16614. Headers h3 = {{"Range", "bytes=5-9"},
  16615. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16616. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16617. ASSERT_TRUE(res3);
  16618. EXPECT_EQ(200, res3->status);
  16619. EXPECT_EQ(content, res3->body);
  16620. // Range request with future If-Range date: should get 206
  16621. Headers h4 = {{"Range", "bytes=0-4"},
  16622. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16623. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16624. ASSERT_TRUE(res4);
  16625. EXPECT_EQ(206, res4->status);
  16626. EXPECT_EQ("ABCDE", res4->body);
  16627. svr.stop();
  16628. t.join();
  16629. std::remove(fname);
  16630. }
  16631. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16632. using namespace httplib;
  16633. const char *fname = "etag_malformed.txt";
  16634. const char *content = "malformed-etag";
  16635. {
  16636. std::ofstream ofs(fname);
  16637. ofs << content;
  16638. ASSERT_TRUE(ofs.good());
  16639. }
  16640. Server svr;
  16641. svr.set_mount_point("/static", ".");
  16642. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16643. svr.wait_until_ready();
  16644. Client cli(HOST, PORT);
  16645. // baseline: should get 200 and an ETag
  16646. auto res1 = cli.Get("/static/etag_malformed.txt");
  16647. ASSERT_TRUE(res1);
  16648. ASSERT_EQ(200, res1->status);
  16649. ASSERT_TRUE(res1->has_header("ETag"));
  16650. // Malformed ETag value (missing quotes) should be treated as non-matching
  16651. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16652. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16653. ASSERT_TRUE(res_bad);
  16654. EXPECT_EQ(200, res_bad->status);
  16655. // Whitespace-only header value should be considered invalid / non-matching
  16656. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16657. "Host: localhost\r\n"
  16658. "If-None-Match: \r\n"
  16659. "Connection: close\r\n"
  16660. "\r\n";
  16661. std::string out;
  16662. ASSERT_TRUE(send_request(5, raw_req, &out));
  16663. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16664. svr.stop();
  16665. t.join();
  16666. std::remove(fname);
  16667. }
  16668. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16669. using namespace httplib;
  16670. const char *fname = "ims_invalid_format.txt";
  16671. const char *content = "ims-bad-format";
  16672. {
  16673. std::ofstream ofs(fname);
  16674. ofs << content;
  16675. ASSERT_TRUE(ofs.good());
  16676. }
  16677. Server svr;
  16678. svr.set_mount_point("/static", ".");
  16679. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16680. svr.wait_until_ready();
  16681. Client cli(HOST, PORT);
  16682. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16683. ASSERT_TRUE(res1);
  16684. ASSERT_EQ(200, res1->status);
  16685. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16686. // If-Modified-Since with invalid format should not result in 304
  16687. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16688. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16689. ASSERT_TRUE(res_bad);
  16690. EXPECT_EQ(200, res_bad->status);
  16691. // If-Range with invalid date format should be treated as mismatch -> full
  16692. // content (200)
  16693. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16694. {"If-Range", "invalid-date"}};
  16695. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16696. ASSERT_TRUE(res_ifrange);
  16697. EXPECT_EQ(200, res_ifrange->status);
  16698. svr.stop();
  16699. t.join();
  16700. std::remove(fname);
  16701. }
  16702. TEST(ETagTest, IfRangeWithMalformedETag) {
  16703. using namespace httplib;
  16704. const char *fname = "ifrange_malformed.txt";
  16705. const std::string content = "0123456789";
  16706. {
  16707. std::ofstream ofs(fname);
  16708. ofs << content;
  16709. ASSERT_TRUE(ofs.good());
  16710. }
  16711. Server svr;
  16712. svr.set_mount_point("/static", ".");
  16713. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16714. svr.wait_until_ready();
  16715. Client cli(HOST, PORT);
  16716. // First request: get ETag
  16717. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16718. ASSERT_TRUE(res1);
  16719. ASSERT_EQ(200, res1->status);
  16720. ASSERT_TRUE(res1->has_header("ETag"));
  16721. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16722. // full content (200)
  16723. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16724. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16725. ASSERT_TRUE(res2);
  16726. EXPECT_EQ(200, res2->status);
  16727. EXPECT_EQ(content, res2->body);
  16728. svr.stop();
  16729. t.join();
  16730. std::remove(fname);
  16731. }
  16732. TEST(ETagTest, ExtremeLargeDateValues) {
  16733. using namespace httplib;
  16734. const char *fname = "ims_extreme_date.txt";
  16735. const char *content = "ims-extreme-date";
  16736. {
  16737. std::ofstream ofs(fname);
  16738. ofs << content;
  16739. ASSERT_TRUE(ofs.good());
  16740. }
  16741. Server svr;
  16742. svr.set_mount_point("/static", ".");
  16743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16744. svr.wait_until_ready();
  16745. Client cli(HOST, PORT);
  16746. auto res1 = cli.Get(std::string("/static/") + fname);
  16747. ASSERT_TRUE(res1);
  16748. ASSERT_EQ(200, res1->status);
  16749. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16750. // Extremely large year that may overflow date parsing routines.
  16751. Headers h_large_date = {
  16752. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16753. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16754. ASSERT_TRUE(res_bad);
  16755. // Expect server to treat this as invalid/mismatch and return full content
  16756. EXPECT_EQ(200, res_bad->status);
  16757. // If-Range with extremely large date should be treated as mismatch -> full
  16758. // content (200)
  16759. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16760. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16761. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16762. ASSERT_TRUE(res_ifrange);
  16763. EXPECT_EQ(200, res_ifrange->status);
  16764. svr.stop();
  16765. t.join();
  16766. std::remove(fname);
  16767. }
  16768. TEST(ETagTest, NegativeFileModificationTime) {
  16769. using namespace httplib;
  16770. const char *fname = "ims_negative_mtime.txt";
  16771. const std::string content = "negative-mtime";
  16772. {
  16773. std::ofstream ofs(fname);
  16774. ofs << content;
  16775. ASSERT_TRUE(ofs.good());
  16776. }
  16777. // Try to set file mtime to a negative value. This may fail on some
  16778. // platforms/filesystems; if it fails, the test will still verify server
  16779. // behaves safely by performing a regular conditional request.
  16780. #if defined(__APPLE__) || defined(__linux__)
  16781. bool set_negative = false;
  16782. do {
  16783. struct timeval times[2];
  16784. // access time: now
  16785. times[0].tv_sec = time(nullptr);
  16786. times[0].tv_usec = 0;
  16787. // modification time: negative (e.g., -1)
  16788. times[1].tv_sec = -1;
  16789. times[1].tv_usec = 0;
  16790. if (utimes(fname, times) == 0) { set_negative = true; }
  16791. } while (0);
  16792. #else
  16793. bool set_negative = false;
  16794. #endif
  16795. Server svr;
  16796. svr.set_mount_point("/static", ".");
  16797. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16798. svr.wait_until_ready();
  16799. Client cli(HOST, PORT);
  16800. auto res1 = cli.Get(std::string("/static/") + fname);
  16801. ASSERT_TRUE(res1);
  16802. ASSERT_EQ(200, res1->status);
  16803. bool has_last_modified = res1->has_header("Last-Modified");
  16804. std::string last_modified;
  16805. if (has_last_modified) {
  16806. last_modified = res1->get_header_value("Last-Modified");
  16807. }
  16808. if (set_negative) {
  16809. // If we successfully set a negative mtime, ensure server returns a
  16810. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16811. // with an old date and ensure server handles it without crash.
  16812. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16813. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16814. ASSERT_TRUE(res2);
  16815. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16816. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16817. } else {
  16818. // Could not set negative mtime on this platform; fall back to verifying
  16819. // that normal invalid/malformed dates are treated safely (non-304).
  16820. Headers h_bad_date = {
  16821. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16822. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16823. ASSERT_TRUE(res_bad);
  16824. EXPECT_EQ(200, res_bad->status);
  16825. }
  16826. svr.stop();
  16827. t.join();
  16828. std::remove(fname);
  16829. }
  16830. //==============================================================================
  16831. // SSE Parsing Tests
  16832. //==============================================================================
  16833. class SSEParsingTest : public ::testing::Test {
  16834. protected:
  16835. // Test helper that mimics SSE parsing behavior
  16836. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16837. int &retry_ms) {
  16838. // Blank line signals end of event
  16839. if (line.empty() || line == "\r") { return true; }
  16840. // Lines starting with ':' are comments (ignored)
  16841. if (!line.empty() && line[0] == ':') { return false; }
  16842. // Find the colon separator
  16843. auto colon_pos = line.find(':');
  16844. if (colon_pos == std::string::npos) {
  16845. // Line with no colon is treated as field name with empty value
  16846. return false;
  16847. }
  16848. std::string field = line.substr(0, colon_pos);
  16849. std::string value;
  16850. // Value starts after colon, skip optional single space
  16851. if (colon_pos + 1 < line.size()) {
  16852. size_t value_start = colon_pos + 1;
  16853. if (line[value_start] == ' ') { value_start++; }
  16854. value = line.substr(value_start);
  16855. // Remove trailing \r if present
  16856. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16857. }
  16858. // Handle known fields
  16859. if (field == "event") {
  16860. msg.event = value;
  16861. } else if (field == "data") {
  16862. // Multiple data lines are concatenated with newlines
  16863. if (!msg.data.empty()) { msg.data += "\n"; }
  16864. msg.data += value;
  16865. } else if (field == "id") {
  16866. // Empty id is valid (clears the last event ID)
  16867. msg.id = value;
  16868. } else if (field == "retry") {
  16869. // Parse retry interval in milliseconds
  16870. {
  16871. int v = 0;
  16872. auto res =
  16873. detail::from_chars(value.data(), value.data() + value.size(), v);
  16874. if (res.ec == std::errc{}) { retry_ms = v; }
  16875. }
  16876. }
  16877. // Unknown fields are ignored per SSE spec
  16878. return false;
  16879. }
  16880. };
  16881. // Test: Single-line data
  16882. TEST_F(SSEParsingTest, SingleLineData) {
  16883. sse::SSEMessage msg;
  16884. int retry_ms = 3000;
  16885. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16886. EXPECT_EQ(msg.data, "hello");
  16887. EXPECT_EQ(msg.event, "message");
  16888. // Blank line ends event
  16889. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16890. }
  16891. // Test: Multi-line data
  16892. TEST_F(SSEParsingTest, MultiLineData) {
  16893. sse::SSEMessage msg;
  16894. int retry_ms = 3000;
  16895. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16896. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16897. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16898. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16899. }
  16900. // Test: Custom event types
  16901. TEST_F(SSEParsingTest, CustomEventType) {
  16902. sse::SSEMessage msg;
  16903. int retry_ms = 3000;
  16904. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16905. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16906. EXPECT_EQ(msg.event, "update");
  16907. EXPECT_EQ(msg.data, "payload");
  16908. }
  16909. // Test: Event ID handling
  16910. TEST_F(SSEParsingTest, EventIdHandling) {
  16911. sse::SSEMessage msg;
  16912. int retry_ms = 3000;
  16913. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16914. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16915. EXPECT_EQ(msg.id, "12345");
  16916. }
  16917. // Test: Empty event ID (clears last event ID)
  16918. TEST_F(SSEParsingTest, EmptyEventId) {
  16919. sse::SSEMessage msg;
  16920. msg.id = "previous";
  16921. int retry_ms = 3000;
  16922. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16923. EXPECT_EQ(msg.id, "");
  16924. }
  16925. // Test: Retry field parsing
  16926. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16927. sse::SSEMessage msg;
  16928. int retry_ms = 3000;
  16929. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16930. EXPECT_EQ(retry_ms, 5000);
  16931. }
  16932. // Test: Invalid retry value
  16933. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16934. sse::SSEMessage msg;
  16935. int retry_ms = 3000;
  16936. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16937. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16938. }
  16939. // Test: Comments (lines starting with :)
  16940. TEST_F(SSEParsingTest, CommentsIgnored) {
  16941. sse::SSEMessage msg;
  16942. int retry_ms = 3000;
  16943. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16944. EXPECT_EQ(msg.data, "");
  16945. EXPECT_EQ(msg.event, "message");
  16946. }
  16947. // Test: Colon in value
  16948. TEST_F(SSEParsingTest, ColonInValue) {
  16949. sse::SSEMessage msg;
  16950. int retry_ms = 3000;
  16951. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16952. EXPECT_EQ(msg.data, "hello:world:test");
  16953. }
  16954. // Test: Line with no colon (field name only)
  16955. TEST_F(SSEParsingTest, FieldNameOnly) {
  16956. sse::SSEMessage msg;
  16957. int retry_ms = 3000;
  16958. // According to SSE spec, this is treated as field name with empty value
  16959. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16960. // Since we don't recognize "data" without colon, data should be empty
  16961. EXPECT_EQ(msg.data, "");
  16962. }
  16963. // Test: Trailing \r handling
  16964. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16965. sse::SSEMessage msg;
  16966. int retry_ms = 3000;
  16967. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16968. EXPECT_EQ(msg.data, "hello");
  16969. }
  16970. // Test: Unknown fields ignored
  16971. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16972. sse::SSEMessage msg;
  16973. int retry_ms = 3000;
  16974. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16975. EXPECT_EQ(msg.data, "");
  16976. EXPECT_EQ(msg.event, "message");
  16977. }
  16978. // Test: Space after colon is optional
  16979. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16980. sse::SSEMessage msg1, msg2;
  16981. int retry_ms = 3000;
  16982. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16983. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16984. EXPECT_EQ(msg1.data, "hello");
  16985. EXPECT_EQ(msg2.data, "hello");
  16986. }
  16987. // Test: SSEMessage clear
  16988. TEST_F(SSEParsingTest, MessageClear) {
  16989. sse::SSEMessage msg;
  16990. msg.event = "custom";
  16991. msg.data = "some data";
  16992. msg.id = "123";
  16993. msg.clear();
  16994. EXPECT_EQ(msg.event, "message");
  16995. EXPECT_EQ(msg.data, "");
  16996. EXPECT_EQ(msg.id, "");
  16997. }
  16998. // Test: Complete event parsing
  16999. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17000. sse::SSEMessage msg;
  17001. int retry_ms = 3000;
  17002. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17003. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17004. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17005. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17006. // Blank line ends event
  17007. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17008. EXPECT_EQ(msg.event, "notification");
  17009. EXPECT_EQ(msg.id, "evt-42");
  17010. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17011. EXPECT_EQ(retry_ms, 1000);
  17012. }
  17013. //==============================================================================
  17014. // Integration Tests with Server
  17015. //==============================================================================
  17016. class SSEIntegrationTest : public ::testing::Test {
  17017. protected:
  17018. void SetUp() override {
  17019. stop_server_.store(false);
  17020. events_.clear();
  17021. server_ = httplib::detail::make_unique<Server>();
  17022. setup_server();
  17023. start_server();
  17024. }
  17025. void TearDown() override {
  17026. stop_server_.store(true);
  17027. event_cv_.notify_all();
  17028. server_->stop();
  17029. if (server_thread_.joinable()) { server_thread_.join(); }
  17030. }
  17031. void setup_server() {
  17032. // Simple SSE endpoint
  17033. server_->Get("/events", [this](const Request &req, Response &res) {
  17034. auto last_id = req.get_header_value("Last-Event-ID");
  17035. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17036. res.set_chunked_content_provider(
  17037. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17038. std::unique_lock<std::mutex> lock(event_mutex_);
  17039. if (event_cv_.wait_for(
  17040. lock, std::chrono::milliseconds(200), [this] {
  17041. return !events_.empty() || stop_server_.load();
  17042. })) {
  17043. if (stop_server_.load()) { return false; }
  17044. if (!events_.empty()) {
  17045. std::string event = events_.front();
  17046. events_.erase(events_.begin());
  17047. sink.write(event.data(), event.size());
  17048. return true;
  17049. }
  17050. }
  17051. return !stop_server_.load();
  17052. });
  17053. });
  17054. // Endpoint that returns error
  17055. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17056. res.status = 500;
  17057. res.set_content("Internal Server Error", "text/plain");
  17058. });
  17059. // Endpoint for custom event types
  17060. server_->Get("/custom-events", [](const Request &, Response &res) {
  17061. res.set_chunked_content_provider(
  17062. "text/event-stream", [](size_t offset, DataSink &sink) {
  17063. if (offset == 0) {
  17064. std::string event = "event: update\ndata: updated\n\n"
  17065. "event: delete\ndata: deleted\n\n";
  17066. sink.write(event.data(), event.size());
  17067. }
  17068. return false; // End stream after sending
  17069. });
  17070. });
  17071. }
  17072. void start_server() {
  17073. port_ = server_->bind_to_any_port(HOST);
  17074. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17075. // Wait for server to start
  17076. while (!server_->is_running()) {
  17077. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17078. }
  17079. }
  17080. int get_port() const { return port_; }
  17081. void send_event(const std::string &event) {
  17082. std::lock_guard<std::mutex> lock(event_mutex_);
  17083. events_.push_back(event);
  17084. event_cv_.notify_all();
  17085. }
  17086. std::unique_ptr<Server> server_;
  17087. std::thread server_thread_;
  17088. std::mutex event_mutex_;
  17089. std::condition_variable event_cv_;
  17090. std::vector<std::string> events_;
  17091. std::atomic<bool> stop_server_{false};
  17092. std::string last_received_event_id_;
  17093. int port_ = 0;
  17094. };
  17095. // Test: Successful connection and on_open callback
  17096. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17097. // Add a simple endpoint that sends one event and closes
  17098. server_->Get("/simple-event", [](const Request &, Response &res) {
  17099. res.set_chunked_content_provider(
  17100. "text/event-stream", [](size_t offset, DataSink &sink) {
  17101. if (offset == 0) {
  17102. std::string event = "data: hello\n\n";
  17103. sink.write(event.data(), event.size());
  17104. }
  17105. return false; // Close stream after sending
  17106. });
  17107. });
  17108. Client client("localhost", get_port());
  17109. sse::SSEClient sse(client, "/simple-event");
  17110. std::atomic<bool> open_called{false};
  17111. std::atomic<bool> message_received{false};
  17112. sse.on_open([&open_called]() { open_called.store(true); });
  17113. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17114. if (msg.data == "hello") { message_received.store(true); }
  17115. });
  17116. sse.set_reconnect_interval(100);
  17117. sse.set_max_reconnect_attempts(1);
  17118. // Start async
  17119. sse.start_async();
  17120. // Wait for message to be processed
  17121. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17122. sse.stop();
  17123. EXPECT_TRUE(open_called.load());
  17124. EXPECT_TRUE(message_received.load());
  17125. }
  17126. // Test: on_message callback
  17127. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17128. // Endpoint that sends multiple events then closes
  17129. server_->Get("/multi-event", [](const Request &, Response &res) {
  17130. res.set_chunked_content_provider(
  17131. "text/event-stream", [](size_t offset, DataSink &sink) {
  17132. if (offset == 0) {
  17133. std::string events = "data: message1\n\ndata: message2\n\n";
  17134. sink.write(events.data(), events.size());
  17135. }
  17136. return false;
  17137. });
  17138. });
  17139. Client client("localhost", get_port());
  17140. sse::SSEClient sse(client, "/multi-event");
  17141. std::vector<std::string> received_messages;
  17142. std::mutex messages_mutex;
  17143. sse.on_message([&](const sse::SSEMessage &msg) {
  17144. std::lock_guard<std::mutex> lock(messages_mutex);
  17145. received_messages.push_back(msg.data);
  17146. });
  17147. sse.set_reconnect_interval(100);
  17148. sse.set_max_reconnect_attempts(1);
  17149. sse.start_async();
  17150. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17151. sse.stop();
  17152. std::lock_guard<std::mutex> lock(messages_mutex);
  17153. EXPECT_GE(received_messages.size(), 2u);
  17154. if (received_messages.size() >= 2) {
  17155. EXPECT_EQ(received_messages[0], "message1");
  17156. EXPECT_EQ(received_messages[1], "message2");
  17157. }
  17158. }
  17159. // Test: on_event for specific types
  17160. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17161. Client client("localhost", get_port());
  17162. sse::SSEClient sse(client, "/custom-events");
  17163. std::atomic<bool> update_received{false};
  17164. std::atomic<bool> delete_received{false};
  17165. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17166. if (msg.data == "updated") { update_received.store(true); }
  17167. });
  17168. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17169. if (msg.data == "deleted") { delete_received.store(true); }
  17170. });
  17171. sse.set_max_reconnect_attempts(1);
  17172. sse.start_async();
  17173. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17174. sse.stop();
  17175. EXPECT_TRUE(update_received.load());
  17176. EXPECT_TRUE(delete_received.load());
  17177. }
  17178. // Test: on_error callback on connection failure
  17179. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17180. // Connect to a non-existent port
  17181. Client client("localhost", 59999);
  17182. sse::SSEClient sse(client, "/events");
  17183. std::atomic<bool> error_called{false};
  17184. Error received_error = Error::Success;
  17185. sse.on_error([&](Error err) {
  17186. error_called.store(true);
  17187. received_error = err;
  17188. });
  17189. sse.set_reconnect_interval(50);
  17190. sse.set_max_reconnect_attempts(1);
  17191. sse.start_async();
  17192. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17193. sse.stop();
  17194. EXPECT_TRUE(error_called.load());
  17195. EXPECT_NE(received_error, Error::Success);
  17196. }
  17197. // Test: Last-Event-ID header sent on reconnect
  17198. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17199. // Endpoint that sends event with ID
  17200. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17201. res.set_chunked_content_provider(
  17202. "text/event-stream", [](size_t offset, DataSink &sink) {
  17203. if (offset == 0) {
  17204. std::string event = "id: evt-123\ndata: test\n\n";
  17205. sink.write(event.data(), event.size());
  17206. }
  17207. return false;
  17208. });
  17209. });
  17210. Client client("localhost", get_port());
  17211. sse::SSEClient sse(client, "/event-with-id");
  17212. std::atomic<bool> id_received{false};
  17213. sse.on_message([&](const sse::SSEMessage &msg) {
  17214. if (!msg.id.empty()) { id_received.store(true); }
  17215. });
  17216. sse.set_reconnect_interval(100);
  17217. sse.set_max_reconnect_attempts(1);
  17218. sse.start_async();
  17219. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17220. sse.stop();
  17221. EXPECT_TRUE(id_received.load());
  17222. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17223. }
  17224. // Test: Manual stop
  17225. TEST_F(SSEIntegrationTest, ManualStop) {
  17226. // Endpoint that sends one event and stays open briefly
  17227. std::atomic<bool> handler_running{true};
  17228. server_->Get("/stay-open", [&handler_running](const Request &,
  17229. Response &res) {
  17230. res.set_chunked_content_provider(
  17231. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17232. if (offset == 0) {
  17233. std::string event = "data: connected\n\n";
  17234. sink.write(event.data(), event.size());
  17235. }
  17236. // Keep connection open while handler_running is true
  17237. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17238. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17239. }
  17240. return false;
  17241. });
  17242. });
  17243. Client client("localhost", get_port());
  17244. sse::SSEClient sse(client, "/stay-open");
  17245. std::atomic<bool> connected{false};
  17246. sse.on_open([&connected]() { connected.store(true); });
  17247. sse.set_reconnect_interval(100);
  17248. sse.set_max_reconnect_attempts(1);
  17249. sse.start_async();
  17250. // Wait for connection to establish
  17251. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17252. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17253. }
  17254. EXPECT_TRUE(connected.load());
  17255. EXPECT_TRUE(sse.is_connected());
  17256. // Signal handler to stop
  17257. handler_running.store(false);
  17258. // Stop SSE client
  17259. sse.stop();
  17260. EXPECT_FALSE(sse.is_connected());
  17261. }
  17262. // Test: SSEClient with custom headers
  17263. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17264. // Setup a server endpoint that checks for custom header
  17265. std::atomic<bool> header_received{false};
  17266. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17267. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17268. header_received.store(true);
  17269. }
  17270. res.set_chunked_content_provider("text/event-stream",
  17271. [](size_t, DataSink &) { return false; });
  17272. });
  17273. Client client("localhost", get_port());
  17274. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17275. sse::SSEClient sse(client, "/header-check", headers);
  17276. sse.set_max_reconnect_attempts(1);
  17277. sse.start_async();
  17278. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17279. sse.stop();
  17280. EXPECT_TRUE(header_received.load());
  17281. }
  17282. // Test: Reconnect interval configuration
  17283. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17284. Client client("localhost", get_port());
  17285. sse::SSEClient sse(client, "/events");
  17286. auto &result = sse.set_reconnect_interval(500);
  17287. // Builder pattern should return reference to self
  17288. EXPECT_EQ(&result, &sse);
  17289. }
  17290. // Test: Max reconnect attempts
  17291. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17292. // Connect to non-existent port to force reconnects
  17293. Client client("localhost", 59998);
  17294. sse::SSEClient sse(client, "/events");
  17295. std::atomic<int> error_count{0};
  17296. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17297. sse.set_reconnect_interval(50);
  17298. sse.set_max_reconnect_attempts(2);
  17299. auto start = std::chrono::steady_clock::now();
  17300. sse.start(); // Blocking call
  17301. auto end = std::chrono::steady_clock::now();
  17302. // Should have stopped after 2 failed attempts
  17303. EXPECT_GE(error_count.load(), 2);
  17304. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17305. auto duration =
  17306. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17307. #ifdef _WIN32
  17308. // Windows is much slower for socket connection failures
  17309. EXPECT_LT(duration.count(), 7000);
  17310. #else
  17311. EXPECT_LT(duration.count(), 1000);
  17312. #endif
  17313. }
  17314. // Test: Multi-line data in integration
  17315. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17316. // Endpoint with multi-line data
  17317. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17318. res.set_chunked_content_provider(
  17319. "text/event-stream", [](size_t offset, DataSink &sink) {
  17320. if (offset == 0) {
  17321. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17322. sink.write(event.data(), event.size());
  17323. }
  17324. return false;
  17325. });
  17326. });
  17327. Client client("localhost", get_port());
  17328. sse::SSEClient sse(client, "/multiline-data");
  17329. std::string received_data;
  17330. std::mutex data_mutex;
  17331. sse.on_message([&](const sse::SSEMessage &msg) {
  17332. std::lock_guard<std::mutex> lock(data_mutex);
  17333. received_data = msg.data;
  17334. });
  17335. sse.set_reconnect_interval(100);
  17336. sse.set_max_reconnect_attempts(1);
  17337. sse.start_async();
  17338. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17339. sse.stop();
  17340. std::lock_guard<std::mutex> lock(data_mutex);
  17341. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17342. }
  17343. // Test: Auto-reconnect after server disconnection
  17344. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17345. std::atomic<int> connection_count{0};
  17346. std::atomic<int> message_count{0};
  17347. // Endpoint that sends one event and closes, forcing reconnect
  17348. server_->Get("/reconnect-test",
  17349. [&connection_count](const Request &, Response &res) {
  17350. connection_count.fetch_add(1);
  17351. res.set_chunked_content_provider(
  17352. "text/event-stream", [](size_t offset, DataSink &sink) {
  17353. if (offset == 0) {
  17354. std::string event = "data: hello\n\n";
  17355. sink.write(event.data(), event.size());
  17356. }
  17357. return false; // Close connection after sending
  17358. });
  17359. });
  17360. Client client("localhost", get_port());
  17361. sse::SSEClient sse(client, "/reconnect-test");
  17362. sse.on_message([&message_count](const sse::SSEMessage &) {
  17363. message_count.fetch_add(1);
  17364. });
  17365. sse.set_reconnect_interval(100);
  17366. sse.set_max_reconnect_attempts(3);
  17367. sse.start_async();
  17368. // Wait long enough for multiple reconnects
  17369. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17370. sse.stop();
  17371. // Should have connected multiple times (initial + reconnects)
  17372. EXPECT_GE(connection_count.load(), 2);
  17373. // Should have received messages from multiple connections
  17374. EXPECT_GE(message_count.load(), 2);
  17375. }
  17376. // Test: Last-Event-ID sent on reconnect
  17377. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17378. std::atomic<int> connection_count{0};
  17379. std::vector<std::string> received_last_event_ids;
  17380. std::mutex id_mutex;
  17381. // Endpoint that checks Last-Event-ID header and sends event with ID
  17382. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17383. int conn = connection_count.fetch_add(1);
  17384. // Capture the Last-Event-ID header from each connection
  17385. {
  17386. std::lock_guard<std::mutex> lock(id_mutex);
  17387. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17388. }
  17389. res.set_chunked_content_provider(
  17390. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17391. if (offset == 0) {
  17392. std::string event =
  17393. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17394. sink.write(event.data(), event.size());
  17395. }
  17396. return false;
  17397. });
  17398. });
  17399. Client client("localhost", get_port());
  17400. sse::SSEClient sse(client, "/reconnect-with-id");
  17401. sse.set_reconnect_interval(100);
  17402. sse.set_max_reconnect_attempts(3);
  17403. sse.start_async();
  17404. // Wait for at least 2 connections
  17405. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17406. sse.stop();
  17407. // Verify behavior
  17408. std::lock_guard<std::mutex> lock(id_mutex);
  17409. EXPECT_GE(received_last_event_ids.size(), 2u);
  17410. // First connection should have no Last-Event-ID
  17411. if (!received_last_event_ids.empty()) {
  17412. EXPECT_EQ(received_last_event_ids[0], "");
  17413. }
  17414. // Second connection should have Last-Event-ID from first connection
  17415. if (received_last_event_ids.size() >= 2) {
  17416. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17417. }
  17418. }
  17419. // Test: set_headers updates headers used on reconnect
  17420. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17421. std::vector<std::string> received_tokens;
  17422. std::mutex token_mutex;
  17423. // Endpoint that captures Authorization header
  17424. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17425. {
  17426. std::lock_guard<std::mutex> lock(token_mutex);
  17427. received_tokens.push_back(req.get_header_value("Authorization"));
  17428. }
  17429. res.set_chunked_content_provider(
  17430. "text/event-stream", [](size_t offset, DataSink &sink) {
  17431. if (offset == 0) {
  17432. std::string event = "data: hello\n\n";
  17433. sink.write(event.data(), event.size());
  17434. }
  17435. return false; // Close connection to trigger reconnect
  17436. });
  17437. });
  17438. Client client("localhost", get_port());
  17439. Headers headers = {{"Authorization", "Bearer old-token"}};
  17440. sse::SSEClient sse(client, "/auth-check", headers);
  17441. // Update headers on each successful connection
  17442. sse.on_open(
  17443. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17444. sse.set_reconnect_interval(100);
  17445. sse.set_max_reconnect_attempts(3);
  17446. sse.start_async();
  17447. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17448. sse.stop();
  17449. std::lock_guard<std::mutex> lock(token_mutex);
  17450. ASSERT_GE(received_tokens.size(), 2u);
  17451. // First connection uses original header
  17452. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17453. // Second connection uses updated header from set_headers
  17454. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17455. }
  17456. // Test: 401 allows reconnection (so on_error can refresh headers)
  17457. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17458. std::atomic<int> connection_count{0};
  17459. // Endpoint: returns 401 on first attempt, 200 on second
  17460. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17461. int conn = connection_count.fetch_add(1);
  17462. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17463. res.status = StatusCode::Unauthorized_401;
  17464. res.set_content("Unauthorized", "text/plain");
  17465. return;
  17466. }
  17467. res.set_chunked_content_provider(
  17468. "text/event-stream", [](size_t offset, DataSink &sink) {
  17469. if (offset == 0) {
  17470. std::string event = "data: authenticated\n\n";
  17471. sink.write(event.data(), event.size());
  17472. }
  17473. return false;
  17474. });
  17475. });
  17476. Client client("localhost", get_port());
  17477. Headers headers = {{"Authorization", "Bearer expired"}};
  17478. sse::SSEClient sse(client, "/auth-retry", headers);
  17479. std::atomic<bool> message_received{false};
  17480. // Refresh token on error
  17481. sse.on_error(
  17482. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17483. sse.on_message([&](const sse::SSEMessage &msg) {
  17484. if (msg.data == "authenticated") { message_received.store(true); }
  17485. });
  17486. sse.set_reconnect_interval(100);
  17487. sse.set_max_reconnect_attempts(3);
  17488. sse.start_async();
  17489. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17490. sse.stop();
  17491. // Should have reconnected after 401 and succeeded with new token
  17492. EXPECT_GE(connection_count.load(), 2);
  17493. EXPECT_TRUE(message_received.load());
  17494. }
  17495. TEST(Issue2318Test, EmptyHostString) {
  17496. {
  17497. httplib::Client cli_empty("", PORT);
  17498. auto res = cli_empty.Get("/");
  17499. ASSERT_FALSE(res);
  17500. EXPECT_EQ(httplib::Error::Connection, res.error());
  17501. }
  17502. {
  17503. httplib::Client cli(" ", PORT);
  17504. auto res = cli.Get("/");
  17505. ASSERT_FALSE(res);
  17506. EXPECT_EQ(httplib::Error::Connection, res.error());
  17507. }
  17508. }
  17509. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17510. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17511. Server svr;
  17512. // Set a small payload limit (1KB)
  17513. svr.set_payload_max_length(1024);
  17514. svr.Post("/test", [&](const Request &req, Response &res) {
  17515. res.set_content("Body size: " + std::to_string(req.body.size()),
  17516. "text/plain");
  17517. });
  17518. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17519. auto se = detail::scope_exit([&] {
  17520. svr.stop();
  17521. listen_thread.join();
  17522. });
  17523. svr.wait_until_ready();
  17524. // Create data that compresses well but exceeds limit when decompressed
  17525. // 8KB of repeated null bytes compresses to a very small size
  17526. std::string original_data(8 * 1024, '\0');
  17527. // Compress the data using gzip
  17528. std::string compressed_data;
  17529. detail::gzip_compressor compressor;
  17530. compressor.compress(original_data.data(), original_data.size(), true,
  17531. [&](const char *data, size_t size) {
  17532. compressed_data.append(data, size);
  17533. return true;
  17534. });
  17535. // Verify compression worked (compressed should be much smaller)
  17536. ASSERT_LT(compressed_data.size(), original_data.size());
  17537. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17538. // Send compressed data with Content-Encoding: gzip
  17539. Client cli(HOST, PORT);
  17540. Headers headers = {{"Content-Encoding", "gzip"}};
  17541. auto res =
  17542. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17543. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17545. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17546. }
  17547. #endif
  17548. // ============================================================================
  17549. // OpenSSL-Specific Tests
  17550. // ============================================================================
  17551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17552. X509 *readCertificate(const std::string &strFileName) {
  17553. std::ifstream inStream(strFileName);
  17554. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17555. std::istreambuf_iterator<char>());
  17556. if (strCertPEM.empty()) return (nullptr);
  17557. BIO *pbCert = BIO_new(BIO_s_mem());
  17558. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17559. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17560. BIO_free(pbCert);
  17561. return (pCert);
  17562. }
  17563. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17564. std::ifstream inStream(strFileName);
  17565. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17566. std::istreambuf_iterator<char>());
  17567. if (strPrivateKeyPEM.empty()) return (nullptr);
  17568. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17569. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17570. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17571. BIO_free(pbPrivKey);
  17572. return (pPrivateKey);
  17573. }
  17574. TEST(BindServerTest, UpdateCerts) {
  17575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17576. int port = svr.bind_to_any_port("0.0.0.0");
  17577. ASSERT_TRUE(svr.is_valid());
  17578. ASSERT_TRUE(port > 0);
  17579. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17580. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17581. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17582. ASSERT_TRUE(cert != nullptr);
  17583. ASSERT_TRUE(ca_cert != nullptr);
  17584. ASSERT_TRUE(key != nullptr);
  17585. X509_STORE *cert_store = X509_STORE_new();
  17586. X509_STORE_add_cert(cert_store, ca_cert);
  17587. // svr.update_certs(cert, key, cert_store); // deprecated
  17588. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17589. CLIENT_CA_CERT_FILE);
  17590. ASSERT_TRUE(svr.is_valid());
  17591. svr.stop();
  17592. X509_STORE_free(cert_store);
  17593. X509_free(cert);
  17594. X509_free(ca_cert);
  17595. EVP_PKEY_free(key);
  17596. }
  17597. // Test that update_certs() updates client CA list correctly
  17598. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17599. // Start with file-based constructor
  17600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17601. ASSERT_TRUE(svr.is_valid());
  17602. // Initially no client CA list should be set
  17603. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17604. ASSERT_TRUE(ssl_ctx != nullptr);
  17605. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17606. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17607. EXPECT_EQ(0, count_before);
  17608. // Now update with client CA (PEM string)
  17609. std::string cert_pem, key_pem, ca_pem;
  17610. read_file(SERVER_CERT_FILE, cert_pem);
  17611. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17612. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17613. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17614. ASSERT_TRUE(svr.is_valid());
  17615. // Now client CA list should be set
  17616. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17617. ASSERT_TRUE(ca_list_after != nullptr);
  17618. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17619. }
  17620. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17621. // Test that the file-path SSLServer constructor properly sets the client CA
  17622. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17624. ASSERT_TRUE(svr.is_valid());
  17625. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17626. ASSERT_TRUE(ssl_ctx != nullptr);
  17627. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17628. ASSERT_TRUE(ca_list != nullptr);
  17629. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17630. }
  17631. #endif
  17632. // ============================================================================
  17633. // MbedTLS-Specific Tests
  17634. // ============================================================================
  17635. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17636. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17637. using namespace httplib::tls;
  17638. // Track if callback was invoked
  17639. bool callback_invoked = false;
  17640. // The callback receives void* ctx which is actually MbedTlsContext*
  17641. // We can access the mbedtls_ssl_config via the context
  17642. auto setup_callback = [&callback_invoked](void *ctx) {
  17643. callback_invoked = true;
  17644. // Cast to MbedTlsContext* to access the ssl config
  17645. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17646. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17647. // Use static variables to hold certificate data (simplified for test)
  17648. static mbedtls_x509_crt own_cert;
  17649. static mbedtls_pk_context own_key;
  17650. static mbedtls_x509_crt ca_chain;
  17651. static bool initialized = false;
  17652. if (!initialized) {
  17653. mbedtls_x509_crt_init(&own_cert);
  17654. mbedtls_pk_init(&own_key);
  17655. mbedtls_x509_crt_init(&ca_chain);
  17656. // Load server certificate
  17657. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17658. return false;
  17659. }
  17660. // Load server private key.
  17661. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17662. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17663. #if MBEDTLS_VERSION_MAJOR == 3
  17664. ,
  17665. mbedtls_ctr_drbg_random, nullptr
  17666. #endif
  17667. ) != 0) {
  17668. return false;
  17669. }
  17670. // Load CA chain for client verification
  17671. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17672. return false;
  17673. }
  17674. initialized = true;
  17675. }
  17676. // Configure the SSL config
  17677. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17678. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17679. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17680. // Set minimum TLS version using mbedTLS native API
  17681. #if MBEDTLS_VERSION_MAJOR >= 3
  17682. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17683. #else
  17684. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17685. MBEDTLS_SSL_MINOR_VERSION_3);
  17686. #endif
  17687. return true;
  17688. };
  17689. SSLServer svr(setup_callback);
  17690. ASSERT_TRUE(svr.is_valid());
  17691. ASSERT_TRUE(callback_invoked);
  17692. svr.Get("/test", [&](const Request &req, Response &res) {
  17693. res.set_content("test", "text/plain");
  17694. auto cert = req.peer_cert();
  17695. ASSERT_TRUE(static_cast<bool>(cert));
  17696. auto common_name = cert.subject_cn();
  17697. EXPECT_EQ("Common Name", common_name);
  17698. });
  17699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17700. auto se = detail::scope_exit([&] {
  17701. svr.stop();
  17702. t.join();
  17703. ASSERT_FALSE(svr.is_running());
  17704. });
  17705. svr.wait_until_ready();
  17706. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17707. cli.enable_server_certificate_verification(false);
  17708. cli.set_connection_timeout(30);
  17709. auto res = cli.Get("/test");
  17710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17711. ASSERT_EQ(StatusCode::OK_200, res->status);
  17712. }
  17713. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17714. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17715. // keep-alive SSL session, which reads through that config in
  17716. // mbedtls_ssl_close_notify.
  17717. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17719. ASSERT_TRUE(svr.is_valid());
  17720. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17721. res.set_content("test", "text/plain");
  17722. });
  17723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17724. auto se = detail::scope_exit([&] {
  17725. svr.stop();
  17726. t.join();
  17727. ASSERT_FALSE(svr.is_running());
  17728. });
  17729. svr.wait_until_ready();
  17730. {
  17731. SSLClient cli(HOST, PORT);
  17732. cli.enable_server_certificate_verification(false);
  17733. cli.set_keep_alive(true);
  17734. auto res = cli.Get("/test");
  17735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17736. ASSERT_EQ(StatusCode::OK_200, res->status);
  17737. // cli is destructed here with the keep-alive SSL session still open.
  17738. }
  17739. }
  17740. #endif
  17741. // WebSocket Tests
  17742. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17743. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17744. // defining the meaning of these bits has been negotiated.
  17745. auto make_frame = [](uint8_t first_byte) {
  17746. std::string frame;
  17747. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17748. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17749. frame += "Hello";
  17750. return frame;
  17751. };
  17752. // RSV1 set (0x40)
  17753. {
  17754. detail::BufferStream strm;
  17755. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17756. ws::Opcode opcode;
  17757. std::string payload;
  17758. bool fin;
  17759. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17760. false, 1024));
  17761. }
  17762. // RSV2 set (0x20)
  17763. {
  17764. detail::BufferStream strm;
  17765. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17766. ws::Opcode opcode;
  17767. std::string payload;
  17768. bool fin;
  17769. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17770. false, 1024));
  17771. }
  17772. // RSV3 set (0x10)
  17773. {
  17774. detail::BufferStream strm;
  17775. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17776. ws::Opcode opcode;
  17777. std::string payload;
  17778. bool fin;
  17779. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17780. false, 1024));
  17781. }
  17782. // No RSV bits set - should succeed
  17783. {
  17784. detail::BufferStream strm;
  17785. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17786. ws::Opcode opcode;
  17787. std::string payload;
  17788. bool fin;
  17789. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17790. false, 1024));
  17791. EXPECT_EQ(ws::Opcode::Text, opcode);
  17792. EXPECT_EQ("Hello", payload);
  17793. EXPECT_TRUE(fin);
  17794. }
  17795. }
  17796. TEST(WebSocketTest, ControlFrameValidation) {
  17797. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17798. // payload length <= 125.
  17799. // Ping with FIN=0 - must be rejected
  17800. {
  17801. detail::BufferStream strm;
  17802. std::string frame;
  17803. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17804. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17805. strm.write(frame.data(), frame.size());
  17806. ws::Opcode opcode;
  17807. std::string payload;
  17808. bool fin;
  17809. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17810. false, 1024));
  17811. }
  17812. // Close with FIN=0 - must be rejected
  17813. {
  17814. detail::BufferStream strm;
  17815. std::string frame;
  17816. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17817. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17818. strm.write(frame.data(), frame.size());
  17819. ws::Opcode opcode;
  17820. std::string payload;
  17821. bool fin;
  17822. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17823. false, 1024));
  17824. }
  17825. // Ping with payload_len=126 (extended length) - must be rejected
  17826. {
  17827. detail::BufferStream strm;
  17828. std::string frame;
  17829. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17830. frame += static_cast<char>(126); // payload_len=126 (>125)
  17831. frame += static_cast<char>(0x00); // extended length high byte
  17832. frame += static_cast<char>(126); // extended length low byte
  17833. frame += std::string(126, 'x');
  17834. strm.write(frame.data(), frame.size());
  17835. ws::Opcode opcode;
  17836. std::string payload;
  17837. bool fin;
  17838. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17839. false, 1024));
  17840. }
  17841. // Ping with FIN=1 and payload_len=125 - should succeed
  17842. {
  17843. detail::BufferStream strm;
  17844. std::string frame;
  17845. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17846. frame += static_cast<char>(125); // payload_len=125
  17847. frame += std::string(125, 'x');
  17848. strm.write(frame.data(), frame.size());
  17849. ws::Opcode opcode;
  17850. std::string payload;
  17851. bool fin;
  17852. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17853. false, 1024));
  17854. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17855. EXPECT_EQ(125u, payload.size());
  17856. EXPECT_TRUE(fin);
  17857. }
  17858. }
  17859. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17860. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17861. // length MUST be 0.
  17862. // MSB set - must be rejected
  17863. {
  17864. detail::BufferStream strm;
  17865. std::string frame;
  17866. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17867. frame += static_cast<char>(127); // 64-bit extended length
  17868. frame += static_cast<char>(0x80); // MSB set (invalid)
  17869. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17870. strm.write(frame.data(), frame.size());
  17871. ws::Opcode opcode;
  17872. std::string payload;
  17873. bool fin;
  17874. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17875. false, 1024));
  17876. }
  17877. // MSB clear - should pass length parsing (will be rejected by max_len,
  17878. // but that's a different check; use a small length to verify)
  17879. {
  17880. detail::BufferStream strm;
  17881. std::string frame;
  17882. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17883. frame += static_cast<char>(127); // 64-bit extended length
  17884. frame += std::string(7, '\0'); // high bytes = 0
  17885. frame += static_cast<char>(0x03); // length = 3
  17886. frame += "abc";
  17887. strm.write(frame.data(), frame.size());
  17888. ws::Opcode opcode;
  17889. std::string payload;
  17890. bool fin;
  17891. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17892. false, 1024));
  17893. EXPECT_EQ(ws::Opcode::Text, opcode);
  17894. EXPECT_EQ("abc", payload);
  17895. }
  17896. }
  17897. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17898. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17899. // Valid UTF-8
  17900. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17901. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17902. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17903. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17904. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17905. // Invalid UTF-8
  17906. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17907. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17908. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17909. EXPECT_FALSE(
  17910. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17911. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17912. }
  17913. TEST(WebSocketTest, ConnectAndDisconnect) {
  17914. Server svr;
  17915. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17916. std::string msg;
  17917. while (ws.read(msg)) {}
  17918. });
  17919. auto port = svr.bind_to_any_port(HOST);
  17920. std::thread t([&]() { svr.listen_after_bind(); });
  17921. svr.wait_until_ready();
  17922. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17923. auto res = client.connect();
  17924. ASSERT_TRUE(res);
  17925. EXPECT_EQ(Error::Success, res.error());
  17926. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17927. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17928. EXPECT_TRUE(client.is_open());
  17929. client.close();
  17930. EXPECT_FALSE(client.is_open());
  17931. svr.stop();
  17932. t.join();
  17933. }
  17934. TEST(WebSocketTest, ValidURL) {
  17935. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17936. EXPECT_TRUE(ws1.is_valid());
  17937. ws::WebSocketClient ws2("ws://example.com/path");
  17938. EXPECT_TRUE(ws2.is_valid());
  17939. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17940. EXPECT_TRUE(ws3.is_valid());
  17941. #ifdef CPPHTTPLIB_SSL_ENABLED
  17942. ws::WebSocketClient wss1("wss://example.com/path");
  17943. EXPECT_TRUE(wss1.is_valid());
  17944. ws::WebSocketClient wss2("wss://example.com:443/path");
  17945. EXPECT_TRUE(wss2.is_valid());
  17946. #endif
  17947. }
  17948. TEST(WebSocketTest, InvalidURL) {
  17949. // No scheme
  17950. ws::WebSocketClient ws1("localhost:8080/path");
  17951. EXPECT_FALSE(ws1.is_valid());
  17952. // No path
  17953. ws::WebSocketClient ws2("ws://localhost:8080");
  17954. EXPECT_FALSE(ws2.is_valid());
  17955. // Empty string
  17956. ws::WebSocketClient ws3("");
  17957. EXPECT_FALSE(ws3.is_valid());
  17958. // Missing host
  17959. ws::WebSocketClient ws4("ws://:8080/path");
  17960. EXPECT_FALSE(ws4.is_valid());
  17961. // Port number overflow — should not crash
  17962. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17963. EXPECT_FALSE(ws5.is_valid());
  17964. // Port out of range
  17965. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17966. EXPECT_FALSE(ws6.is_valid());
  17967. }
  17968. TEST(WebSocketTest, UnsupportedScheme) {
  17969. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17970. ws::WebSocketClient ws1("http://localhost:8080/path");
  17971. EXPECT_FALSE(ws1.is_valid());
  17972. ws::WebSocketClient ws2("https://localhost:8080/path");
  17973. EXPECT_FALSE(ws2.is_valid());
  17974. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17975. EXPECT_FALSE(ws3.is_valid());
  17976. #else
  17977. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17978. std::invalid_argument);
  17979. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17980. std::invalid_argument);
  17981. #endif
  17982. }
  17983. TEST(WebSocketTest, ConnectWhenInvalid) {
  17984. ws::WebSocketClient ws("not a valid url");
  17985. EXPECT_FALSE(ws.is_valid());
  17986. auto res = ws.connect();
  17987. EXPECT_FALSE(res);
  17988. EXPECT_EQ(Error::Connection, res.error());
  17989. EXPECT_EQ(-1, res.status());
  17990. }
  17991. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17992. // Grab a port that is free, then close it again so nothing listens there
  17993. Server svr;
  17994. auto port = svr.bind_to_any_port(HOST);
  17995. svr.stop();
  17996. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17997. auto res = client.connect();
  17998. ASSERT_FALSE(res);
  17999. EXPECT_EQ(Error::Connection, res.error());
  18000. EXPECT_EQ(-1, res.status());
  18001. }
  18002. TEST(WebSocketTest, DefaultPort) {
  18003. ws::WebSocketClient ws1("ws://example.com/path");
  18004. EXPECT_TRUE(ws1.is_valid());
  18005. // ws:// defaults to port 80 (verified by successful parse)
  18006. #ifdef CPPHTTPLIB_SSL_ENABLED
  18007. ws::WebSocketClient ws2("wss://example.com/path");
  18008. EXPECT_TRUE(ws2.is_valid());
  18009. // wss:// defaults to port 443 (verified by successful parse)
  18010. #endif
  18011. }
  18012. TEST(WebSocketTest, IPv6LiteralAddress) {
  18013. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18014. EXPECT_TRUE(ws1.is_valid());
  18015. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18016. EXPECT_TRUE(ws2.is_valid());
  18017. }
  18018. TEST(WebSocketTest, ComplexPath) {
  18019. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18020. EXPECT_TRUE(ws1.is_valid());
  18021. ws::WebSocketClient ws2("ws://localhost:8080/");
  18022. EXPECT_TRUE(ws2.is_valid());
  18023. }
  18024. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18025. Server svr;
  18026. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18027. std::string msg;
  18028. while (ws.read(msg)) {}
  18029. });
  18030. auto port = svr.bind_to_any_port(HOST);
  18031. std::thread t([&]() { svr.listen_after_bind(); });
  18032. svr.wait_until_ready();
  18033. auto another_host = "example.com";
  18034. auto wrong_ip = "192.0.2.1";
  18035. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18036. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18037. ASSERT_TRUE(client.connect());
  18038. EXPECT_TRUE(client.is_open());
  18039. client.close();
  18040. svr.stop();
  18041. t.join();
  18042. }
  18043. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18044. Server svr;
  18045. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18046. std::string msg;
  18047. while (ws.read(msg)) {}
  18048. });
  18049. auto port = svr.bind_to_any_port(HOST);
  18050. std::thread t([&]() { svr.listen_after_bind(); });
  18051. svr.wait_until_ready();
  18052. auto wrong_ip = "192.0.2.1";
  18053. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18054. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18055. client.set_connection_timeout(1);
  18056. client.set_read_timeout(1);
  18057. client.set_write_timeout(1);
  18058. EXPECT_FALSE(client.connect());
  18059. EXPECT_FALSE(client.is_open());
  18060. svr.stop();
  18061. t.join();
  18062. }
  18063. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18064. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18065. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18066. // (RFC 6761) is only a map key and the Host header value.
  18067. auto host = "target.invalid";
  18068. Server svr;
  18069. std::string received_host;
  18070. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18071. received_host = req.get_header_value("Host");
  18072. std::string msg;
  18073. while (ws.read(msg)) {}
  18074. });
  18075. auto port = svr.bind_to_any_port(HOST);
  18076. std::thread t([&]() { svr.listen_after_bind(); });
  18077. // ASSERT_* below returns from the test body, which would leave t joinable
  18078. // and make ~thread call std::terminate.
  18079. auto se = detail::scope_exit([&] {
  18080. svr.stop();
  18081. if (t.joinable()) { t.join(); }
  18082. });
  18083. svr.wait_until_ready();
  18084. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18085. std::to_string(port) + "/ws");
  18086. client.set_hostname_addr_map({{host, HOST}});
  18087. ASSERT_TRUE(client.connect());
  18088. EXPECT_TRUE(client.is_open());
  18089. client.close();
  18090. svr.stop();
  18091. t.join();
  18092. // The mapping only redirects the connection; the identity stays host_.
  18093. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18094. }
  18095. class WebSocketIntegrationTest : public ::testing::Test {
  18096. protected:
  18097. void SetUp() override {
  18098. server_ = httplib::detail::make_unique<Server>();
  18099. setup_server();
  18100. start_server();
  18101. }
  18102. void TearDown() override {
  18103. server_->stop();
  18104. if (server_thread_.joinable()) { server_thread_.join(); }
  18105. }
  18106. void setup_server() {
  18107. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18108. std::string msg;
  18109. ws::ReadResult ret;
  18110. while ((ret = ws.read(msg))) {
  18111. if (ret == ws::Binary) {
  18112. ws.send(msg.data(), msg.size());
  18113. } else {
  18114. ws.send(msg);
  18115. }
  18116. }
  18117. });
  18118. server_->WebSocket("/ws-echo-string",
  18119. [](const Request &, ws::WebSocket &ws) {
  18120. std::string msg;
  18121. while (ws.read(msg)) {
  18122. ws.send("echo: " + msg);
  18123. }
  18124. });
  18125. server_->WebSocket(
  18126. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18127. // Echo back request metadata
  18128. ws.send("path:" + req.path);
  18129. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18130. std::string msg;
  18131. while (ws.read(msg)) {}
  18132. });
  18133. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18134. std::string msg;
  18135. ws.read(msg); // wait for a message
  18136. ws.close();
  18137. });
  18138. server_->WebSocket("/ws-close-status",
  18139. [](const Request &, ws::WebSocket &ws) {
  18140. std::string msg;
  18141. ws.read(msg); // wait for a message
  18142. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18143. });
  18144. server_->WebSocket(
  18145. "/ws-subprotocol",
  18146. [](const Request &, ws::WebSocket &ws) {
  18147. std::string msg;
  18148. while (ws.read(msg)) {
  18149. ws.send(msg);
  18150. }
  18151. },
  18152. [](const std::vector<std::string> &protocols) -> std::string {
  18153. for (const auto &p : protocols) {
  18154. if (p == "graphql-ws") { return p; }
  18155. }
  18156. return "";
  18157. });
  18158. }
  18159. void start_server() {
  18160. port_ = server_->bind_to_any_port(HOST);
  18161. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18162. server_->wait_until_ready();
  18163. }
  18164. std::unique_ptr<Server> server_;
  18165. std::thread server_thread_;
  18166. int port_ = 0;
  18167. };
  18168. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18170. "/ws-echo");
  18171. ASSERT_TRUE(client.connect());
  18172. ASSERT_TRUE(client.is_open());
  18173. ASSERT_TRUE(client.send("Hello WebSocket"));
  18174. std::string msg;
  18175. EXPECT_EQ(ws::Text, client.read(msg));
  18176. EXPECT_EQ("Hello WebSocket", msg);
  18177. client.close();
  18178. }
  18179. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18181. "/ws-echo");
  18182. ASSERT_TRUE(client.connect());
  18183. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18184. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18185. std::string msg;
  18186. EXPECT_EQ(ws::Binary, client.read(msg));
  18187. EXPECT_EQ(binary_data, msg);
  18188. client.close();
  18189. }
  18190. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18192. "/ws-echo");
  18193. ASSERT_TRUE(client.connect());
  18194. for (int i = 0; i < 10; i++) {
  18195. auto text = "message " + std::to_string(i);
  18196. ASSERT_TRUE(client.send(text));
  18197. std::string msg;
  18198. ASSERT_TRUE(client.read(msg));
  18199. EXPECT_EQ(text, msg);
  18200. }
  18201. client.close();
  18202. }
  18203. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18205. "/ws-close");
  18206. ASSERT_TRUE(client.connect());
  18207. // Send a message to trigger the server to close
  18208. ASSERT_TRUE(client.send("trigger close"));
  18209. // The server will close, so read should return false
  18210. std::string msg;
  18211. EXPECT_FALSE(client.read(msg));
  18212. EXPECT_FALSE(client.is_open());
  18213. }
  18214. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18216. "/ws-echo");
  18217. ASSERT_TRUE(client.connect());
  18218. // 128KB message
  18219. std::string large_data(128 * 1024, 'X');
  18220. ASSERT_TRUE(client.send(large_data));
  18221. std::string msg;
  18222. ASSERT_TRUE(client.read(msg));
  18223. EXPECT_EQ(large_data, msg);
  18224. client.close();
  18225. }
  18226. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18228. "/ws-echo");
  18229. ASSERT_TRUE(client.connect());
  18230. const int num_threads = 4;
  18231. std::vector<std::thread> threads;
  18232. std::atomic<int> send_count{0};
  18233. for (int t = 0; t < num_threads; t++) {
  18234. threads.emplace_back([&client, &send_count, t]() {
  18235. for (int i = 0; i < 5; i++) {
  18236. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18237. if (client.send(text)) { send_count++; }
  18238. }
  18239. });
  18240. }
  18241. for (auto &th : threads) {
  18242. th.join();
  18243. }
  18244. int received = 0;
  18245. std::string msg;
  18246. while (received < send_count.load()) {
  18247. if (!client.read(msg)) { break; }
  18248. received++;
  18249. }
  18250. EXPECT_EQ(send_count.load(), received);
  18251. client.close();
  18252. }
  18253. TEST_F(WebSocketIntegrationTest, ReadString) {
  18254. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18255. "/ws-echo-string");
  18256. ASSERT_TRUE(client.connect());
  18257. ASSERT_TRUE(client.send("hello"));
  18258. std::string msg;
  18259. ASSERT_TRUE(client.read(msg));
  18260. EXPECT_EQ("echo: hello", msg);
  18261. ASSERT_TRUE(client.send("world"));
  18262. ASSERT_TRUE(client.read(msg));
  18263. EXPECT_EQ("echo: world", msg);
  18264. client.close();
  18265. }
  18266. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18267. Headers headers = {{"X-Test-Header", "test-value"}};
  18268. ws::WebSocketClient client(
  18269. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18270. ASSERT_TRUE(client.connect());
  18271. std::string msg;
  18272. ASSERT_TRUE(client.read(msg));
  18273. EXPECT_EQ("path:/ws-request-info", msg);
  18274. ASSERT_TRUE(client.read(msg));
  18275. EXPECT_EQ("header:test-value", msg);
  18276. client.close();
  18277. }
  18278. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18280. "/ws-echo");
  18281. client.set_read_timeout(1, 0); // 1 second
  18282. ASSERT_TRUE(client.connect());
  18283. // Don't send anything — server echo handler waits for a message,
  18284. // so read() should time out and return false.
  18285. std::string msg;
  18286. EXPECT_FALSE(client.read(msg));
  18287. }
  18288. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18289. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18290. "/ws-echo");
  18291. client.set_read_timeout(5, 0);
  18292. ASSERT_TRUE(client.connect());
  18293. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18294. // The server should reject it and close the connection.
  18295. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18296. client.send(oversized);
  18297. // The server's read() should have failed due to payload limit,
  18298. // so our read() should return false (connection closed).
  18299. std::string msg;
  18300. EXPECT_FALSE(client.read(msg));
  18301. }
  18302. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18303. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18304. "/ws-echo");
  18305. client.set_read_timeout(10, 0);
  18306. ASSERT_TRUE(client.connect());
  18307. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18308. // This should succeed.
  18309. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18310. ASSERT_TRUE(client.send(at_limit));
  18311. std::string msg;
  18312. ASSERT_TRUE(client.read(msg));
  18313. EXPECT_EQ(at_limit.size(), msg.size());
  18314. client.close();
  18315. }
  18316. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18317. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18318. "/nonexistent");
  18319. auto res = client.connect();
  18320. EXPECT_FALSE(res);
  18321. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18322. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18323. EXPECT_FALSE(client.is_open());
  18324. }
  18325. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18327. "/ws-echo");
  18328. ASSERT_TRUE(client.connect());
  18329. ASSERT_TRUE(client.send(""));
  18330. std::string msg;
  18331. EXPECT_EQ(ws::Text, client.read(msg));
  18332. EXPECT_EQ("", msg);
  18333. client.close();
  18334. }
  18335. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18337. "/ws-echo");
  18338. // First connection
  18339. ASSERT_TRUE(client.connect());
  18340. ASSERT_TRUE(client.send("first"));
  18341. std::string msg;
  18342. ASSERT_TRUE(client.read(msg));
  18343. EXPECT_EQ("first", msg);
  18344. client.close();
  18345. EXPECT_FALSE(client.is_open());
  18346. // Reconnect using the same client object
  18347. ASSERT_TRUE(client.connect());
  18348. ASSERT_TRUE(client.is_open());
  18349. ASSERT_TRUE(client.send("second"));
  18350. ASSERT_TRUE(client.read(msg));
  18351. EXPECT_EQ("second", msg);
  18352. client.close();
  18353. }
  18354. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18355. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18356. "/ws-close-status");
  18357. ASSERT_TRUE(client.connect());
  18358. // Trigger the server to close with GoingAway status
  18359. ASSERT_TRUE(client.send("trigger"));
  18360. // read() should return false after receiving the close frame
  18361. std::string msg;
  18362. EXPECT_FALSE(client.read(msg));
  18363. EXPECT_FALSE(client.is_open());
  18364. }
  18365. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18367. "/ws-echo");
  18368. ASSERT_TRUE(client.connect());
  18369. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18370. EXPECT_FALSE(client.is_open());
  18371. }
  18372. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18373. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18374. ws::WebSocketClient client(
  18375. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18376. ASSERT_TRUE(client.connect());
  18377. // Server should have selected graphql-ws
  18378. EXPECT_EQ("graphql-ws", client.subprotocol());
  18379. client.close();
  18380. }
  18381. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18382. Headers headers;
  18383. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18384. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18385. ws::WebSocketClient client(
  18386. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18387. ASSERT_TRUE(client.connect());
  18388. // The offer on the second field line counts too, so graphql-ws is selected
  18389. EXPECT_EQ("graphql-ws", client.subprotocol());
  18390. client.close();
  18391. }
  18392. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18393. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18394. ws::WebSocketClient client(
  18395. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18396. ASSERT_TRUE(client.connect());
  18397. // Server should not have selected any subprotocol
  18398. EXPECT_TRUE(client.subprotocol().empty());
  18399. client.close();
  18400. }
  18401. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18402. // Connect without requesting any subprotocol
  18403. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18404. "/ws-subprotocol");
  18405. ASSERT_TRUE(client.connect());
  18406. EXPECT_TRUE(client.subprotocol().empty());
  18407. client.close();
  18408. }
  18409. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18411. "/ws-echo");
  18412. client.set_tcp_nodelay(true);
  18413. client.set_connection_timeout(3, 0);
  18414. bool socket_options_called = false;
  18415. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18416. ASSERT_TRUE(client.connect());
  18417. ASSERT_TRUE(client.is_open());
  18418. EXPECT_TRUE(socket_options_called);
  18419. ASSERT_TRUE(client.send("hello"));
  18420. std::string msg;
  18421. auto result = client.read(msg);
  18422. EXPECT_EQ(result, ws::ReadResult::Text);
  18423. EXPECT_EQ(msg, "hello");
  18424. client.close();
  18425. }
  18426. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18428. "/ws-echo");
  18429. client.set_connection_timeout(std::chrono::seconds(3));
  18430. client.set_write_timeout(std::chrono::seconds(3));
  18431. // A sub-second remainder exercises the seconds/microseconds split.
  18432. client.set_read_timeout(std::chrono::milliseconds(1500));
  18433. ASSERT_TRUE(client.connect());
  18434. auto start = std::chrono::steady_clock::now();
  18435. std::string msg;
  18436. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18437. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18438. std::chrono::steady_clock::now() - start)
  18439. .count();
  18440. // Above 1s so that dropping the microseconds half of the split fails here,
  18441. // and well under the 300s default so that ignoring the setter fails too.
  18442. EXPECT_GE(elapsed, 1400);
  18443. EXPECT_LT(elapsed, 30000);
  18444. }
  18445. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18446. Server svr;
  18447. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18448. if (!req.has_header("Authorization")) {
  18449. res.status = StatusCode::Unauthorized_401;
  18450. res.set_content("Unauthorized", "text/plain");
  18451. return Server::HandlerResponse::Handled;
  18452. }
  18453. return Server::HandlerResponse::Unhandled;
  18454. });
  18455. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18456. std::string msg;
  18457. while (ws.read(msg)) {
  18458. ws.send(msg);
  18459. }
  18460. });
  18461. auto port = svr.bind_to_any_port("localhost");
  18462. std::thread t([&]() { svr.listen_after_bind(); });
  18463. svr.wait_until_ready();
  18464. // Without Authorization header - should be rejected before upgrade
  18465. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18466. EXPECT_FALSE(client1.connect());
  18467. // With Authorization header - should succeed
  18468. Headers headers = {{"Authorization", "Bearer token123"}};
  18469. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18470. headers);
  18471. ASSERT_TRUE(client2.connect());
  18472. ASSERT_TRUE(client2.send("hello"));
  18473. std::string msg;
  18474. ASSERT_TRUE(client2.read(msg));
  18475. EXPECT_EQ("hello", msg);
  18476. client2.close();
  18477. svr.stop();
  18478. t.join();
  18479. }
  18480. TEST(WebSocketTest, QueryStringInHandshake) {
  18481. Server svr;
  18482. std::mutex mtx;
  18483. std::string received_target;
  18484. std::string received_token;
  18485. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18486. {
  18487. std::lock_guard<std::mutex> lock(mtx);
  18488. received_target = req.target;
  18489. if (req.has_param("token")) {
  18490. received_token = req.get_param_value("token");
  18491. }
  18492. }
  18493. std::string msg;
  18494. while (ws.read(msg)) {
  18495. ws.send(msg);
  18496. }
  18497. });
  18498. auto port = svr.bind_to_any_port("localhost");
  18499. std::thread t([&]() { svr.listen_after_bind(); });
  18500. svr.wait_until_ready();
  18501. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18502. "/ws?token=ABC&session=123");
  18503. ASSERT_TRUE(client.connect());
  18504. // Round-trip ensures the handler has run and captured the request.
  18505. ASSERT_TRUE(client.send("hello"));
  18506. std::string msg;
  18507. ASSERT_TRUE(client.read(msg));
  18508. EXPECT_EQ("hello", msg);
  18509. client.close();
  18510. {
  18511. std::lock_guard<std::mutex> lock(mtx);
  18512. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18513. EXPECT_EQ("ABC", received_token);
  18514. }
  18515. svr.stop();
  18516. t.join();
  18517. }
  18518. // Run a handshake against a throwaway server and hand the request the server
  18519. // received back to the caller, so tests can assert on the headers the client
  18520. // actually put on the wire.
  18521. static void capture_websocket_handshake_request(
  18522. const Headers &client_headers,
  18523. std::function<void(const Request &, int port)> verify) {
  18524. Server svr;
  18525. std::mutex mtx;
  18526. Request received;
  18527. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18528. {
  18529. std::lock_guard<std::mutex> lock(mtx);
  18530. received = req;
  18531. }
  18532. std::string msg;
  18533. while (ws.read(msg)) {
  18534. ws.send(msg);
  18535. }
  18536. });
  18537. auto port = svr.bind_to_any_port("localhost");
  18538. std::thread t([&]() { svr.listen_after_bind(); });
  18539. auto se = detail::scope_exit([&] {
  18540. svr.stop();
  18541. t.join();
  18542. });
  18543. svr.wait_until_ready();
  18544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18545. client_headers);
  18546. ASSERT_TRUE(client.connect());
  18547. ASSERT_TRUE(client.send("hello"));
  18548. std::string msg;
  18549. ASSERT_TRUE(client.read(msg));
  18550. client.close();
  18551. {
  18552. std::lock_guard<std::mutex> lock(mtx);
  18553. verify(received, port);
  18554. }
  18555. }
  18556. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18557. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18558. // Non-default port must be present in the Host header. Default ports
  18559. // (80/443) are omitted; that logic is covered by
  18560. // MakeHostAndPortStringTest.
  18561. EXPECT_EQ("localhost:" + std::to_string(port),
  18562. req.get_header_value("Host"));
  18563. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18564. req.get_header_value("User-Agent"));
  18565. EXPECT_FALSE(req.has_header("Accept"));
  18566. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18567. EXPECT_FALSE(req.has_header("Content-Length"));
  18568. });
  18569. }
  18570. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18571. capture_websocket_handshake_request(
  18572. {{"Host", "example.com"},
  18573. {"User-Agent", "custom-agent"},
  18574. {"X-Custom", "value"}},
  18575. [](const Request &req, int) {
  18576. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18577. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18578. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18579. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18580. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18581. });
  18582. }
  18583. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18584. capture_websocket_handshake_request(
  18585. {{"Upgrade", "bogus"},
  18586. {"Connection", "close"},
  18587. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18588. {"Sec-WebSocket-Version", "8"}},
  18589. [](const Request &req, int) {
  18590. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18591. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18592. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18593. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18594. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18595. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18596. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18597. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18598. req.get_header_value("Sec-WebSocket-Key"));
  18599. });
  18600. }
  18601. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18602. // A header the client refuses to send must abort the handshake before any
  18603. // part of it reaches the wire; a lone request line would otherwise sit in
  18604. // the peer's buffer as a truncated request.
  18605. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18606. ASSERT_NE(INVALID_SOCKET, srv);
  18607. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18608. sockaddr_in addr{};
  18609. addr.sin_family = AF_INET;
  18610. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18611. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18612. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18613. ASSERT_EQ(0, ::listen(srv, 1));
  18614. sockaddr_in bound{};
  18615. socklen_t bound_len = sizeof(bound);
  18616. ASSERT_EQ(
  18617. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18618. auto port = ntohs(bound.sin_port);
  18619. ssize_t received = -1;
  18620. std::thread t([&] {
  18621. // Bound every blocking call so a regression fails the test with a bad
  18622. // value instead of hanging the suite.
  18623. fd_set rfds;
  18624. FD_ZERO(&rfds);
  18625. FD_SET(srv, &rfds);
  18626. timeval tv{5, 0};
  18627. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18628. 0) {
  18629. return;
  18630. }
  18631. sockaddr_in cli_addr{};
  18632. socklen_t cli_len = sizeof(cli_addr);
  18633. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18634. if (cli == INVALID_SOCKET) { return; }
  18635. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18636. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18637. char buf[4096];
  18638. received = ::recv(cli, buf, sizeof(buf), 0);
  18639. });
  18640. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18641. // connect() has already shut the socket down by the time it returns false,
  18642. // so the peer sees EOF without waiting for the client to be destroyed.
  18643. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18644. {{"X-Bad", "a\r\nInjected: 1"}});
  18645. EXPECT_FALSE(client.connect());
  18646. t.join();
  18647. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18648. EXPECT_EQ(0, received);
  18649. }
  18650. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18651. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18652. // contains "upgrade" as a substring is a different token and must not
  18653. // start a WebSocket handshake.
  18654. auto make_request = [](const std::vector<std::string> &connection_values) {
  18655. Request req;
  18656. req.method = "GET";
  18657. req.headers.emplace("Upgrade", "websocket");
  18658. for (const auto &value : connection_values) {
  18659. req.headers.emplace("Connection", value);
  18660. }
  18661. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18662. req.headers.emplace("Sec-WebSocket-Version", "13");
  18663. return req;
  18664. };
  18665. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18666. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18667. EXPECT_TRUE(
  18668. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18669. EXPECT_TRUE(
  18670. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18671. EXPECT_TRUE(
  18672. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18673. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18674. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18675. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18676. EXPECT_FALSE(
  18677. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18678. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18679. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18680. }
  18681. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18682. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18683. // asks recipients to match each protocol-name case-insensitively, and RFC
  18684. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18685. // client naming websocket alongside another protocol, or on a second field
  18686. // line, is offering websocket; a value that merely contains "websocket" as a
  18687. // substring is a different protocol name and is not.
  18688. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18689. Request req;
  18690. req.method = "GET";
  18691. for (const auto &value : upgrade_values) {
  18692. req.headers.emplace("Upgrade", value);
  18693. }
  18694. req.headers.emplace("Connection", "Upgrade");
  18695. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18696. req.headers.emplace("Sec-WebSocket-Version", "13");
  18697. return req;
  18698. };
  18699. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18700. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18701. EXPECT_TRUE(
  18702. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18703. EXPECT_TRUE(
  18704. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18705. EXPECT_TRUE(
  18706. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18707. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18708. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18709. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18710. EXPECT_FALSE(
  18711. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18712. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18713. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18714. }
  18715. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18716. Server svr;
  18717. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18718. auto port = svr.bind_to_any_port("localhost");
  18719. std::thread t([&]() { svr.listen_after_bind(); });
  18720. auto se = detail::scope_exit([&] {
  18721. svr.stop();
  18722. t.join();
  18723. });
  18724. svr.wait_until_ready();
  18725. Headers headers = {{"Upgrade", "websocket"},
  18726. {"Connection", "notupgrade"},
  18727. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18728. {"Sec-WebSocket-Version", "13"}};
  18729. Client cli("localhost", port);
  18730. auto res = cli.Get("/ws", headers);
  18731. // The route exists only as a WebSocket route, so a request that fails the
  18732. // handshake check falls through to ordinary routing.
  18733. ASSERT_TRUE(res);
  18734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18735. }
  18736. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18737. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18738. // Connection value is the only thing left for the client to reject.
  18739. Server svr;
  18740. svr.Get("/ws", [](const Request &req, Response &res) {
  18741. res.status = StatusCode::SwitchingProtocol_101;
  18742. res.set_header("Upgrade", "websocket");
  18743. res.set_header("Connection", "notupgrade");
  18744. res.set_header("Sec-WebSocket-Accept",
  18745. detail::websocket_accept_key(
  18746. req.get_header_value("Sec-WebSocket-Key")));
  18747. });
  18748. auto port = svr.bind_to_any_port("localhost");
  18749. std::thread t([&]() { svr.listen_after_bind(); });
  18750. auto se = detail::scope_exit([&] {
  18751. svr.stop();
  18752. t.join();
  18753. });
  18754. svr.wait_until_ready();
  18755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18756. auto res = client.connect();
  18757. EXPECT_FALSE(res);
  18758. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18759. EXPECT_FALSE(client.is_open());
  18760. }
  18761. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18762. // The socket path doubles as the URL host, so it must not contain '/'.
  18763. const char *shard = getenv("GTEST_SHARD_INDEX");
  18764. const std::string sock_path =
  18765. shard ? std::string("httplib-ws-") + shard + ".sock"
  18766. : std::string("httplib-ws.sock");
  18767. std::remove(sock_path.c_str());
  18768. Server svr;
  18769. std::mutex mtx;
  18770. std::string received_host;
  18771. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18772. {
  18773. std::lock_guard<std::mutex> lock(mtx);
  18774. received_host = req.get_header_value("Host");
  18775. }
  18776. std::string msg;
  18777. while (ws.read(msg)) {
  18778. ws.send(msg);
  18779. }
  18780. });
  18781. svr.set_address_family(AF_UNIX);
  18782. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. std::remove(sock_path.c_str());
  18787. });
  18788. svr.wait_until_ready();
  18789. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18790. client.set_address_family(AF_UNIX);
  18791. ASSERT_TRUE(client.connect());
  18792. ASSERT_TRUE(client.send("hello"));
  18793. std::string msg;
  18794. ASSERT_TRUE(client.read(msg));
  18795. client.close();
  18796. {
  18797. std::lock_guard<std::mutex> lock(mtx);
  18798. // There is no host:port for a Unix socket, so the same "localhost"
  18799. // placeholder the HTTP client uses is expected.
  18800. EXPECT_EQ("localhost", received_host);
  18801. }
  18802. }
  18803. // Two threads must never parse WebSocket frames from the same stream.
  18804. // close() used to read the peer's Close reply with its own frame read, so it
  18805. // raced a reader thread that was in the middle of a payload: the payload loop
  18806. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18807. // so bytes taken by close() were replaced with bytes from further along the
  18808. // stream. The message kept its length and silently changed content.
  18809. //
  18810. // The raw peer below sends a frame header plus part of the payload, waits for
  18811. // the handler to call close(), and only then sends the rest. Whichever thread
  18812. // would win the race for those bytes, the message must arrive intact, because
  18813. // close() must not touch the stream while read() owns it.
  18814. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18815. #ifndef _WIN32
  18816. signal(SIGPIPE, SIG_IGN);
  18817. #endif
  18818. const size_t payload_len = 120; // fits the 7-bit length field
  18819. const size_t prefix_len = 8;
  18820. const int attempts = 8;
  18821. std::string expected(payload_len, '\0');
  18822. for (size_t i = 0; i < payload_len; i++) {
  18823. expected[i] = static_cast<char>('a' + i % 26);
  18824. }
  18825. std::atomic<bool> peer_stalled{false};
  18826. std::atomic<bool> handler_done{false};
  18827. std::mutex received_mutex;
  18828. std::vector<std::string> received;
  18829. // Bound every wait, so a regression fails the test instead of hanging the
  18830. // suite.
  18831. auto wait_for = [](const std::atomic<bool> &flag) {
  18832. for (int i = 0; i < 500 && !flag; i++) {
  18833. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18834. }
  18835. };
  18836. Server svr;
  18837. svr.set_websocket_ping_interval(0);
  18838. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18839. std::thread reader([&]() {
  18840. std::string msg;
  18841. while (ws.read(msg)) {
  18842. std::lock_guard<std::mutex> guard(received_mutex);
  18843. received.push_back(msg);
  18844. }
  18845. });
  18846. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18847. // inside read_websocket_frame() when close() runs.
  18848. wait_for(peer_stalled);
  18849. ws.close();
  18850. reader.join();
  18851. handler_done = true;
  18852. });
  18853. auto port = svr.bind_to_any_port("127.0.0.1");
  18854. std::thread t([&]() { svr.listen_after_bind(); });
  18855. auto se = detail::scope_exit([&] {
  18856. svr.stop();
  18857. t.join();
  18858. });
  18859. svr.wait_until_ready();
  18860. auto send_bytes = [](socket_t s, const std::string &data) {
  18861. #ifdef _WIN32
  18862. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18863. #else
  18864. auto n = ::send(s, data.data(), data.size(), 0);
  18865. #endif
  18866. return n == static_cast<decltype(n)>(data.size());
  18867. };
  18868. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18869. // Every length used here fits the 7-bit length field.
  18870. auto masked_header = [](uint8_t first_byte, size_t len) {
  18871. std::string h;
  18872. h += static_cast<char>(first_byte);
  18873. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18874. h.append(4, '\0'); // mask key
  18875. return h;
  18876. };
  18877. for (int attempt = 0; attempt < attempts; attempt++) {
  18878. peer_stalled = false;
  18879. handler_done = false;
  18880. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18881. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18882. auto se_sock = detail::scope_exit([&] {
  18883. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18884. });
  18885. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18886. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18887. sockaddr_in addr{};
  18888. addr.sin_family = AF_INET;
  18889. addr.sin_port = htons(static_cast<uint16_t>(port));
  18890. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18891. ASSERT_EQ(
  18892. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18893. << "attempt " << attempt;
  18894. ASSERT_TRUE(send_bytes(sock,
  18895. "GET /ws HTTP/1.1\r\n"
  18896. "Host: 127.0.0.1\r\n"
  18897. "Upgrade: websocket\r\n"
  18898. "Connection: Upgrade\r\n"
  18899. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18900. "Sec-WebSocket-Version: 13\r\n"
  18901. "\r\n"))
  18902. << "attempt " << attempt;
  18903. std::string response;
  18904. while (response.find("\r\n\r\n") == std::string::npos) {
  18905. char buf[512];
  18906. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18907. if (n <= 0) { break; }
  18908. response.append(buf, static_cast<size_t>(n));
  18909. }
  18910. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18911. << "attempt " << attempt;
  18912. // Send the header of a Binary message but only the first prefix_len bytes
  18913. // of its payload, leaving the reader thread stalled inside the payload.
  18914. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18915. expected.substr(0, prefix_len)))
  18916. << "attempt " << attempt;
  18917. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18918. peer_stalled = true;
  18919. // Let close() send its Close frame and park in its own read before the
  18920. // rest of the payload arrives, so both threads are waiting for it.
  18921. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18922. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18923. close_frame += static_cast<char>(0x03); // status 1000
  18924. close_frame += static_cast<char>(0xE8);
  18925. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18926. << "attempt " << attempt;
  18927. // Closing the peer releases the reader thread even on the buggy path,
  18928. // where it waits for bytes another thread already consumed.
  18929. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18930. detail::close_socket(sock);
  18931. sock = INVALID_SOCKET;
  18932. wait_for(handler_done);
  18933. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18934. }
  18935. std::lock_guard<std::mutex> guard(received_mutex);
  18936. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18937. << "a message in flight when close() ran was dropped";
  18938. for (size_t i = 0; i < received.size(); i++) {
  18939. EXPECT_EQ(expected, received[i]) << "message " << i;
  18940. }
  18941. }
  18942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18943. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18944. protected:
  18945. void SetUp() override {
  18946. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18947. SERVER_PRIVATE_KEY_FILE);
  18948. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18949. std::string msg;
  18950. ws::ReadResult ret;
  18951. while ((ret = ws.read(msg))) {
  18952. if (ret == ws::Binary) {
  18953. ws.send(msg.data(), msg.size());
  18954. } else {
  18955. ws.send(msg);
  18956. }
  18957. }
  18958. });
  18959. port_ = server_->bind_to_any_port(HOST);
  18960. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18961. server_->wait_until_ready();
  18962. }
  18963. void TearDown() override {
  18964. server_->stop();
  18965. if (server_thread_.joinable()) { server_thread_.join(); }
  18966. }
  18967. std::unique_ptr<SSLServer> server_;
  18968. std::thread server_thread_;
  18969. int port_ = 0;
  18970. };
  18971. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18972. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18973. "/ws-echo");
  18974. client.enable_server_certificate_verification(false);
  18975. ASSERT_TRUE(client.connect());
  18976. ASSERT_TRUE(client.is_open());
  18977. ASSERT_TRUE(client.send("Hello WSS"));
  18978. std::string msg;
  18979. EXPECT_EQ(ws::Text, client.read(msg));
  18980. EXPECT_EQ("Hello WSS", msg);
  18981. client.close();
  18982. }
  18983. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18984. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18985. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18986. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18987. // client (without calling close() first) is the only path that runs
  18988. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18989. // bug exactly.
  18990. //
  18991. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18992. // when linked against an instrumented libssl; run under Valgrind to catch it
  18993. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18994. // suite (the freed session otherwise stalls on the close handshake) — this test
  18995. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18996. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18997. {
  18998. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18999. "/ws-echo");
  19000. client.enable_server_certificate_verification(false);
  19001. client.set_read_timeout(2, 0);
  19002. client.set_write_timeout(2, 0);
  19003. ASSERT_TRUE(client.connect());
  19004. ASSERT_TRUE(client.is_open());
  19005. ASSERT_TRUE(client.send("still open"));
  19006. // Intentionally do NOT call client.close(): leaving scope runs
  19007. // shutdown_and_close() with the WebSocket still open, which must send the
  19008. // close frame while the TLS session is still alive.
  19009. }
  19010. }
  19011. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19012. // shutdown_and_close() at the start of connect(), reproducing the same
  19013. // use-after-free within the test body rather than at scope exit. The second
  19014. // connect must succeed and echo, proving the close handshake ran over a live
  19015. // session. See the note above about memory-tool requirements.
  19016. TEST_F(WebSocketSSLIntegrationTest,
  19017. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19018. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19019. "/ws-echo");
  19020. client.enable_server_certificate_verification(false);
  19021. client.set_read_timeout(2, 0);
  19022. client.set_write_timeout(2, 0);
  19023. ASSERT_TRUE(client.connect());
  19024. ASSERT_TRUE(client.is_open());
  19025. ASSERT_TRUE(client.send("still open"));
  19026. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19027. // the still-open connection, which must not touch a freed TLS session.
  19028. ASSERT_TRUE(client.connect());
  19029. ASSERT_TRUE(client.is_open());
  19030. ASSERT_TRUE(client.send("after reconnect"));
  19031. std::string msg;
  19032. EXPECT_EQ(ws::Text, client.read(msg));
  19033. EXPECT_EQ("after reconnect", msg);
  19034. client.close();
  19035. }
  19036. #endif
  19037. #ifdef CPPHTTPLIB_SSL_ENABLED
  19038. class WebSocketSSLCATest : public ::testing::Test {
  19039. protected:
  19040. void SetUp() override {
  19041. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19042. SERVER_PRIVATE_KEY_FILE);
  19043. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19044. std::string msg;
  19045. while (ws.read(msg)) {
  19046. ws.send(msg);
  19047. }
  19048. });
  19049. port_ = server_->bind_to_any_port("127.0.0.1");
  19050. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19051. server_->wait_until_ready();
  19052. }
  19053. void TearDown() override {
  19054. server_->stop();
  19055. if (server_thread_.joinable()) { server_thread_.join(); }
  19056. }
  19057. std::string url() const {
  19058. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19059. }
  19060. std::unique_ptr<SSLServer> server_;
  19061. std::thread server_thread_;
  19062. int port_ = 0;
  19063. };
  19064. // A custom CA loaded as PEM verifies the server with full certificate
  19065. // verification enabled
  19066. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19067. ws::WebSocketClient client(url());
  19068. std::string cert;
  19069. read_file(SERVER_CERT2_FILE, cert);
  19070. client.load_ca_cert_store(cert.c_str(), cert.size());
  19071. ASSERT_TRUE(client.connect());
  19072. ASSERT_TRUE(client.send("hello"));
  19073. std::string msg;
  19074. EXPECT_EQ(ws::Text, client.read(msg));
  19075. EXPECT_EQ("hello", msg);
  19076. client.close();
  19077. }
  19078. // A custom CA that does not cover the server must fail verification (the
  19079. // custom CA is exclusive; system certs are not loaded alongside it)
  19080. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19081. ws::WebSocketClient client(url());
  19082. std::string cert;
  19083. read_file(CLIENT_CA_CERT_FILE, cert);
  19084. client.load_ca_cert_store(cert.c_str(), cert.size());
  19085. auto res = client.connect();
  19086. ASSERT_FALSE(res);
  19087. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19088. EXPECT_EQ(-1, res.status());
  19089. EXPECT_NE(0u, res.ssl_backend_error());
  19090. }
  19091. // The same CA as a file path rather than PEM in memory
  19092. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19093. ws::WebSocketClient client(url());
  19094. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19095. ASSERT_TRUE(client.connect());
  19096. ASSERT_TRUE(client.send("hello"));
  19097. std::string msg;
  19098. EXPECT_EQ(ws::Text, client.read(msg));
  19099. EXPECT_EQ("hello", msg);
  19100. client.close();
  19101. }
  19102. // ...and a CA file that does not cover the server still fails, so it is the
  19103. // path above that decides the outcome
  19104. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19105. ws::WebSocketClient client(url());
  19106. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19107. ASSERT_FALSE(client.connect());
  19108. }
  19109. // Regression test: reconnecting with a native custom CA store used to reuse
  19110. // a store handle the previous TLS context had already freed (use-after-free
  19111. // under the OpenSSL backend). The context now lives as long as the client.
  19112. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19113. ws::WebSocketClient client(url());
  19114. std::string cert;
  19115. read_file(SERVER_CERT2_FILE, cert);
  19116. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19117. ASSERT_TRUE(client.connect());
  19118. client.close();
  19119. ASSERT_TRUE(client.connect());
  19120. ASSERT_TRUE(client.send("again"));
  19121. std::string msg;
  19122. EXPECT_EQ(ws::Text, client.read(msg));
  19123. EXPECT_EQ("again", msg);
  19124. client.close();
  19125. }
  19126. // Regression test: a certificate with a trusted chain but no identity match
  19127. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19128. // verification entirely for IP hosts, so this connection succeeded there.
  19129. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19130. // chain verification while the identity check must still fail.
  19131. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19133. ASSERT_TRUE(svr.is_valid());
  19134. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19135. std::string msg;
  19136. while (ws.read(msg)) {
  19137. ws.send(msg);
  19138. }
  19139. });
  19140. auto port = svr.bind_to_any_port("127.0.0.1");
  19141. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19142. auto se = detail::scope_exit([&] {
  19143. svr.stop();
  19144. t.join();
  19145. });
  19146. svr.wait_until_ready();
  19147. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19148. "/echo");
  19149. std::string cert;
  19150. read_file(SERVER_CERT_FILE, cert);
  19151. client.load_ca_cert_store(cert.c_str(), cert.size());
  19152. ASSERT_FALSE(client.connect());
  19153. }
  19154. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19155. // SNI, so nothing binds the host name to the TLS session. These bind the
  19156. // server to "localhost" instead, the only shape that exercises the SNI and
  19157. // hostname-verification path with certificate verification left enabled.
  19158. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19159. protected:
  19160. void Start(const char *cert_file) {
  19161. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19162. SERVER_PRIVATE_KEY_FILE);
  19163. ASSERT_TRUE(server_->is_valid());
  19164. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19165. std::string msg;
  19166. while (ws.read(msg)) {
  19167. ws.send(msg);
  19168. }
  19169. });
  19170. port_ = server_->bind_to_any_port("localhost");
  19171. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19172. server_->wait_until_ready();
  19173. }
  19174. void TearDown() override {
  19175. if (server_) { server_->stop(); }
  19176. if (server_thread_.joinable()) { server_thread_.join(); }
  19177. }
  19178. std::string url() const {
  19179. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19180. }
  19181. std::unique_ptr<SSLServer> server_;
  19182. std::thread server_thread_;
  19183. int port_ = 0;
  19184. };
  19185. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19186. // out and the connection is usable
  19187. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19188. Start(SERVER_CERT2_FILE);
  19189. ws::WebSocketClient client(url());
  19190. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19191. ASSERT_TRUE(client.connect());
  19192. ASSERT_TRUE(client.send("hello"));
  19193. std::string msg;
  19194. EXPECT_EQ(ws::Text, client.read(msg));
  19195. EXPECT_EQ("hello", msg);
  19196. client.close();
  19197. }
  19198. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19199. // while the identity check must still reject "localhost"
  19200. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19201. Start(SERVER_CERT_FILE);
  19202. ws::WebSocketClient client(url());
  19203. client.set_ca_cert_path(SERVER_CERT_FILE);
  19204. auto res = client.connect();
  19205. ASSERT_FALSE(res);
  19206. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19207. EXPECT_EQ(-1, res.status());
  19208. }
  19209. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19210. // disabled: the chain is still checked, only the identity check is skipped
  19211. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19212. Start(SERVER_CERT_FILE);
  19213. ws::WebSocketClient client(url());
  19214. client.set_ca_cert_path(SERVER_CERT_FILE);
  19215. client.enable_server_hostname_verification(false);
  19216. ASSERT_TRUE(client.connect());
  19217. ASSERT_TRUE(client.send("hello"));
  19218. std::string msg;
  19219. EXPECT_EQ(ws::Text, client.read(msg));
  19220. EXPECT_EQ("hello", msg);
  19221. client.close();
  19222. }
  19223. // A CA that did not sign the server certificate fails the chain, even though
  19224. // the name would match
  19225. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19226. Start(SERVER_CERT2_FILE);
  19227. ws::WebSocketClient client(url());
  19228. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19229. ASSERT_FALSE(client.connect());
  19230. }
  19231. // With verification disabled, neither the chain nor the name is checked
  19232. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19233. Start(SERVER_CERT_FILE);
  19234. ws::WebSocketClient client(url());
  19235. client.enable_server_certificate_verification(false);
  19236. ASSERT_TRUE(client.connect());
  19237. ASSERT_TRUE(client.send("hello"));
  19238. std::string msg;
  19239. EXPECT_EQ(ws::Text, client.read(msg));
  19240. EXPECT_EQ("hello", msg);
  19241. client.close();
  19242. }
  19243. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19244. protected:
  19245. void SetUp() override {
  19246. server_ = httplib::detail::make_unique<SSLServer>(
  19247. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19248. ASSERT_TRUE(server_->is_valid());
  19249. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19250. std::string msg;
  19251. while (ws.read(msg)) {
  19252. ws.send(msg);
  19253. }
  19254. });
  19255. port_ = server_->bind_to_any_port("localhost");
  19256. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19257. server_->wait_until_ready();
  19258. }
  19259. void TearDown() override {
  19260. server_->stop();
  19261. if (server_thread_.joinable()) { server_thread_.join(); }
  19262. }
  19263. std::string url() const {
  19264. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19265. }
  19266. void ConnectWithClientCert(const std::string &client_cert_file,
  19267. const std::string &client_private_key_file,
  19268. const char *private_key_password) {
  19269. std::string cert_pem, key_pem;
  19270. read_file(client_cert_file, cert_pem);
  19271. read_file(client_private_key_file, key_pem);
  19272. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19273. key_pem.c_str(), key_pem.size(),
  19274. private_key_password};
  19275. ws::WebSocketClient client(url(), pem);
  19276. ASSERT_TRUE(client.is_valid());
  19277. client.enable_server_certificate_verification(false);
  19278. ASSERT_TRUE(client.connect());
  19279. ASSERT_TRUE(client.send("hello"));
  19280. std::string msg;
  19281. EXPECT_EQ(ws::Text, client.read(msg));
  19282. EXPECT_EQ("hello", msg);
  19283. client.close();
  19284. }
  19285. std::unique_ptr<SSLServer> server_;
  19286. std::thread server_thread_;
  19287. int port_ = 0;
  19288. };
  19289. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19290. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19291. }
  19292. // Control for the tests above: the fixture's server really does require a
  19293. // client certificate, so it is the PEM the constructor installed that decides
  19294. // the outcome.
  19295. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19296. ws::WebSocketClient client(url());
  19297. ASSERT_TRUE(client.is_valid());
  19298. client.enable_server_certificate_verification(false);
  19299. EXPECT_FALSE(client.connect());
  19300. }
  19301. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19302. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19303. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19304. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19305. }
  19306. #endif
  19307. #if !defined(_WIN32)
  19308. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19309. auto secret_dir = std::string("./symlink_test_secret");
  19310. auto served_dir = std::string("./symlink_test_served");
  19311. auto secret_file = secret_dir + "/secret.txt";
  19312. auto symlink_path = served_dir + "/escape";
  19313. // Setup: create directories and files
  19314. mkdir(secret_dir.c_str(), 0755);
  19315. mkdir(served_dir.c_str(), 0755);
  19316. {
  19317. std::ofstream ofs(secret_file);
  19318. ofs << "SECRET_DATA";
  19319. }
  19320. // Create symlink using absolute path so it resolves correctly
  19321. #ifdef PATH_MAX
  19322. char abs_secret[PATH_MAX];
  19323. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19324. #else
  19325. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19326. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19327. ASSERT_NE(nullptr, abs_secret);
  19328. #endif
  19329. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19330. auto se = detail::scope_exit([&] {
  19331. unlink(symlink_path.c_str());
  19332. unlink(secret_file.c_str());
  19333. rmdir(served_dir.c_str());
  19334. rmdir(secret_dir.c_str());
  19335. });
  19336. Server svr;
  19337. svr.set_mount_point("/", served_dir);
  19338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19339. auto se2 = detail::scope_exit([&] {
  19340. svr.stop();
  19341. listen_thread.join();
  19342. });
  19343. svr.wait_until_ready();
  19344. Client cli("localhost", PORT);
  19345. // Symlink pointing outside base dir should be blocked
  19346. auto res = cli.Get("/escape/secret.txt");
  19347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19348. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19349. }
  19350. #endif
  19351. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19352. // A GET request with Content-Length to a static file handler must have its
  19353. // body drained before the keep-alive connection is reused. Otherwise the
  19354. // unread body bytes are interpreted as the next HTTP request.
  19355. //
  19356. // The body is sent AFTER receiving the first response (as in the original
  19357. // PoC) so that the stream_line_reader cannot buffer it together with the
  19358. // headers of the first request.
  19359. Server svr;
  19360. svr.set_mount_point("/", "./www");
  19361. std::atomic<int> smuggled_count(0);
  19362. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19363. smuggled_count++;
  19364. res.set_content("oops", "text/plain");
  19365. });
  19366. auto port = svr.bind_to_any_port("localhost");
  19367. thread t = thread([&] { svr.listen_after_bind(); });
  19368. auto se = detail::scope_exit([&] {
  19369. svr.stop();
  19370. t.join();
  19371. });
  19372. svr.wait_until_ready();
  19373. auto error = Error::Success;
  19374. auto sock = detail::create_client_socket(
  19375. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19376. /*connection_timeout_sec=*/2, 0,
  19377. /*read_timeout_sec=*/2, 0,
  19378. /*write_timeout_sec=*/2, 0, std::string(), error);
  19379. ASSERT_NE(INVALID_SOCKET, sock);
  19380. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19381. // The "smuggled" request will be sent as the body of the outer GET
  19382. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19383. "Host: localhost\r\n"
  19384. "Connection: close\r\n"
  19385. "\r\n";
  19386. // Step 1: Send only the outer request headers (no body yet)
  19387. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19388. "Host: localhost\r\n"
  19389. "Content-Length: " +
  19390. std::to_string(smuggled.size()) +
  19391. "\r\n"
  19392. "\r\n";
  19393. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19394. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19395. // Step 2: Read the first response (server serves file without reading body)
  19396. std::string first_response;
  19397. char buf[4096];
  19398. for (;;) {
  19399. auto n = recv(sock, buf, sizeof(buf), 0);
  19400. if (n <= 0) break;
  19401. first_response.append(buf, static_cast<size_t>(n));
  19402. // Stop once we have a complete response (headers + body)
  19403. auto hdr_end = first_response.find("\r\n\r\n");
  19404. if (hdr_end != std::string::npos) {
  19405. // Check for Content-Length to know when the body is complete
  19406. auto cl_pos = first_response.find("Content-Length:");
  19407. if (cl_pos != std::string::npos) {
  19408. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19409. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19410. auto cl = std::stoul(
  19411. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19412. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19413. } else {
  19414. break; // No Content-Length, assume headers-only response
  19415. }
  19416. }
  19417. }
  19418. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19419. // Step 3: Now send the body, which looks like a new HTTP request.
  19420. // On a vulnerable server the keep-alive loop reads this as a second request.
  19421. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19422. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19423. // Step 4: Try to read a second response (should NOT exist after fix)
  19424. std::string second_response;
  19425. for (;;) {
  19426. auto n = recv(sock, buf, sizeof(buf), 0);
  19427. if (n <= 0) break;
  19428. second_response.append(buf, static_cast<size_t>(n));
  19429. }
  19430. // The smuggled request must NOT have been processed
  19431. EXPECT_EQ(0, smuggled_count.load());
  19432. }
  19433. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19434. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19435. // must be rejected with 400 Bad Request.
  19436. Server svr;
  19437. svr.Post("/test", [&](const Request &, Response &res) {
  19438. res.set_content("ok", "text/plain");
  19439. });
  19440. thread t = thread([&] { svr.listen(HOST, PORT); });
  19441. auto se = detail::scope_exit([&] {
  19442. svr.stop();
  19443. t.join();
  19444. ASSERT_FALSE(svr.is_running());
  19445. });
  19446. svr.wait_until_ready();
  19447. // Exact "chunked"
  19448. {
  19449. auto req = "POST /test HTTP/1.1\r\n"
  19450. "Host: localhost\r\n"
  19451. "Content-Length: 5\r\n"
  19452. "Transfer-Encoding: chunked\r\n"
  19453. "Connection: close\r\n"
  19454. "\r\n"
  19455. "hello";
  19456. std::string response;
  19457. ASSERT_TRUE(send_request(1, req, &response));
  19458. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19459. response.substr(0, response.find("\r\n")));
  19460. }
  19461. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19462. {
  19463. auto req = "POST /test HTTP/1.1\r\n"
  19464. "Host: localhost\r\n"
  19465. "Content-Length: 5\r\n"
  19466. "Transfer-Encoding: gzip, chunked\r\n"
  19467. "Connection: close\r\n"
  19468. "\r\n"
  19469. "hello";
  19470. std::string response;
  19471. ASSERT_TRUE(send_request(1, req, &response));
  19472. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19473. response.substr(0, response.find("\r\n")));
  19474. }
  19475. }
  19476. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19477. Server svr;
  19478. svr.Post("/test", [&](const Request &, Response &res) {
  19479. res.set_content("ok", "text/plain");
  19480. });
  19481. thread t = thread([&] { svr.listen(HOST, PORT); });
  19482. auto se = detail::scope_exit([&] {
  19483. svr.stop();
  19484. t.join();
  19485. ASSERT_FALSE(svr.is_running());
  19486. });
  19487. svr.wait_until_ready();
  19488. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19489. // length cannot be determined, so the server must answer 400 and close
  19490. // rather than treat the request as bodyless and leave the body in the
  19491. // socket for the next request to pick up.
  19492. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19493. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19494. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19495. std::string response;
  19496. ASSERT_TRUE(send_request(1, req, &response));
  19497. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19498. response.substr(0, response.find("\r\n")))
  19499. << transfer_encoding;
  19500. }
  19501. // RFC 9110 5.3: the codings may also be split across several
  19502. // Transfer-Encoding lines, which combine in the order they were received.
  19503. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19504. // just like the single-line "chunked, gzip" above.
  19505. {
  19506. auto req = "POST /test HTTP/1.1\r\n"
  19507. "Host: localhost\r\n"
  19508. "Transfer-Encoding: chunked\r\n"
  19509. "Transfer-Encoding: gzip\r\n"
  19510. "\r\n"
  19511. "0\r\n\r\n";
  19512. std::string response;
  19513. ASSERT_TRUE(send_request(1, req, &response));
  19514. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19515. response.substr(0, response.find("\r\n")));
  19516. }
  19517. // A sequence ending in chunked stays valid.
  19518. auto req = "POST /test HTTP/1.1\r\n"
  19519. "Host: localhost\r\n"
  19520. "Transfer-Encoding: gzip, chunked\r\n"
  19521. "Connection: close\r\n"
  19522. "\r\n"
  19523. "0\r\n\r\n";
  19524. std::string response;
  19525. ASSERT_TRUE(send_request(1, req, &response));
  19526. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19527. // ...including when it is spread over several lines.
  19528. auto split_req = "POST /test HTTP/1.1\r\n"
  19529. "Host: localhost\r\n"
  19530. "Transfer-Encoding: gzip\r\n"
  19531. "Transfer-Encoding: chunked\r\n"
  19532. "Connection: close\r\n"
  19533. "\r\n"
  19534. "0\r\n\r\n";
  19535. std::string split_response;
  19536. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19537. EXPECT_EQ("HTTP/1.1 200 OK",
  19538. split_response.substr(0, split_response.find("\r\n")));
  19539. }
  19540. // Regression for issue #2450: a DELETE without Content-Length on a
  19541. // keep-alive connection must not let the post-response drain consume the
  19542. // next request's bytes.
  19543. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19544. Server svr;
  19545. std::atomic<int> delete_count(0);
  19546. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19547. delete_count++;
  19548. res.status = StatusCode::NoContent_204;
  19549. });
  19550. auto port = svr.bind_to_any_port(HOST);
  19551. thread t = thread([&] { svr.listen_after_bind(); });
  19552. auto se = detail::scope_exit([&] {
  19553. svr.stop();
  19554. t.join();
  19555. });
  19556. svr.wait_until_ready();
  19557. auto error = Error::Success;
  19558. auto sock = detail::create_client_socket(
  19559. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19560. /*connection_timeout_sec=*/2, 0,
  19561. /*read_timeout_sec=*/2, 0,
  19562. /*write_timeout_sec=*/2, 0, std::string(), error);
  19563. ASSERT_NE(INVALID_SOCKET, sock);
  19564. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19565. auto send_request_and_read_response = [&](const std::string &req,
  19566. std::string &out) -> bool {
  19567. auto sent = send(sock, req.data(), req.size(), 0);
  19568. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19569. char buf[4096];
  19570. for (;;) {
  19571. auto n = recv(sock, buf, sizeof(buf), 0);
  19572. if (n <= 0) { return !out.empty(); }
  19573. out.append(buf, static_cast<size_t>(n));
  19574. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19575. }
  19576. };
  19577. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19578. "Host: localhost\r\n"
  19579. "\r\n";
  19580. std::string resp1;
  19581. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19582. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19583. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19584. "Host: localhost\r\n"
  19585. "Connection: close\r\n"
  19586. "\r\n";
  19587. std::string resp2;
  19588. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19589. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19590. EXPECT_EQ(2, delete_count.load());
  19591. }
  19592. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19593. Server svr;
  19594. svr.Post("/ingest", [&](const Request &, Response &res,
  19595. const ContentReader &content_reader) {
  19596. auto consumed = content_reader([](const char *, size_t) { return false; });
  19597. EXPECT_FALSE(consumed);
  19598. res.status = StatusCode::Conflict_409;
  19599. res.set_header("Connection", "close");
  19600. });
  19601. auto port = svr.bind_to_any_port(HOST);
  19602. thread t = thread([&] { svr.listen_after_bind(); });
  19603. auto se = detail::scope_exit([&] {
  19604. svr.stop();
  19605. t.join();
  19606. });
  19607. svr.wait_until_ready();
  19608. auto error = Error::Success;
  19609. auto sock = detail::create_client_socket(
  19610. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19611. /*connection_timeout_sec=*/2, 0,
  19612. /*read_timeout_sec=*/1, 0,
  19613. /*write_timeout_sec=*/2, 0, std::string(), error);
  19614. ASSERT_NE(INVALID_SOCKET, sock);
  19615. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19616. std::string request = "POST /ingest HTTP/1.1\r\n"
  19617. "Host: localhost\r\n"
  19618. "Transfer-Encoding: chunked\r\n"
  19619. "\r\n"
  19620. "4\r\n"
  19621. "data\r\n";
  19622. auto sent = send(sock, request.data(), request.size(), 0);
  19623. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19624. std::string response;
  19625. ssize_t received = 0;
  19626. do {
  19627. char buf[4096];
  19628. received = recv(sock, buf, sizeof(buf), 0);
  19629. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19630. } while (received > 0);
  19631. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19632. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19633. EXPECT_EQ(0, received);
  19634. }
  19635. namespace no_proxy_test {
  19636. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19637. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19638. // calling listen().
  19639. class ScopedServer {
  19640. public:
  19641. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19642. ~ScopedServer() {
  19643. svr_.stop();
  19644. if (th_.joinable()) { th_.join(); }
  19645. }
  19646. Server &svr() { return svr_; }
  19647. int port() const { return port_; }
  19648. void listen() {
  19649. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19650. svr_.wait_until_ready();
  19651. }
  19652. private:
  19653. Server svr_;
  19654. std::thread th_;
  19655. int port_ = 0;
  19656. };
  19657. class ProxyAndTargetServers {
  19658. public:
  19659. ProxyAndTargetServers() {
  19660. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19661. proxy_hits_++;
  19662. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19663. res.set_content("via-proxy", "text/plain");
  19664. });
  19665. target_.Get(".*", [this](const Request &req, Response &res) {
  19666. target_hits_++;
  19667. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19668. res.set_content("direct", "text/plain");
  19669. });
  19670. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19671. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19672. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19673. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19674. proxy_mock_.wait_until_ready();
  19675. target_.wait_until_ready();
  19676. }
  19677. ~ProxyAndTargetServers() {
  19678. proxy_mock_.stop();
  19679. target_.stop();
  19680. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19681. if (target_thread_.joinable()) { target_thread_.join(); }
  19682. }
  19683. Server &proxy_mock() { return proxy_mock_; }
  19684. Server &target() { return target_; }
  19685. int proxy_port() const { return proxy_port_; }
  19686. int target_port() const { return target_port_; }
  19687. int proxy_hits() const { return proxy_hits_.load(); }
  19688. int target_hits() const { return target_hits_.load(); }
  19689. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19690. void reset_counters() {
  19691. proxy_hits_ = 0;
  19692. target_hits_ = 0;
  19693. last_had_proxy_authz_ = false;
  19694. }
  19695. private:
  19696. Server proxy_mock_;
  19697. Server target_;
  19698. std::thread proxy_thread_;
  19699. std::thread target_thread_;
  19700. int proxy_port_ = 0;
  19701. int target_port_ = 0;
  19702. std::atomic<int> proxy_hits_{0};
  19703. std::atomic<int> target_hits_{0};
  19704. std::atomic<bool> last_had_proxy_authz_{false};
  19705. };
  19706. inline std::unique_ptr<Client> make_client(const std::string &host,
  19707. ProxyAndTargetServers &s) {
  19708. auto cli = detail::make_unique<Client>(host, s.target_port());
  19709. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19710. cli->set_proxy("127.0.0.1", s.proxy_port());
  19711. return cli;
  19712. }
  19713. } // namespace no_proxy_test
  19714. using no_proxy_test::make_client;
  19715. using no_proxy_test::ProxyAndTargetServers;
  19716. TEST(NoProxyTest, ExactHostnameBypasses) {
  19717. ProxyAndTargetServers s;
  19718. auto cli = make_client("example.com", s);
  19719. cli->set_no_proxy({"example.com"});
  19720. auto res = cli->Get("/");
  19721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19722. EXPECT_EQ(0, s.proxy_hits());
  19723. EXPECT_EQ(1, s.target_hits());
  19724. }
  19725. TEST(NoProxyTest, SubdomainBypasses) {
  19726. ProxyAndTargetServers s;
  19727. auto cli = make_client("foo.example.com", s);
  19728. cli->set_no_proxy({"example.com"});
  19729. auto res = cli->Get("/");
  19730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19731. EXPECT_EQ(0, s.proxy_hits());
  19732. EXPECT_EQ(1, s.target_hits());
  19733. }
  19734. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19735. // Regression guard: "evilexample.com" must not be considered a subdomain
  19736. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19737. // check would let traffic bypass the proxy and leak credentials direct
  19738. // to the attacker host.
  19739. ProxyAndTargetServers s;
  19740. auto cli = make_client("evilexample.com", s);
  19741. cli->set_no_proxy({"example.com"});
  19742. auto res = cli->Get("/");
  19743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19744. EXPECT_GE(s.proxy_hits(), 1);
  19745. EXPECT_EQ(0, s.target_hits());
  19746. }
  19747. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19748. ProxyAndTargetServers s;
  19749. auto cli = make_client("example.com.evil.com", s);
  19750. cli->set_no_proxy({"example.com"});
  19751. auto res = cli->Get("/");
  19752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19753. EXPECT_GE(s.proxy_hits(), 1);
  19754. EXPECT_EQ(0, s.target_hits());
  19755. }
  19756. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19757. ProxyAndTargetServers s;
  19758. auto cli = make_client("example.com", s);
  19759. cli->set_no_proxy({".example.com"});
  19760. auto res = cli->Get("/");
  19761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19762. EXPECT_EQ(0, s.proxy_hits());
  19763. EXPECT_EQ(1, s.target_hits());
  19764. }
  19765. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19766. ProxyAndTargetServers s;
  19767. auto cli = make_client("Example.COM", s);
  19768. cli->set_no_proxy({"EXAMPLE.com"});
  19769. auto res = cli->Get("/");
  19770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19771. EXPECT_EQ(0, s.proxy_hits());
  19772. EXPECT_EQ(1, s.target_hits());
  19773. }
  19774. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19775. ProxyAndTargetServers s;
  19776. auto cli = make_client("example.com.", s);
  19777. cli->set_no_proxy({"example.com"});
  19778. auto res = cli->Get("/");
  19779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19780. EXPECT_EQ(0, s.proxy_hits());
  19781. EXPECT_EQ(1, s.target_hits());
  19782. }
  19783. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19784. // Trailing dots must be normalized on BOTH sides — host and entry.
  19785. // An implementation that only strips the host-side trailing dot would
  19786. // fail to match host "example.com" against entry "example.com." because
  19787. // a literal substring search would compare 11 chars against 12.
  19788. ProxyAndTargetServers s;
  19789. auto cli = make_client("example.com", s);
  19790. cli->set_no_proxy({"example.com."});
  19791. auto res = cli->Get("/");
  19792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19793. EXPECT_EQ(0, s.proxy_hits());
  19794. EXPECT_EQ(1, s.target_hits());
  19795. }
  19796. TEST(NoProxyTest, WildcardBypassesEverything) {
  19797. ProxyAndTargetServers s;
  19798. auto cli = make_client("anything.invalid.test", s);
  19799. cli->set_no_proxy({"*"});
  19800. auto res = cli->Get("/");
  19801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19802. EXPECT_EQ(0, s.proxy_hits());
  19803. EXPECT_EQ(1, s.target_hits());
  19804. }
  19805. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19806. ProxyAndTargetServers s;
  19807. Client cli("127.0.0.1", s.target_port());
  19808. cli.set_proxy("127.0.0.1", s.proxy_port());
  19809. cli.set_no_proxy({"127.0.0.1"});
  19810. auto res = cli.Get("/");
  19811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19812. EXPECT_EQ(0, s.proxy_hits());
  19813. EXPECT_EQ(1, s.target_hits());
  19814. }
  19815. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19816. ProxyAndTargetServers s;
  19817. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19818. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19819. cli.set_proxy("127.0.0.1", s.proxy_port());
  19820. cli.set_no_proxy({"::1"});
  19821. auto res = cli.Get("/");
  19822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19823. EXPECT_EQ(0, s.proxy_hits());
  19824. EXPECT_EQ(1, s.target_hits());
  19825. }
  19826. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19827. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19828. // must still be recognized as IPv6 for CIDR matching. Implementations
  19829. // that detect IPv6 only when the host begins with '[' would parse the
  19830. // host as a hostname and miss the match.
  19831. ProxyAndTargetServers s;
  19832. Client cli("fe80::1", s.target_port());
  19833. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19834. cli.set_proxy("127.0.0.1", s.proxy_port());
  19835. cli.set_no_proxy({"fe80::/10"});
  19836. auto res = cli.Get("/");
  19837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19838. EXPECT_EQ(0, s.proxy_hits());
  19839. EXPECT_EQ(1, s.target_hits());
  19840. }
  19841. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19842. ProxyAndTargetServers s;
  19843. Client cli("::1", s.target_port());
  19844. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19845. cli.set_proxy("127.0.0.1", s.proxy_port());
  19846. cli.set_no_proxy({"[::1]"});
  19847. auto res = cli.Get("/");
  19848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19849. EXPECT_EQ(0, s.proxy_hits());
  19850. EXPECT_EQ(1, s.target_hits());
  19851. }
  19852. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19853. ProxyAndTargetServers s;
  19854. Client cli("fe80::1", s.target_port());
  19855. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19856. cli.set_proxy("127.0.0.1", s.proxy_port());
  19857. cli.set_no_proxy({"[fe80::]/10"});
  19858. auto res = cli.Get("/");
  19859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19860. EXPECT_EQ(0, s.proxy_hits());
  19861. EXPECT_EQ(1, s.target_hits());
  19862. }
  19863. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19864. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19865. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19866. // tricks via address-family conversion.
  19867. ProxyAndTargetServers s;
  19868. Client cli("::ffff:127.0.0.1", s.target_port());
  19869. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19870. cli.set_proxy("127.0.0.1", s.proxy_port());
  19871. cli.set_no_proxy({"127.0.0.1"});
  19872. auto res = cli.Get("/");
  19873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19874. EXPECT_GE(s.proxy_hits(), 1);
  19875. EXPECT_EQ(0, s.target_hits());
  19876. }
  19877. TEST(NoProxyTest, IPv4CidrMatch) {
  19878. ProxyAndTargetServers s;
  19879. Client cli("127.0.0.1", s.target_port());
  19880. cli.set_proxy("127.0.0.1", s.proxy_port());
  19881. cli.set_no_proxy({"127.0.0.0/8"});
  19882. auto res = cli.Get("/");
  19883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19884. EXPECT_EQ(0, s.proxy_hits());
  19885. EXPECT_EQ(1, s.target_hits());
  19886. }
  19887. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19888. ProxyAndTargetServers s;
  19889. Client cli("127.0.0.1", s.target_port());
  19890. cli.set_proxy("127.0.0.1", s.proxy_port());
  19891. cli.set_no_proxy({"10.0.0.0/8"});
  19892. auto res = cli.Get("/");
  19893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19894. EXPECT_GE(s.proxy_hits(), 1);
  19895. EXPECT_EQ(0, s.target_hits());
  19896. }
  19897. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19898. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19899. // IPv4 target matches.
  19900. ProxyAndTargetServers s;
  19901. Client cli("127.0.0.1", s.target_port());
  19902. cli.set_proxy("127.0.0.1", s.proxy_port());
  19903. cli.set_no_proxy({"0.0.0.0/0"});
  19904. auto res = cli.Get("/");
  19905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19906. EXPECT_EQ(0, s.proxy_hits());
  19907. EXPECT_EQ(1, s.target_hits());
  19908. }
  19909. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19910. ProxyAndTargetServers s;
  19911. Client cli("127.0.0.1", s.target_port());
  19912. cli.set_proxy("127.0.0.1", s.proxy_port());
  19913. cli.set_no_proxy({"127.0.0.1"});
  19914. auto res = cli.Get("/");
  19915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19916. EXPECT_EQ(0, s.proxy_hits());
  19917. EXPECT_EQ(1, s.target_hits());
  19918. }
  19919. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19920. ProxyAndTargetServers s;
  19921. Client cli("127.0.0.1", s.target_port());
  19922. cli.set_proxy("127.0.0.1", s.proxy_port());
  19923. cli.set_no_proxy({"127.0.0.0/33"});
  19924. auto res = cli.Get("/");
  19925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19926. EXPECT_GE(s.proxy_hits(), 1);
  19927. EXPECT_EQ(0, s.target_hits());
  19928. }
  19929. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19930. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19931. ProxyAndTargetServers s;
  19932. Client cli("127.0.0.1", s.target_port());
  19933. cli.set_proxy("127.0.0.1", s.proxy_port());
  19934. cli.set_no_proxy({"127.0.0.1/"});
  19935. auto res = cli.Get("/");
  19936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19937. EXPECT_GE(s.proxy_hits(), 1);
  19938. EXPECT_EQ(0, s.target_hits());
  19939. }
  19940. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19941. ProxyAndTargetServers s;
  19942. auto cli = make_client("internal.corp", s);
  19943. cli->set_proxy_basic_auth("u", "p");
  19944. cli->set_no_proxy({"internal.corp"});
  19945. auto res = cli->Get("/");
  19946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19947. EXPECT_EQ(1, s.target_hits());
  19948. EXPECT_EQ(0, s.proxy_hits());
  19949. EXPECT_FALSE(s.last_had_proxy_authz())
  19950. << "Proxy-Authorization must not be sent direct to the target";
  19951. }
  19952. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19953. ProxyAndTargetServers s;
  19954. auto cli = make_client("public.example", s);
  19955. cli->set_proxy_basic_auth("u", "p");
  19956. cli->set_no_proxy({"internal.corp"}); // does not match
  19957. auto res = cli->Get("/");
  19958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19959. EXPECT_GE(s.proxy_hits(), 1);
  19960. EXPECT_TRUE(s.last_had_proxy_authz());
  19961. }
  19962. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19963. ProxyAndTargetServers s;
  19964. auto cli = make_client("anything.test", s);
  19965. auto res = cli->Get("/");
  19966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19967. EXPECT_GE(s.proxy_hits(), 1);
  19968. EXPECT_EQ(0, s.target_hits());
  19969. }
  19970. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19971. ProxyAndTargetServers s;
  19972. auto cli = make_client("example.com", s);
  19973. cli->set_no_proxy({"example.com:8080"});
  19974. auto res = cli->Get("/");
  19975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19976. EXPECT_GE(s.proxy_hits(), 1);
  19977. EXPECT_EQ(0, s.target_hits());
  19978. }
  19979. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19980. ProxyAndTargetServers s;
  19981. auto cli = make_client("anything.test", s);
  19982. cli->set_no_proxy({"", " ", "\t"});
  19983. auto res = cli->Get("/");
  19984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19985. EXPECT_GE(s.proxy_hits(), 1);
  19986. EXPECT_EQ(0, s.target_hits());
  19987. }
  19988. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19989. // An entry with leading/trailing whitespace must still match — env-style
  19990. // values are commonly pasted with stray spaces and an implementation
  19991. // that feeds the raw token directly to inet_pton would fail to match
  19992. // valid CIDRs because of the spaces.
  19993. ProxyAndTargetServers s;
  19994. Client cli("127.0.0.1", s.target_port());
  19995. cli.set_proxy("127.0.0.1", s.proxy_port());
  19996. cli.set_no_proxy({" 127.0.0.0/8 "});
  19997. auto res = cli.Get("/");
  19998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19999. EXPECT_EQ(0, s.proxy_hits());
  20000. EXPECT_EQ(1, s.target_hits());
  20001. }
  20002. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20003. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20004. // go direct and must NOT carry Proxy-Authorization.
  20005. std::atomic<int> proxy_hits{0};
  20006. std::atomic<int> target_hits{0};
  20007. std::atomic<bool> target_saw_authz{false};
  20008. no_proxy_test::ScopedServer proxy_mock, target;
  20009. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20010. proxy_hits++;
  20011. res.status = 302;
  20012. res.set_header("Location", "http://127.0.0.1:" +
  20013. std::to_string(target.port()) + "/landed");
  20014. });
  20015. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20016. target_hits++;
  20017. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20018. res.set_content("direct", "text/plain");
  20019. });
  20020. proxy_mock.listen();
  20021. target.listen();
  20022. Client cli("public.example", target.port());
  20023. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20024. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20025. cli.set_proxy_basic_auth("u", "p");
  20026. cli.set_no_proxy({"127.0.0.1"});
  20027. cli.set_follow_location(true);
  20028. auto res = cli.Get("/redir");
  20029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20030. EXPECT_GE(proxy_hits.load(), 1);
  20031. EXPECT_GE(target_hits.load(), 1);
  20032. EXPECT_FALSE(target_saw_authz.load());
  20033. }
  20034. #ifdef CPPHTTPLIB_SSL_ENABLED
  20035. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20036. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20037. // proxy creds would be sent to the (possibly hostile) origin.
  20038. std::atomic<int> target_hits{0};
  20039. std::atomic<bool> target_saw_proxy_authz{false};
  20040. no_proxy_test::ScopedServer target;
  20041. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20042. target_hits++;
  20043. if (req.has_header("Proxy-Authorization")) {
  20044. target_saw_proxy_authz = true;
  20045. }
  20046. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20047. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20048. "nonce=\"abc\", algorithm=MD5");
  20049. });
  20050. target.listen();
  20051. // The proxy address is set to the target's port: the bypass MUST kick in;
  20052. // if it doesn't, the test still routes "via proxy" to the same server and
  20053. // the Proxy-Authorization assertion below catches the leak.
  20054. Client cli("evil.example", target.port());
  20055. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20056. cli.set_proxy("127.0.0.1", target.port());
  20057. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20058. cli.set_no_proxy({"evil.example"});
  20059. auto res = cli.Get("/x");
  20060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20061. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20062. EXPECT_EQ(1, target_hits.load());
  20063. EXPECT_FALSE(target_saw_proxy_authz.load());
  20064. }
  20065. #endif
  20066. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20067. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20068. std::atomic<int> proxy_hits{0};
  20069. std::atomic<int> bypass_hits{0};
  20070. std::atomic<bool> proxy_saw_c_url{false};
  20071. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20072. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20073. proxy_hits++;
  20074. if (req.path.find("/start") != std::string::npos) {
  20075. res.status = 302;
  20076. res.set_header("Location", "http://127.0.0.1:" +
  20077. std::to_string(bypass_server.port()) +
  20078. "/middle");
  20079. return;
  20080. }
  20081. if (req.path.find("/end") != std::string::npos) {
  20082. proxy_saw_c_url = true;
  20083. res.set_content("c-via-proxy", "text/plain");
  20084. return;
  20085. }
  20086. res.set_content("unexpected", "text/plain");
  20087. });
  20088. // public.example's "advertised" port is arbitrary (the request never lands
  20089. // there — it goes through the proxy), but use a dynamic value to stay
  20090. // friendly with sharded parallel runs.
  20091. int public_port = bypass_server.port();
  20092. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20093. bypass_hits++;
  20094. res.status = 302;
  20095. res.set_header("Location", "http://public.example:" +
  20096. std::to_string(public_port) + "/end");
  20097. });
  20098. proxy_mock.listen();
  20099. bypass_server.listen();
  20100. Client cli("public.example", public_port);
  20101. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20102. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20103. cli.set_no_proxy({"127.0.0.1"});
  20104. cli.set_follow_location(true);
  20105. auto res = cli.Get("/start");
  20106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20107. EXPECT_EQ(StatusCode::OK_200, res->status);
  20108. EXPECT_EQ("c-via-proxy", res->body);
  20109. EXPECT_GE(proxy_hits.load(), 2);
  20110. EXPECT_GE(bypass_hits.load(), 1);
  20111. EXPECT_TRUE(proxy_saw_c_url.load());
  20112. }
  20113. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20114. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20115. // request reconnects to the correct endpoint.
  20116. std::atomic<int> proxy_hits{0};
  20117. std::atomic<int> target_hits{0};
  20118. no_proxy_test::ScopedServer proxy_mock, target;
  20119. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20120. proxy_hits++;
  20121. res.set_content("via-proxy", "text/plain");
  20122. });
  20123. target.svr().Get(".*", [&](const Request &, Response &res) {
  20124. target_hits++;
  20125. res.set_content("direct", "text/plain");
  20126. });
  20127. proxy_mock.listen();
  20128. target.listen();
  20129. Client cli("public.example", target.port());
  20130. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20131. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20132. cli.set_keep_alive(true);
  20133. auto res1 = cli.Get("/a");
  20134. ASSERT_TRUE(res1);
  20135. EXPECT_EQ("via-proxy", res1->body);
  20136. EXPECT_EQ(1, proxy_hits.load());
  20137. EXPECT_EQ(0, target_hits.load());
  20138. cli.set_no_proxy({"public.example"});
  20139. auto res2 = cli.Get("/b");
  20140. ASSERT_TRUE(res2);
  20141. EXPECT_EQ("direct", res2->body);
  20142. EXPECT_EQ(1, proxy_hits.load());
  20143. EXPECT_EQ(1, target_hits.load());
  20144. }
  20145. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20146. namespace proxy_tunnel_test {
  20147. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20148. class ScopedSSLServer {
  20149. public:
  20150. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20151. port_ = svr_.bind_to_any_port("127.0.0.1");
  20152. }
  20153. ~ScopedSSLServer() {
  20154. svr_.stop();
  20155. if (th_.joinable()) { th_.join(); }
  20156. }
  20157. SSLServer &svr() { return svr_; }
  20158. int port() const { return port_; }
  20159. void listen() {
  20160. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20161. svr_.wait_until_ready();
  20162. }
  20163. private:
  20164. SSLServer svr_;
  20165. std::thread th_;
  20166. int port_ = 0;
  20167. };
  20168. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20169. class ScopedConnectProxy {
  20170. public:
  20171. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20172. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20173. if (listen_fd_ < 0) { return; }
  20174. int yes = 1;
  20175. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20176. sockaddr_in a{};
  20177. a.sin_family = AF_INET;
  20178. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20179. a.sin_port = 0;
  20180. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20181. return;
  20182. }
  20183. socklen_t alen = sizeof(a);
  20184. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20185. 0) {
  20186. return;
  20187. }
  20188. port_ = ntohs(a.sin_port);
  20189. if (::listen(listen_fd_, 1) != 0) { return; }
  20190. th_ = std::thread([this] { run(); });
  20191. }
  20192. ~ScopedConnectProxy() {
  20193. stop_ = true;
  20194. if (listen_fd_ >= 0) {
  20195. ::shutdown(listen_fd_, SHUT_RDWR);
  20196. ::close(listen_fd_);
  20197. }
  20198. if (th_.joinable()) { th_.join(); }
  20199. }
  20200. int port() const { return port_; }
  20201. int connect_hits() const { return connect_hits_.load(); }
  20202. private:
  20203. void run() {
  20204. while (!stop_.load()) {
  20205. fd_set rfds;
  20206. FD_ZERO(&rfds);
  20207. FD_SET(listen_fd_, &rfds);
  20208. timeval tv{0, 100 * 1000};
  20209. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20210. if (sel <= 0) { continue; }
  20211. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20212. if (client_fd < 0) { continue; }
  20213. std::string req;
  20214. char buf[2048];
  20215. while (req.find("\r\n\r\n") == std::string::npos) {
  20216. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20217. if (n <= 0) { break; }
  20218. req.append(buf, static_cast<size_t>(n));
  20219. }
  20220. if (req.compare(0, 7, "CONNECT") != 0) {
  20221. ::close(client_fd);
  20222. continue;
  20223. }
  20224. connect_hits_++;
  20225. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20226. ::send(client_fd, ok, std::strlen(ok), 0);
  20227. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20228. sockaddr_in o{};
  20229. o.sin_family = AF_INET;
  20230. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20231. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20232. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20233. 0) {
  20234. ::close(client_fd);
  20235. ::close(origin_fd);
  20236. continue;
  20237. }
  20238. auto forward = [](int from, int to) {
  20239. char b[8192];
  20240. for (;;) {
  20241. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20242. if (n <= 0) { break; }
  20243. ssize_t off = 0;
  20244. while (off < n) {
  20245. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20246. if (s <= 0) {
  20247. off = n;
  20248. break;
  20249. }
  20250. off += s;
  20251. }
  20252. }
  20253. ::shutdown(to, SHUT_WR);
  20254. };
  20255. std::thread t1([&] { forward(client_fd, origin_fd); });
  20256. std::thread t2([&] { forward(origin_fd, client_fd); });
  20257. t1.join();
  20258. t2.join();
  20259. ::close(client_fd);
  20260. ::close(origin_fd);
  20261. }
  20262. }
  20263. int forward_port_ = -1;
  20264. int listen_fd_ = -1;
  20265. int port_ = 0;
  20266. std::thread th_;
  20267. std::atomic<bool> stop_{false};
  20268. std::atomic<int> connect_hits_{0};
  20269. };
  20270. } // namespace proxy_tunnel_test
  20271. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20272. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20273. // retry; otherwise proxy creds would be sent to the origin.
  20274. std::atomic<int> origin_hits{0};
  20275. std::atomic<bool> origin_saw_proxy_authz{false};
  20276. proxy_tunnel_test::ScopedSSLServer origin;
  20277. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20278. origin_hits++;
  20279. if (req.has_header("Proxy-Authorization")) {
  20280. origin_saw_proxy_authz = true;
  20281. }
  20282. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20283. res.set_header("Proxy-Authenticate",
  20284. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20285. "algorithm=MD5");
  20286. });
  20287. origin.listen();
  20288. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20289. ASSERT_NE(0, proxy.port());
  20290. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20291. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20292. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20293. // and answer with its own status, making this test flaky.
  20294. SSLClient cli("127.0.0.1", origin.port());
  20295. cli.enable_server_certificate_verification(false);
  20296. cli.set_proxy("127.0.0.1", proxy.port());
  20297. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20298. auto res = cli.Get("/x");
  20299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20300. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20301. EXPECT_EQ(1, origin_hits.load());
  20302. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20303. EXPECT_EQ(1, proxy.connect_hits());
  20304. }
  20305. #endif