1
0

test.cc 780 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298
  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, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  8512. // A provider reaching a pass with nothing to hand over - an empty buffer
  8513. // popped off a queue, say - must not be taken to mean the body is finished.
  8514. // It used to end the loop with the terminating chunk unwritten while the
  8515. // server still considered the response complete, so the peer waited for an
  8516. // end that never arrived.
  8517. Server svr;
  8518. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8519. auto step = std::make_shared<int>(0);
  8520. res.set_chunked_content_provider("text/plain",
  8521. [step](size_t /*offset*/, DataSink &sink) {
  8522. switch ((*step)++) {
  8523. case 0: sink.write("", 0); break;
  8524. case 1: sink.write("hello", 5); break;
  8525. default: sink.done(); break;
  8526. }
  8527. return true;
  8528. });
  8529. });
  8530. auto port = svr.bind_to_any_port(HOST);
  8531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8532. auto listen_se = detail::scope_exit([&] {
  8533. svr.stop();
  8534. listen_thread.join();
  8535. ASSERT_FALSE(svr.is_running());
  8536. });
  8537. svr.wait_until_ready();
  8538. Client cli(HOST, port);
  8539. // Without the fix the body is never terminated, so bound the wait rather
  8540. // than letting the test hang on the default read timeout.
  8541. cli.set_read_timeout(5, 0);
  8542. auto res = cli.Get("/stream");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::OK_200, res->status);
  8545. EXPECT_EQ("hello", res->body);
  8546. }
  8547. TEST(StreamingTest, NoContentLengthStreaming) {
  8548. Server svr;
  8549. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8550. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8551. if (offset < 6) {
  8552. sink.os << (offset < 3 ? "a" : "b");
  8553. } else {
  8554. sink.done();
  8555. }
  8556. return true;
  8557. });
  8558. });
  8559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8560. auto listen_se = detail::scope_exit([&] {
  8561. svr.stop();
  8562. listen_thread.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. Client client(HOST, PORT);
  8567. auto get_thread = std::thread([&client]() {
  8568. std::string s;
  8569. auto res =
  8570. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8571. s += std::string(data, len);
  8572. return true;
  8573. });
  8574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8575. EXPECT_EQ(StatusCode::OK_200, res->status);
  8576. EXPECT_EQ("aaabbb", s);
  8577. });
  8578. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8579. // Give GET time to get a few messages.
  8580. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8581. }
  8582. TEST(MountTest, Unmount) {
  8583. Server svr;
  8584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8585. auto se = detail::scope_exit([&] {
  8586. svr.stop();
  8587. listen_thread.join();
  8588. ASSERT_FALSE(svr.is_running());
  8589. });
  8590. svr.wait_until_ready();
  8591. Client cli("localhost", PORT);
  8592. svr.set_mount_point("/mount2", "./www2");
  8593. auto res = cli.Get("/");
  8594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8596. res = cli.Get("/mount2/dir/test.html");
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. EXPECT_EQ(StatusCode::OK_200, res->status);
  8599. svr.set_mount_point("/", "./www");
  8600. res = cli.Get("/dir/");
  8601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8602. EXPECT_EQ(StatusCode::OK_200, res->status);
  8603. svr.remove_mount_point("/");
  8604. res = cli.Get("/dir/");
  8605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8606. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8607. svr.remove_mount_point("/mount2");
  8608. res = cli.Get("/mount2/dir/test.html");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8611. }
  8612. TEST(MountTest, PathSegmentBoundary) {
  8613. Server svr;
  8614. svr.set_mount_point("/mount2", "./www2");
  8615. svr.set_mount_point("/", "./www");
  8616. auto port = svr.bind_to_any_port(HOST);
  8617. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8618. auto se = detail::scope_exit([&] {
  8619. svr.stop();
  8620. listen_thread.join();
  8621. ASSERT_FALSE(svr.is_running());
  8622. });
  8623. svr.wait_until_ready();
  8624. Client cli(HOST, port);
  8625. auto res = cli.Get("/mount2/dir/test.html");
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. // "/mount2" must not match part-way through a path segment.
  8629. res = cli.Get("/mount2dir/test.html");
  8630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8631. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8632. // A mount point ending in '/' keeps matching every path below it.
  8633. res = cli.Get("/dir/test.html");
  8634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. TEST(MountTest, Redicect) {
  8638. Server svr;
  8639. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. listen_thread.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. });
  8645. svr.set_mount_point("/", "./www");
  8646. svr.wait_until_ready();
  8647. Client cli("localhost", PORT);
  8648. auto res = cli.Get("/dir/");
  8649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8650. EXPECT_EQ(StatusCode::OK_200, res->status);
  8651. res = cli.Get("/dir");
  8652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8653. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8654. res = cli.Get("/file");
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. res = cli.Get("/file/");
  8658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8659. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8660. cli.set_follow_location(true);
  8661. res = cli.Get("/dir");
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. }
  8665. TEST(MountTest, MultibytesPathName) {
  8666. Server svr;
  8667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8668. auto se = detail::scope_exit([&] {
  8669. svr.stop();
  8670. listen_thread.join();
  8671. ASSERT_FALSE(svr.is_running());
  8672. });
  8673. svr.set_mount_point("/", "./www");
  8674. svr.wait_until_ready();
  8675. Client cli("localhost", PORT);
  8676. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8680. }
  8681. #ifdef _WIN32
  8682. // Issue #2435: mmap::open() must succeed even when another handle holds
  8683. // the file open for writing (e.g. an active log file).
  8684. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8685. const char *path = "mmap_concurrent_writer_test.txt";
  8686. const char *content = "hello";
  8687. {
  8688. std::ofstream f(path, std::ios::binary);
  8689. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8690. }
  8691. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8692. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8693. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8694. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8695. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8696. detail::mmap m(path);
  8697. ASSERT_TRUE(m.is_open());
  8698. EXPECT_EQ(strlen(content), m.size());
  8699. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8700. }
  8701. #endif
  8702. #ifndef _WIN32
  8703. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8704. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8705. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8706. TEST(MmapTest, FailedMappingIsNotOpen) {
  8707. const char *path = "./mmap_failed_mapping_test_dir";
  8708. ASSERT_EQ(0, ::mkdir(path, 0755));
  8709. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8710. detail::mmap m(path);
  8711. EXPECT_FALSE(m.is_open());
  8712. EXPECT_EQ(0U, m.size());
  8713. EXPECT_NE(static_cast<const void *>(m.data()),
  8714. static_cast<const void *>(MAP_FAILED));
  8715. }
  8716. #endif
  8717. TEST(KeepAliveTest, ReadTimeout) {
  8718. Server svr;
  8719. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8720. std::this_thread::sleep_for(std::chrono::seconds(2));
  8721. res.set_content("a", "text/plain");
  8722. });
  8723. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8724. res.set_content("b", "text/plain");
  8725. });
  8726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8727. auto se = detail::scope_exit([&] {
  8728. svr.stop();
  8729. listen_thread.join();
  8730. ASSERT_FALSE(svr.is_running());
  8731. });
  8732. svr.wait_until_ready();
  8733. Client cli("localhost", PORT);
  8734. cli.set_keep_alive(true);
  8735. cli.set_read_timeout(std::chrono::seconds(1));
  8736. auto resa = cli.Get("/a");
  8737. ASSERT_FALSE(resa);
  8738. EXPECT_EQ(Error::Read, resa.error());
  8739. auto resb = cli.Get("/b");
  8740. ASSERT_TRUE(resb);
  8741. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8742. EXPECT_EQ("b", resb->body);
  8743. }
  8744. TEST(KeepAliveTest, MaxCount) {
  8745. size_t keep_alive_max_count = 3;
  8746. Server svr;
  8747. svr.set_keep_alive_max_count(keep_alive_max_count);
  8748. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8749. res.set_content("Hello World!", "text/plain");
  8750. });
  8751. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8752. auto se = detail::scope_exit([&] {
  8753. svr.stop();
  8754. listen_thread.join();
  8755. ASSERT_FALSE(svr.is_running());
  8756. });
  8757. svr.wait_until_ready();
  8758. Client cli(HOST, PORT);
  8759. cli.set_keep_alive(true);
  8760. for (size_t i = 0; i < 5; i++) {
  8761. auto result = cli.Get("/hi");
  8762. ASSERT_TRUE(result);
  8763. EXPECT_EQ(StatusCode::OK_200, result->status);
  8764. if (i == keep_alive_max_count - 1) {
  8765. EXPECT_EQ("close", result->get_header_value("Connection"));
  8766. } else {
  8767. EXPECT_FALSE(result->has_header("Connection"));
  8768. }
  8769. }
  8770. }
  8771. TEST(KeepAliveTest, Issue1041) {
  8772. Server svr;
  8773. svr.set_keep_alive_timeout(3);
  8774. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8775. res.set_content("Hello World!", "text/plain");
  8776. });
  8777. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8778. auto se = detail::scope_exit([&] {
  8779. svr.stop();
  8780. listen_thread.join();
  8781. ASSERT_FALSE(svr.is_running());
  8782. });
  8783. svr.wait_until_ready();
  8784. Client cli(HOST, PORT);
  8785. cli.set_keep_alive(true);
  8786. auto result = cli.Get("/hi");
  8787. ASSERT_TRUE(result);
  8788. EXPECT_EQ(StatusCode::OK_200, result->status);
  8789. std::this_thread::sleep_for(std::chrono::seconds(5));
  8790. result = cli.Get("/hi");
  8791. ASSERT_TRUE(result);
  8792. EXPECT_EQ(StatusCode::OK_200, result->status);
  8793. }
  8794. TEST(KeepAliveTest, Issue1959) {
  8795. Server svr;
  8796. svr.set_keep_alive_timeout(5);
  8797. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8798. res.set_content("a", "text/plain");
  8799. });
  8800. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8801. auto se = detail::scope_exit([&] {
  8802. if (!svr.is_running()) return;
  8803. svr.stop();
  8804. listen_thread.join();
  8805. ASSERT_FALSE(svr.is_running());
  8806. });
  8807. svr.wait_until_ready();
  8808. Client cli("localhost", PORT);
  8809. cli.set_keep_alive(true);
  8810. using namespace std::chrono;
  8811. auto start = steady_clock::now();
  8812. cli.Get("/a");
  8813. svr.stop();
  8814. listen_thread.join();
  8815. auto end = steady_clock::now();
  8816. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8817. EXPECT_LT(elapsed, 5000);
  8818. }
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. TEST(KeepAliveTest, SSLClientReconnection) {
  8821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8822. ASSERT_TRUE(svr.is_valid());
  8823. svr.set_keep_alive_timeout(1);
  8824. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8825. res.set_content("Hello World!", "text/plain");
  8826. });
  8827. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8828. auto se = detail::scope_exit([&] {
  8829. svr.stop();
  8830. listen_thread.join();
  8831. ASSERT_FALSE(svr.is_running());
  8832. });
  8833. svr.wait_until_ready();
  8834. SSLClient cli(HOST, PORT);
  8835. cli.enable_server_certificate_verification(false);
  8836. cli.set_keep_alive(true);
  8837. auto result = cli.Get("/hi");
  8838. ASSERT_TRUE(result);
  8839. EXPECT_EQ(StatusCode::OK_200, result->status);
  8840. result = cli.Get("/hi");
  8841. ASSERT_TRUE(result);
  8842. EXPECT_EQ(StatusCode::OK_200, result->status);
  8843. std::this_thread::sleep_for(std::chrono::seconds(2));
  8844. // Recoonect
  8845. result = cli.Get("/hi");
  8846. ASSERT_TRUE(result);
  8847. EXPECT_EQ(StatusCode::OK_200, result->status);
  8848. result = cli.Get("/hi");
  8849. ASSERT_TRUE(result);
  8850. EXPECT_EQ(StatusCode::OK_200, result->status);
  8851. }
  8852. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8854. ASSERT_TRUE(svr.is_valid());
  8855. svr.set_keep_alive_timeout(1);
  8856. std::string content = "reconnect";
  8857. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8858. res.set_content("Hello World!", "text/plain");
  8859. });
  8860. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8861. auto se = detail::scope_exit([&] {
  8862. svr.stop();
  8863. listen_thread.join();
  8864. ASSERT_FALSE(svr.is_running());
  8865. });
  8866. svr.wait_until_ready();
  8867. SSLClient cli(HOST, PORT);
  8868. cli.enable_server_certificate_verification(false);
  8869. cli.set_keep_alive(true);
  8870. auto result = cli.Post(
  8871. "/hi", content.size(),
  8872. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8873. sink.write(content.c_str(), content.size());
  8874. return true;
  8875. },
  8876. "text/plain");
  8877. ASSERT_TRUE(result);
  8878. EXPECT_EQ(200, result->status);
  8879. std::this_thread::sleep_for(std::chrono::seconds(2));
  8880. // Recoonect
  8881. result = cli.Post(
  8882. "/hi", content.size(),
  8883. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8884. sink.write(content.c_str(), content.size());
  8885. return true;
  8886. },
  8887. "text/plain");
  8888. ASSERT_TRUE(result);
  8889. EXPECT_EQ(200, result->status);
  8890. result = cli.Post(
  8891. "/hi", content.size(),
  8892. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8893. sink.write(content.c_str(), content.size());
  8894. return true;
  8895. },
  8896. "text/plain");
  8897. ASSERT_TRUE(result);
  8898. EXPECT_EQ(200, result->status);
  8899. }
  8900. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8901. using namespace httplib::tls;
  8902. {
  8903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8904. ASSERT_TRUE(svr.is_valid());
  8905. svr.Get("/sni", [&](const Request &req, Response &res) {
  8906. std::string expected = req.sni();
  8907. EXPECT_EQ(expected, req.get_param_value("expected"));
  8908. res.set_content("ok", "text/plain");
  8909. });
  8910. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8911. auto se = detail::scope_exit([&] {
  8912. svr.stop();
  8913. listen_thread.join();
  8914. ASSERT_FALSE(svr.is_running());
  8915. });
  8916. svr.wait_until_ready();
  8917. {
  8918. SSLClient cli("localhost", PORT);
  8919. cli.enable_server_certificate_verification(false);
  8920. auto res = cli.Get("/sni?expected=localhost");
  8921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8922. }
  8923. {
  8924. SSLClient cli("::1", PORT);
  8925. cli.enable_server_certificate_verification(false);
  8926. auto res = cli.Get("/sni?expected=");
  8927. // NOTE: This may fail if the server is listening on IPv4 only
  8928. // (e.g., when localhost resolves to 127.0.0.1 only)
  8929. if (res) {
  8930. EXPECT_EQ(StatusCode::OK_200, res->status);
  8931. } else {
  8932. EXPECT_EQ(Error::Connection, res.error());
  8933. }
  8934. }
  8935. }
  8936. }
  8937. #endif
  8938. TEST(ClientProblemDetectionTest, ContentProvider) {
  8939. Server svr;
  8940. size_t content_length = 1024 * 1024;
  8941. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8942. res.set_content_provider(
  8943. content_length, "text/plain",
  8944. [&](size_t offset, size_t length, DataSink &sink) {
  8945. auto out_len = std::min(length, static_cast<size_t>(1024));
  8946. std::string out(out_len, '@');
  8947. sink.write(out.data(), out_len);
  8948. return offset < 4096;
  8949. },
  8950. [](bool success) { ASSERT_FALSE(success); });
  8951. });
  8952. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8953. res.set_content_provider(
  8954. 0, "text/plain",
  8955. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8956. EXPECT_TRUE(false);
  8957. return true;
  8958. },
  8959. [](bool success) { ASSERT_FALSE(success); });
  8960. });
  8961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8962. auto se = detail::scope_exit([&] {
  8963. svr.stop();
  8964. listen_thread.join();
  8965. ASSERT_FALSE(svr.is_running());
  8966. });
  8967. svr.wait_until_ready();
  8968. Client cli("localhost", PORT);
  8969. {
  8970. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8971. size_t /*data_length*/) { return false; });
  8972. ASSERT_FALSE(res);
  8973. }
  8974. {
  8975. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8976. size_t /*data_length*/) { return false; });
  8977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8978. }
  8979. }
  8980. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  8981. // A writer only has to assign `write`. The other three used to be left as
  8982. // empty std::functions, so a provider calling one threw
  8983. // std::bad_function_call out of the thread running it and took the whole
  8984. // process down.
  8985. DataSink sink;
  8986. std::string written;
  8987. sink.write = [&](const char *data, size_t data_len) {
  8988. written.append(data, data_len);
  8989. return true;
  8990. };
  8991. EXPECT_TRUE(sink.is_writable());
  8992. sink.done();
  8993. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  8994. EXPECT_TRUE(written.empty());
  8995. }
  8996. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  8997. // A sink that cannot carry trailers still has to finish.
  8998. DataSink sink;
  8999. auto done_count = 0;
  9000. sink.done = [&]() { done_count++; };
  9001. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9002. EXPECT_EQ(1, done_count);
  9003. }
  9004. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9005. Server svr;
  9006. const std::string body(4096, 'x');
  9007. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9008. res.set_content_provider(body.size(), "text/plain",
  9009. [&](size_t offset, size_t length, DataSink &sink) {
  9010. sink.write(body.data() + offset, length);
  9011. sink.done();
  9012. return true;
  9013. });
  9014. });
  9015. auto port = svr.bind_to_any_port(HOST);
  9016. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9017. auto se = detail::scope_exit([&] {
  9018. svr.stop();
  9019. listen_thread.join();
  9020. ASSERT_FALSE(svr.is_running());
  9021. });
  9022. svr.wait_until_ready();
  9023. Client cli(HOST, port);
  9024. auto res = cli.Get("/");
  9025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9026. EXPECT_EQ(StatusCode::OK_200, res->status);
  9027. EXPECT_EQ(body, res->body);
  9028. }
  9029. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9030. Server svr;
  9031. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9032. res.set_content_provider(
  9033. 1024, "text/plain",
  9034. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9035. sink.write("hello", 5);
  9036. sink.done(); // short of the 1024 bytes the response promised
  9037. return true;
  9038. });
  9039. });
  9040. auto port = svr.bind_to_any_port(HOST);
  9041. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9042. auto se = detail::scope_exit([&] {
  9043. svr.stop();
  9044. listen_thread.join();
  9045. ASSERT_FALSE(svr.is_running());
  9046. });
  9047. svr.wait_until_ready();
  9048. Client cli(HOST, port);
  9049. cli.set_read_timeout(5, 0);
  9050. // The response is short of its Content-Length, so the client cannot read a
  9051. // complete body. What matters is that this returns at all: a no-op done()
  9052. // would leave the writer looping over a provider that never makes progress.
  9053. auto res = cli.Get("/");
  9054. EXPECT_FALSE(res);
  9055. }
  9056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9057. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9058. // The compressed path builds the whole body before connecting, so this
  9059. // fails client-side and never reaches a server.
  9060. Client cli(HOST, PORT);
  9061. cli.set_compress(true);
  9062. auto res = cli.Post(
  9063. "/", 1024,
  9064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9065. sink.write("hello", 5);
  9066. sink.done(); // short of the 1024 bytes the request announced
  9067. return true;
  9068. },
  9069. "text/plain");
  9070. ASSERT_FALSE(res);
  9071. EXPECT_EQ(Error::Write, res.error());
  9072. }
  9073. #endif
  9074. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9075. Server svr;
  9076. svr.set_error_handler([](Request const &, Response &res) -> void {
  9077. res.set_chunked_content_provider(
  9078. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9079. sink.os << "hello";
  9080. sink.os << "world";
  9081. sink.done();
  9082. return true;
  9083. });
  9084. });
  9085. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9086. auto se = detail::scope_exit([&] {
  9087. svr.stop();
  9088. listen_thread.join();
  9089. ASSERT_FALSE(svr.is_running());
  9090. });
  9091. svr.wait_until_ready();
  9092. Client cli("localhost", PORT);
  9093. auto res = cli.Get("/");
  9094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9095. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9096. EXPECT_EQ("helloworld", res->body);
  9097. }
  9098. TEST(LongPollingTest, ClientCloseDetection) {
  9099. Server svr;
  9100. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9101. res.set_chunked_content_provider(
  9102. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9103. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9104. sink.os << "hello";
  9105. auto count = 10;
  9106. while (count > 0 && sink.is_writable()) {
  9107. this_thread::sleep_for(chrono::milliseconds(10));
  9108. count--;
  9109. }
  9110. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9111. return true;
  9112. });
  9113. });
  9114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9115. auto se = detail::scope_exit([&] {
  9116. svr.stop();
  9117. listen_thread.join();
  9118. ASSERT_FALSE(svr.is_running());
  9119. });
  9120. svr.wait_until_ready();
  9121. Client cli("localhost", PORT);
  9122. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9123. EXPECT_EQ("hello", string(data, data_length));
  9124. return false; // close the socket immediately.
  9125. });
  9126. ASSERT_FALSE(res);
  9127. }
  9128. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9129. Server svr;
  9130. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9131. res.set_chunked_content_provider(
  9132. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9133. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9134. sink.os << "hello";
  9135. EXPECT_TRUE(sink.os.good());
  9136. // Wait for the client to close the connection
  9137. auto count = 10;
  9138. while (count > 0 && sink.is_writable()) {
  9139. this_thread::sleep_for(chrono::milliseconds(10));
  9140. count--;
  9141. }
  9142. // After client disconnect, write repeatedly until the socket
  9143. // write actually fails (small writes may be absorbed by the
  9144. // kernel buffer)
  9145. std::string chunk(1024, 'x');
  9146. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9147. sink.os << chunk;
  9148. }
  9149. EXPECT_TRUE(sink.os.fail());
  9150. return true;
  9151. });
  9152. });
  9153. auto port = svr.bind_to_any_port("localhost");
  9154. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  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. Client cli("localhost", port);
  9162. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9163. EXPECT_EQ("hello", string(data, data_length));
  9164. return false; // close the socket immediately.
  9165. });
  9166. ASSERT_FALSE(res);
  9167. }
  9168. TEST(GetWithParametersTest, GetWithParameters) {
  9169. Server svr;
  9170. svr.Get("/", [&](const Request &req, Response &) {
  9171. EXPECT_EQ("world", req.get_param_value("hello"));
  9172. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9173. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9174. });
  9175. svr.Get("/params", [&](const Request &req, Response &) {
  9176. EXPECT_EQ("world", req.get_param_value("hello"));
  9177. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9178. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9179. });
  9180. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9181. EXPECT_EQ("resource-id", req.matches[1]);
  9182. EXPECT_EQ("foo", req.get_param_value("param1"));
  9183. EXPECT_EQ("bar", req.get_param_value("param2"));
  9184. });
  9185. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9186. EXPECT_EQ("user-id", req.path_params.at("id"));
  9187. EXPECT_EQ("foo", req.get_param_value("param1"));
  9188. EXPECT_EQ("bar", req.get_param_value("param2"));
  9189. });
  9190. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. listen_thread.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. {
  9198. Client cli(HOST, PORT);
  9199. Params params;
  9200. params.emplace("hello", "world");
  9201. params.emplace("hello2", "world2");
  9202. params.emplace("hello3", "world3");
  9203. auto res = cli.Get("/", params, Headers{});
  9204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9205. EXPECT_EQ(StatusCode::OK_200, res->status);
  9206. }
  9207. {
  9208. Client cli(HOST, PORT);
  9209. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9211. EXPECT_EQ(StatusCode::OK_200, res->status);
  9212. }
  9213. {
  9214. Client cli(HOST, PORT);
  9215. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9217. EXPECT_EQ(StatusCode::OK_200, res->status);
  9218. }
  9219. {
  9220. Client cli(HOST, PORT);
  9221. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. }
  9225. }
  9226. TEST(GetWithParametersTest, GetWithParameters2) {
  9227. Server svr;
  9228. svr.Get("/", [&](const Request &req, Response &res) {
  9229. auto text = req.get_param_value("hello");
  9230. res.set_content(text, "text/plain");
  9231. });
  9232. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9233. auto se = detail::scope_exit([&] {
  9234. svr.stop();
  9235. listen_thread.join();
  9236. ASSERT_FALSE(svr.is_running());
  9237. });
  9238. svr.wait_until_ready();
  9239. Client cli("localhost", PORT);
  9240. Params params;
  9241. params.emplace("hello", "world");
  9242. std::string body;
  9243. auto res = cli.Get("/", params, Headers{},
  9244. [&](const char *data, size_t data_length) {
  9245. body.append(data, data_length);
  9246. return true;
  9247. });
  9248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9249. EXPECT_EQ(StatusCode::OK_200, res->status);
  9250. EXPECT_EQ("world", body);
  9251. }
  9252. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9253. Server svr;
  9254. svr.Get("/search", [&](const Request &req, Response &res) {
  9255. auto q = req.get_param_value("q");
  9256. res.set_content(q, "text/plain");
  9257. });
  9258. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9259. auto se = detail::scope_exit([&] {
  9260. svr.stop();
  9261. listen_thread.join();
  9262. ASSERT_FALSE(svr.is_running());
  9263. });
  9264. svr.wait_until_ready();
  9265. Client cli("localhost", PORT);
  9266. // Verify that Get(path, params) works without requiring Headers argument
  9267. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9269. EXPECT_EQ(StatusCode::OK_200, res->status);
  9270. EXPECT_EQ("cpp-httplib", res->body);
  9271. }
  9272. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9273. auto host = "httpbingo.org";
  9274. auto path = std::string{"/range/32"};
  9275. #ifdef CPPHTTPLIB_SSL_ENABLED
  9276. SSLClient cli(host);
  9277. #else
  9278. Client cli(host);
  9279. #endif
  9280. cli.set_default_headers({make_range_header({{1, 10}})});
  9281. cli.set_connection_timeout(5);
  9282. {
  9283. auto res = cli.Get(path);
  9284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9285. EXPECT_EQ("bcdefghijk", res->body);
  9286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9287. }
  9288. {
  9289. auto res = cli.Get(path);
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ("bcdefghijk", res->body);
  9292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9293. }
  9294. }
  9295. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9296. Server svr;
  9297. svr.set_default_headers({{"Hello", "World"}});
  9298. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9299. res.set_content("ok", "text/plain");
  9300. });
  9301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9302. auto se = detail::scope_exit([&] {
  9303. svr.stop();
  9304. listen_thread.join();
  9305. ASSERT_FALSE(svr.is_running());
  9306. });
  9307. svr.wait_until_ready();
  9308. Client cli("localhost", PORT);
  9309. auto res = cli.Get("/");
  9310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9311. EXPECT_EQ(StatusCode::OK_200, res->status);
  9312. EXPECT_EQ("ok", res->body);
  9313. EXPECT_EQ("World", res->get_header_value("Hello"));
  9314. }
  9315. #ifdef CPPHTTPLIB_SSL_ENABLED
  9316. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9318. ASSERT_TRUE(svr.is_valid());
  9319. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9320. std::this_thread::sleep_for(std::chrono::seconds(2));
  9321. res.set_content("a", "text/plain");
  9322. });
  9323. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9324. res.set_content("b", "text/plain");
  9325. });
  9326. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9327. auto se = detail::scope_exit([&] {
  9328. svr.stop();
  9329. listen_thread.join();
  9330. ASSERT_FALSE(svr.is_running());
  9331. });
  9332. svr.wait_until_ready();
  9333. SSLClient cli("localhost", PORT);
  9334. cli.enable_server_certificate_verification(false);
  9335. cli.set_keep_alive(true);
  9336. cli.set_read_timeout(std::chrono::seconds(1));
  9337. auto resa = cli.Get("/a");
  9338. ASSERT_TRUE(!resa);
  9339. EXPECT_EQ(Error::Read, resa.error());
  9340. auto resb = cli.Get("/b");
  9341. ASSERT_TRUE(resb);
  9342. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9343. EXPECT_EQ("b", resb->body);
  9344. }
  9345. #endif
  9346. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9347. protected:
  9348. ServerTestWithAI_PASSIVE()
  9349. : cli_(HOST, PORT)
  9350. #ifdef CPPHTTPLIB_SSL_ENABLED
  9351. ,
  9352. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9353. #endif
  9354. {
  9355. #ifdef CPPHTTPLIB_SSL_ENABLED
  9356. cli_.enable_server_certificate_verification(false);
  9357. #endif
  9358. }
  9359. virtual void SetUp() {
  9360. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9361. res.set_content("Hello World!", "text/plain");
  9362. });
  9363. t_ = thread(
  9364. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9365. svr_.wait_until_ready();
  9366. }
  9367. virtual void TearDown() {
  9368. svr_.stop();
  9369. t_.join();
  9370. }
  9371. #ifdef CPPHTTPLIB_SSL_ENABLED
  9372. SSLClient cli_;
  9373. SSLServer svr_;
  9374. #else
  9375. Client cli_;
  9376. Server svr_;
  9377. #endif
  9378. thread t_;
  9379. };
  9380. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9381. auto res = cli_.Get("/hi");
  9382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9383. EXPECT_EQ(StatusCode::OK_200, res->status);
  9384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9385. EXPECT_EQ("Hello World!", res->body);
  9386. }
  9387. class ServerUpDownTest : public ::testing::Test {
  9388. protected:
  9389. ServerUpDownTest() : cli_(HOST, PORT) {}
  9390. virtual void SetUp() {
  9391. t_ = thread([&]() {
  9392. svr_.bind_to_any_port(HOST);
  9393. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9394. ASSERT_TRUE(svr_.listen_after_bind());
  9395. });
  9396. svr_.wait_until_ready();
  9397. }
  9398. virtual void TearDown() {
  9399. svr_.stop();
  9400. t_.join();
  9401. }
  9402. Client cli_;
  9403. Server svr_;
  9404. thread t_;
  9405. };
  9406. TEST_F(ServerUpDownTest, QuickStartStop) {
  9407. // Should not crash, especially when run with
  9408. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9409. }
  9410. class PayloadMaxLengthTest : public ::testing::Test {
  9411. protected:
  9412. PayloadMaxLengthTest()
  9413. : cli_(HOST, PORT)
  9414. #ifdef CPPHTTPLIB_SSL_ENABLED
  9415. ,
  9416. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9417. #endif
  9418. {
  9419. #ifdef CPPHTTPLIB_SSL_ENABLED
  9420. cli_.enable_server_certificate_verification(false);
  9421. #endif
  9422. }
  9423. virtual void SetUp() {
  9424. svr_.set_payload_max_length(8);
  9425. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9426. res.set_content("test", "text/plain");
  9427. });
  9428. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9429. svr_.wait_until_ready();
  9430. }
  9431. virtual void TearDown() {
  9432. svr_.stop();
  9433. t_.join();
  9434. }
  9435. #ifdef CPPHTTPLIB_SSL_ENABLED
  9436. SSLClient cli_;
  9437. SSLServer svr_;
  9438. #else
  9439. Client cli_;
  9440. Server svr_;
  9441. #endif
  9442. thread t_;
  9443. };
  9444. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9445. auto res = cli_.Post("/test", "123456789", "text/plain");
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9448. res = cli_.Post("/test", "12345678", "text/plain");
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. }
  9452. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9453. // Test chunked encoding with payload exceeding the 8-byte limit
  9454. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9455. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9458. }
  9459. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9460. // Test chunked encoding with payload within the 8-byte limit
  9461. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9462. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9464. EXPECT_EQ(StatusCode::OK_200, res->status);
  9465. }
  9466. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9467. // Test using send_request to send chunked data exceeding payload limit
  9468. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9469. "Host: " +
  9470. std::string(HOST) + ":" + std::to_string(PORT) +
  9471. "\r\n"
  9472. "Transfer-Encoding: chunked\r\n"
  9473. "Connection: close\r\n"
  9474. "\r\n"
  9475. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9476. "0123456789\r\n"
  9477. "0\r\n" // End chunk
  9478. "\r\n";
  9479. std::string response;
  9480. bool result = send_request(1, chunked_request, &response);
  9481. if (!result) {
  9482. // If send_request fails, it might be because the server closed the
  9483. // connection due to payload limit enforcement, which is acceptable
  9484. SUCCEED()
  9485. << "Server rejected oversized chunked request (connection closed)";
  9486. } else {
  9487. // If we got a response, check if it's an error response or connection was
  9488. // closed early Short response length indicates connection was closed due to
  9489. // payload limit
  9490. if (response.length() <= 10) {
  9491. SUCCEED() << "Server closed connection for oversized chunked request";
  9492. } else {
  9493. // Check for error status codes
  9494. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9495. response.find("Payload Too Large") != std::string::npos ||
  9496. response.find("400") != std::string::npos);
  9497. }
  9498. }
  9499. }
  9500. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9501. // Test request without Content-Length header exceeding payload limit
  9502. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9503. "Host: " +
  9504. std::string(HOST) + ":" +
  9505. std::to_string(PORT) +
  9506. "\r\n"
  9507. "Connection: close\r\n"
  9508. "\r\n";
  9509. // Add payload exceeding the 8-byte limit
  9510. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9511. request_without_content_length += large_payload;
  9512. std::string response;
  9513. bool result = send_request(1, request_without_content_length, &response);
  9514. if (!result) {
  9515. // If send_request fails, server likely closed connection due to payload
  9516. // limit
  9517. SUCCEED() << "Server rejected oversized request without Content-Length "
  9518. "(connection closed)";
  9519. } else {
  9520. // Check if server responded with error or closed connection early
  9521. if (response.length() <= 10) {
  9522. SUCCEED() << "Server closed connection for oversized request without "
  9523. "Content-Length";
  9524. } else {
  9525. // Check for error status codes
  9526. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9527. response.find("Payload Too Large") != std::string::npos ||
  9528. response.find("400") != std::string::npos);
  9529. }
  9530. }
  9531. }
  9532. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9533. // Test request without Content-Length header within payload limit
  9534. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9535. "Host: " +
  9536. std::string(HOST) + ":" +
  9537. std::to_string(PORT) +
  9538. "\r\n"
  9539. "Connection: close\r\n"
  9540. "\r\n";
  9541. // Add payload within the 8-byte limit
  9542. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9543. request_without_content_length += small_payload;
  9544. std::string response;
  9545. bool result = send_request(1, request_without_content_length, &response);
  9546. // For requests without Content-Length, the server may have different behavior
  9547. // The key is that it should not reject due to payload limit for small
  9548. // payloads
  9549. if (result) {
  9550. // Check for any HTTP response (success or error, but not connection closed)
  9551. if (response.length() > 10) {
  9552. SUCCEED()
  9553. << "Server processed request without Content-Length within limit";
  9554. } else {
  9555. // Short response might indicate connection closed, which is acceptable
  9556. SUCCEED() << "Server closed connection for request without "
  9557. "Content-Length (acceptable behavior)";
  9558. }
  9559. } else {
  9560. // Connection failure might be due to protocol requirements
  9561. SUCCEED() << "Connection issue with request without Content-Length "
  9562. "(environment-specific)";
  9563. }
  9564. }
  9565. class LargePayloadMaxLengthTest : public ::testing::Test {
  9566. protected:
  9567. LargePayloadMaxLengthTest()
  9568. : cli_(HOST, PORT)
  9569. #ifdef CPPHTTPLIB_SSL_ENABLED
  9570. ,
  9571. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9572. #endif
  9573. {
  9574. #ifdef CPPHTTPLIB_SSL_ENABLED
  9575. cli_.enable_server_certificate_verification(false);
  9576. #endif
  9577. }
  9578. virtual void SetUp() {
  9579. // Set 10MB payload limit
  9580. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9581. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9582. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9583. res.set_content("Large payload test", "text/plain");
  9584. });
  9585. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9586. svr_.wait_until_ready();
  9587. }
  9588. virtual void TearDown() {
  9589. svr_.stop();
  9590. t_.join();
  9591. }
  9592. #ifdef CPPHTTPLIB_SSL_ENABLED
  9593. SSLClient cli_;
  9594. SSLServer svr_;
  9595. #else
  9596. Client cli_;
  9597. Server svr_;
  9598. #endif
  9599. thread t_;
  9600. };
  9601. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9602. // Test chunked encoding with payload within 10MB limit
  9603. std::string medium_payload(5 * 1024 * 1024,
  9604. 'A'); // 5MB payload, within 10MB limit
  9605. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9607. EXPECT_EQ(StatusCode::OK_200, res->status);
  9608. }
  9609. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9610. // Test chunked encoding with payload exceeding 10MB limit
  9611. std::string large_payload(12 * 1024 * 1024,
  9612. 'B'); // 12MB payload, exceeds 10MB limit
  9613. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9614. // Server may either return 413 or close the connection
  9615. if (res) {
  9616. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9617. } else {
  9618. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9619. }
  9620. }
  9621. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9622. // Test request without Content-Length header within 10MB limit
  9623. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9624. "Host: " +
  9625. std::string(HOST) + ":" +
  9626. std::to_string(PORT) +
  9627. "\r\n"
  9628. "Connection: close\r\n"
  9629. "\r\n";
  9630. // Add 1MB payload (within 10MB limit)
  9631. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9632. request_without_content_length += medium_payload;
  9633. std::string response;
  9634. bool result = send_request(5, request_without_content_length, &response);
  9635. if (result) {
  9636. // Should get a proper HTTP response for payloads within limit
  9637. if (response.length() > 10) {
  9638. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9639. "10MB limit";
  9640. } else {
  9641. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9642. "Content-Length)";
  9643. }
  9644. } else {
  9645. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9646. }
  9647. }
  9648. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9649. // Test request without Content-Length header exceeding 10MB limit
  9650. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9651. "Host: " +
  9652. std::string(HOST) + ":" +
  9653. std::to_string(PORT) +
  9654. "\r\n"
  9655. "Connection: close\r\n"
  9656. "\r\n";
  9657. // Add 12MB payload (exceeds 10MB limit)
  9658. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9659. request_without_content_length += large_payload;
  9660. std::string response;
  9661. bool result = send_request(10, request_without_content_length, &response);
  9662. if (!result) {
  9663. // Server should close connection due to payload limit
  9664. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9665. "(connection closed)";
  9666. } else {
  9667. // Check for error response
  9668. if (response.length() <= 10) {
  9669. SUCCEED()
  9670. << "Server closed connection for 12MB request exceeding 10MB limit";
  9671. } else {
  9672. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9673. response.find("Payload Too Large") != std::string::npos ||
  9674. response.find("400") != std::string::npos);
  9675. }
  9676. }
  9677. }
  9678. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9679. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9680. // path.
  9681. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9682. Server svr;
  9683. const size_t LIMIT = 64 * 1024; // 64KB
  9684. svr.set_payload_max_length(LIMIT);
  9685. size_t total = 0;
  9686. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9687. const ContentReader &content_reader) {
  9688. content_reader([&](const char * /*data*/, size_t len) {
  9689. total += len;
  9690. return true;
  9691. });
  9692. res.status = 200;
  9693. res.set_content("stream_ok", "text/plain");
  9694. });
  9695. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9696. auto se = detail::scope_exit([&] {
  9697. svr.stop();
  9698. thread.join();
  9699. ASSERT_FALSE(svr.is_running());
  9700. });
  9701. svr.wait_until_ready();
  9702. // Prepare 256KB raw data and gzip-compress it
  9703. std::string raw(256 * 1024, 'A');
  9704. std::string gz;
  9705. {
  9706. z_stream zs{};
  9707. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9708. Z_DEFAULT_STRATEGY);
  9709. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9710. zs.avail_in = static_cast<uInt>(raw.size());
  9711. char outbuf[4096];
  9712. int ret;
  9713. do {
  9714. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9715. zs.avail_out = sizeof(outbuf);
  9716. ret = deflate(&zs, Z_FINISH);
  9717. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9718. } while (ret != Z_STREAM_END);
  9719. deflateEnd(&zs);
  9720. }
  9721. Client cli(HOST, PORT);
  9722. cli.set_connection_timeout(std::chrono::seconds(5));
  9723. Headers headers = {{"Content-Encoding", "gzip"}};
  9724. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9725. "application/octet-stream");
  9726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9727. // Server must reject oversized decompressed payloads with 413.
  9728. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9729. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9730. EXPECT_LE(total, LIMIT);
  9731. }
  9732. #ifndef CPPHTTPLIB_SSL_ENABLED
  9733. // For a request with neither Content-Length nor Transfer-Encoding, the
  9734. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9735. // compressed wire bytes straight to the ContentReader without ever routing
  9736. // them through the decompressor, so payload_max_length_ only bounded the
  9737. // compressed size on the wire, not the decompressed size.
  9738. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9739. Server svr;
  9740. const size_t LIMIT = 64 * 1024; // 64KB
  9741. svr.set_payload_max_length(LIMIT);
  9742. size_t total = 0;
  9743. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9744. const ContentReader &content_reader) {
  9745. content_reader([&](const char * /*data*/, size_t len) {
  9746. total += len;
  9747. return true;
  9748. });
  9749. res.status = 200;
  9750. res.set_content("stream_ok", "text/plain");
  9751. });
  9752. auto port = svr.bind_to_any_port(HOST);
  9753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9754. auto se = detail::scope_exit([&] {
  9755. svr.stop();
  9756. thread.join();
  9757. ASSERT_FALSE(svr.is_running());
  9758. });
  9759. svr.wait_until_ready();
  9760. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9761. // StreamingGzipDecompression test above.
  9762. std::string raw(256 * 1024, 'A');
  9763. std::string gz;
  9764. {
  9765. httplib::detail::gzip_compressor compressor;
  9766. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9767. [&](const char *chunk, size_t len) {
  9768. gz.append(chunk, len);
  9769. return true;
  9770. });
  9771. ASSERT_TRUE(result);
  9772. }
  9773. // Send the gzip body over raw TCP with neither Content-Length nor
  9774. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9775. // kicks in.
  9776. std::string req = "POST /stream HTTP/1.1\r\n"
  9777. "Host: " +
  9778. std::string(HOST) + ":" + std::to_string(port) +
  9779. "\r\n"
  9780. "Content-Encoding: gzip\r\n"
  9781. "Connection: close\r\n"
  9782. "\r\n" +
  9783. gz;
  9784. std::string response;
  9785. ASSERT_TRUE(send_request(5, req, &response, port));
  9786. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9787. EXPECT_LE(total, LIMIT);
  9788. }
  9789. #endif
  9790. #endif
  9791. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9792. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9793. // the payload must be passed through untouched instead of being rejected.
  9794. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9795. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9796. Server svr;
  9797. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9798. res.set_content(body, "image/jpeg");
  9799. res.set_header("Content-Encoding", "UTF-8");
  9800. });
  9801. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9802. res.set_content(body, "image/jpeg");
  9803. res.set_header("Content-Encoding", "identity");
  9804. });
  9805. svr.Post("/echo", [](const Request &req, Response &res) {
  9806. res.set_content(req.body, "image/jpeg");
  9807. });
  9808. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. t.join();
  9812. ASSERT_FALSE(svr.is_running());
  9813. });
  9814. svr.wait_until_ready();
  9815. Client cli(HOST, PORT);
  9816. {
  9817. auto res = cli.Get("/image");
  9818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9819. EXPECT_EQ(StatusCode::OK_200, res->status);
  9820. EXPECT_EQ(body, res->body);
  9821. }
  9822. {
  9823. auto res = cli.Get("/identity");
  9824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9825. EXPECT_EQ(StatusCode::OK_200, res->status);
  9826. EXPECT_EQ(body, res->body);
  9827. }
  9828. {
  9829. // The same applies to a request body reaching the server.
  9830. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9831. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. EXPECT_EQ(body, res->body);
  9835. }
  9836. }
  9837. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9838. // gzip-encoded response even when the build has no zlib support.
  9839. static const char GZIPPED_HELLO_WORLD[] = {
  9840. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9841. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9842. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9843. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9844. // A content coding is a whole token, not something the field value merely
  9845. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9846. // as "fibre" look like Brotli, and turned a multi-coding value like
  9847. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9848. // it was never meant to see.
  9849. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9850. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9851. Server svr;
  9852. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9853. res.set_content(body, "image/jpeg");
  9854. res.set_header("Content-Encoding", "fibre");
  9855. });
  9856. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9857. res.set_content(body, "image/jpeg");
  9858. res.set_header("Content-Encoding", "gzip, br");
  9859. });
  9860. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9861. res.set_content(body, "image/jpeg");
  9862. res.set_header("Content-Encoding", "x-zstd-ish");
  9863. });
  9864. auto port = svr.bind_to_any_port(HOST);
  9865. thread t = thread([&]() { svr.listen_after_bind(); });
  9866. auto se = detail::scope_exit([&] {
  9867. svr.stop();
  9868. t.join();
  9869. ASSERT_FALSE(svr.is_running());
  9870. });
  9871. svr.wait_until_ready();
  9872. Client cli(HOST, port);
  9873. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9874. auto res = cli.Get(path);
  9875. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9876. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9877. // Not a coding we recognize, so the payload comes back untouched
  9878. EXPECT_EQ(body, res->body) << path;
  9879. }
  9880. }
  9881. // A content coding cpp-httplib recognizes but was not built with must be
  9882. // reported as such. Handing the still-compressed payload back to the caller
  9883. // would silently corrupt it.
  9884. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9885. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9886. Server svr;
  9887. // "image/jpeg" keeps the server from applying a content coding of its own,
  9888. // so the hand-crafted Content-Encoding below survives.
  9889. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9890. res.set_content(gzipped, "image/jpeg");
  9891. res.set_header("Content-Encoding", "gzip");
  9892. });
  9893. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9894. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9895. res.set_content(gzipped, "image/jpeg");
  9896. res.set_header("Content-Encoding", "GZIP");
  9897. });
  9898. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. t.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli(HOST, PORT);
  9906. {
  9907. auto res = cli.Get("/gzipped");
  9908. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9910. EXPECT_EQ("Hello World!", res->body);
  9911. #else
  9912. ASSERT_FALSE(res);
  9913. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9914. #endif
  9915. }
  9916. {
  9917. // open_stream() must behave the same way.
  9918. auto handle = cli.open_stream("GET", "/gzipped");
  9919. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9920. ASSERT_TRUE(handle.is_valid());
  9921. std::string received;
  9922. char buf[256];
  9923. ssize_t n;
  9924. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9925. received.append(buf, static_cast<size_t>(n));
  9926. }
  9927. EXPECT_EQ("Hello World!", received);
  9928. #else
  9929. EXPECT_FALSE(handle.is_valid());
  9930. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9931. #endif
  9932. }
  9933. {
  9934. // A differently-cased coding must not be mistaken for an unknown one, or
  9935. // the body would be handed back still compressed.
  9936. auto res = cli.Get("/gzipped-uppercase");
  9937. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9939. EXPECT_EQ("Hello World!", res->body);
  9940. #else
  9941. ASSERT_FALSE(res);
  9942. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9943. #endif
  9944. }
  9945. }
  9946. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9947. // the same message as the comma-joined one, so both have to be read the same
  9948. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9949. // single gzip coding, and a body the sender says was encoded twice was handed
  9950. // back after one pass, still compressed but presented as decoded.
  9951. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9952. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9953. Server svr;
  9954. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9955. res.set_content(body, "image/jpeg");
  9956. res.headers.emplace("Content-Encoding", "gzip");
  9957. res.headers.emplace("Content-Encoding", "gzip");
  9958. });
  9959. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9960. res.set_content(body, "image/jpeg");
  9961. res.set_header("Content-Encoding", "gzip, gzip");
  9962. });
  9963. auto port = svr.bind_to_any_port(HOST);
  9964. thread t = thread([&]() { svr.listen_after_bind(); });
  9965. auto se = detail::scope_exit([&] {
  9966. svr.stop();
  9967. t.join();
  9968. ASSERT_FALSE(svr.is_running());
  9969. });
  9970. svr.wait_until_ready();
  9971. Client cli(HOST, port);
  9972. // Two codings is not something cpp-httplib decodes, so both representations
  9973. // take the pass-through path rather than one of them being gunzipped once.
  9974. for (const char *path : {"/split", "/joined"}) {
  9975. auto res = cli.Get(path);
  9976. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9978. EXPECT_EQ(body, res->body) << path;
  9979. }
  9980. }
  9981. // Regression test for DoS vulnerability: a malicious server sending a response
  9982. // without Content-Length header must not cause unbounded memory consumption on
  9983. // the client side. The client should stop reading after a reasonable limit,
  9984. // similar to the server-side set_payload_max_length protection.
  9985. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9986. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9987. #ifndef _WIN32
  9988. signal(SIGPIPE, SIG_IGN);
  9989. #endif
  9990. auto server_thread = std::thread([] {
  9991. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9992. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9993. default_socket_options(srv);
  9994. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9996. sockaddr_in addr{};
  9997. addr.sin_family = AF_INET;
  9998. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9999. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10000. int opt = 1;
  10001. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10002. #ifdef _WIN32
  10003. reinterpret_cast<const char *>(&opt),
  10004. #else
  10005. &opt,
  10006. #endif
  10007. sizeof(opt));
  10008. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10009. ::listen(srv, 1);
  10010. sockaddr_in cli_addr{};
  10011. socklen_t cli_len = sizeof(cli_addr);
  10012. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10013. if (cli != INVALID_SOCKET) {
  10014. char buf[4096];
  10015. ::recv(cli, buf, sizeof(buf), 0);
  10016. // Malicious response: no Content-Length, no chunked encoding
  10017. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10018. "Connection: close\r\n"
  10019. "\r\n";
  10020. ::send(cli,
  10021. #ifdef _WIN32
  10022. static_cast<const char *>(response_header.c_str()),
  10023. static_cast<int>(response_header.size()),
  10024. #else
  10025. response_header.c_str(), response_header.size(),
  10026. #endif
  10027. 0);
  10028. // Send 10MB of data
  10029. std::string chunk(64 * 1024, 'A');
  10030. size_t total_sent = 0;
  10031. while (total_sent < MALICIOUS_DATA_SIZE) {
  10032. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10033. auto sent = ::send(cli,
  10034. #ifdef _WIN32
  10035. static_cast<const char *>(chunk.c_str()),
  10036. static_cast<int>(to_send),
  10037. #else
  10038. chunk.c_str(), to_send,
  10039. #endif
  10040. 0);
  10041. if (sent <= 0) break;
  10042. total_sent += static_cast<size_t>(sent);
  10043. }
  10044. detail::close_socket(cli);
  10045. }
  10046. detail::close_socket(srv);
  10047. });
  10048. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10049. size_t total_read = 0;
  10050. {
  10051. Client cli("127.0.0.1", PORT + 2);
  10052. cli.set_read_timeout(5, 0);
  10053. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10054. auto stream = cli.open_stream("GET", "/malicious");
  10055. ASSERT_TRUE(stream.is_valid());
  10056. char buffer[64 * 1024];
  10057. ssize_t n;
  10058. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10059. total_read += static_cast<size_t>(n);
  10060. }
  10061. } // StreamHandle and Client destroyed here, closing the socket
  10062. server_thread.join();
  10063. // With set_payload_max_length, the client must stop reading before consuming
  10064. // all 10MB. The read loop should be cut off at or near the configured limit.
  10065. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10066. << "Client read " << total_read << " bytes, exceeding the configured "
  10067. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10068. }
  10069. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10070. // the entire response body without truncation.
  10071. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10072. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10073. #ifndef _WIN32
  10074. signal(SIGPIPE, SIG_IGN);
  10075. #endif
  10076. auto server_thread = std::thread([] {
  10077. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10078. default_socket_options(srv);
  10079. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10081. sockaddr_in addr{};
  10082. addr.sin_family = AF_INET;
  10083. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10084. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10085. int opt = 1;
  10086. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10087. #ifdef _WIN32
  10088. reinterpret_cast<const char *>(&opt),
  10089. #else
  10090. &opt,
  10091. #endif
  10092. sizeof(opt));
  10093. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10094. ::listen(srv, 1);
  10095. sockaddr_in cli_addr{};
  10096. socklen_t cli_len = sizeof(cli_addr);
  10097. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10098. if (cli != INVALID_SOCKET) {
  10099. char buf[4096];
  10100. ::recv(cli, buf, sizeof(buf), 0);
  10101. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10102. "Connection: close\r\n"
  10103. "\r\n";
  10104. ::send(cli,
  10105. #ifdef _WIN32
  10106. static_cast<const char *>(response_header.c_str()),
  10107. static_cast<int>(response_header.size()),
  10108. #else
  10109. response_header.c_str(), response_header.size(),
  10110. #endif
  10111. 0);
  10112. std::string chunk(64 * 1024, 'A');
  10113. size_t total_sent = 0;
  10114. while (total_sent < DATA_SIZE) {
  10115. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10116. auto sent = ::send(cli,
  10117. #ifdef _WIN32
  10118. static_cast<const char *>(chunk.c_str()),
  10119. static_cast<int>(to_send),
  10120. #else
  10121. chunk.c_str(), to_send,
  10122. #endif
  10123. 0);
  10124. if (sent <= 0) break;
  10125. total_sent += static_cast<size_t>(sent);
  10126. }
  10127. #ifdef _WIN32
  10128. ::shutdown(cli, SD_SEND);
  10129. #else
  10130. ::shutdown(cli, SHUT_WR);
  10131. #endif
  10132. // Drain until the client closes its end, ensuring all data is delivered
  10133. char drain[1024];
  10134. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10135. detail::close_socket(cli);
  10136. }
  10137. detail::close_socket(srv);
  10138. });
  10139. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10140. size_t total_read = 0;
  10141. {
  10142. Client cli("127.0.0.1", PORT + 2);
  10143. cli.set_read_timeout(5, 0);
  10144. cli.set_payload_max_length(0); // 0 means no limit
  10145. auto stream = cli.open_stream("GET", "/data");
  10146. ASSERT_TRUE(stream.is_valid());
  10147. char buffer[64 * 1024];
  10148. ssize_t n;
  10149. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10150. total_read += static_cast<size_t>(n);
  10151. }
  10152. }
  10153. server_thread.join();
  10154. EXPECT_EQ(total_read, DATA_SIZE)
  10155. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10156. << " bytes without truncation, but only read " << total_read << " bytes.";
  10157. }
  10158. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10159. // enormous Content-Length must not cause the client to pre-allocate a huge
  10160. // response body buffer. The reservation is capped at payload_max_length_, and
  10161. // the read itself fails when the body exceeds the limit.
  10162. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10163. #ifndef _WIN32
  10164. signal(SIGPIPE, SIG_IGN);
  10165. #endif
  10166. auto server_thread = std::thread([] {
  10167. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10168. default_socket_options(srv);
  10169. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10170. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10171. sockaddr_in addr{};
  10172. addr.sin_family = AF_INET;
  10173. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10174. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10175. int opt = 1;
  10176. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10177. #ifdef _WIN32
  10178. reinterpret_cast<const char *>(&opt),
  10179. #else
  10180. &opt,
  10181. #endif
  10182. sizeof(opt));
  10183. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10184. ::listen(srv, 1);
  10185. sockaddr_in cli_addr{};
  10186. socklen_t cli_len = sizeof(cli_addr);
  10187. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10188. if (cli != INVALID_SOCKET) {
  10189. char buf[4096];
  10190. ::recv(cli, buf, sizeof(buf), 0);
  10191. // Malicious response: claim a 20GB body but send only a tiny payload.
  10192. std::string response = "HTTP/1.1 200 OK\r\n"
  10193. "Content-Length: 20000000000\r\n"
  10194. "\r\n"
  10195. "abc";
  10196. ::send(cli,
  10197. #ifdef _WIN32
  10198. static_cast<const char *>(response.c_str()),
  10199. static_cast<int>(response.size()),
  10200. #else
  10201. response.c_str(), response.size(),
  10202. #endif
  10203. 0);
  10204. detail::close_socket(cli);
  10205. }
  10206. detail::close_socket(srv);
  10207. });
  10208. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10209. {
  10210. Client cli("127.0.0.1", PORT + 2);
  10211. cli.set_read_timeout(5, 0);
  10212. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10213. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10214. // (server claims more bytes than payload_max_length permits), but it must
  10215. // not exhaust memory before getting there.
  10216. auto res = cli.Get("/malicious");
  10217. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10218. }
  10219. server_thread.join();
  10220. }
  10221. // Verify that content_receiver bypasses the default payload_max_length,
  10222. // allowing streaming downloads larger than 100MB without requiring an explicit
  10223. // set_payload_max_length call.
  10224. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10225. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10226. #ifndef _WIN32
  10227. signal(SIGPIPE, SIG_IGN);
  10228. #endif
  10229. auto server_thread = std::thread([] {
  10230. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10231. default_socket_options(srv);
  10232. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10233. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10234. sockaddr_in addr{};
  10235. addr.sin_family = AF_INET;
  10236. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10237. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10238. int opt = 1;
  10239. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10240. #ifdef _WIN32
  10241. reinterpret_cast<const char *>(&opt),
  10242. #else
  10243. &opt,
  10244. #endif
  10245. sizeof(opt));
  10246. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10247. ::listen(srv, 1);
  10248. sockaddr_in cli_addr{};
  10249. socklen_t cli_len = sizeof(cli_addr);
  10250. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10251. if (cli != INVALID_SOCKET) {
  10252. char buf[4096];
  10253. ::recv(cli, buf, sizeof(buf), 0);
  10254. // Response with Content-Length larger than default 100MB limit
  10255. auto content_length = std::to_string(DATA_SIZE);
  10256. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10257. "Content-Length: " +
  10258. content_length +
  10259. "\r\n"
  10260. "Connection: close\r\n"
  10261. "\r\n";
  10262. ::send(cli,
  10263. #ifdef _WIN32
  10264. static_cast<const char *>(response_header.c_str()),
  10265. static_cast<int>(response_header.size()),
  10266. #else
  10267. response_header.c_str(), response_header.size(),
  10268. #endif
  10269. 0);
  10270. std::string chunk(64 * 1024, 'A');
  10271. size_t total_sent = 0;
  10272. while (total_sent < DATA_SIZE) {
  10273. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10274. auto sent = ::send(cli,
  10275. #ifdef _WIN32
  10276. static_cast<const char *>(chunk.c_str()),
  10277. static_cast<int>(to_send),
  10278. #else
  10279. chunk.c_str(), to_send,
  10280. #endif
  10281. 0);
  10282. if (sent <= 0) break;
  10283. total_sent += static_cast<size_t>(sent);
  10284. }
  10285. detail::close_socket(cli);
  10286. }
  10287. detail::close_socket(srv);
  10288. });
  10289. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10290. size_t total_received = 0;
  10291. {
  10292. Client cli("127.0.0.1", PORT + 2);
  10293. cli.set_read_timeout(10, 0);
  10294. // Do NOT call set_payload_max_length — use the default 100MB limit
  10295. auto res =
  10296. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10297. total_received += data_length;
  10298. return true;
  10299. });
  10300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10301. EXPECT_EQ(StatusCode::OK_200, res->status);
  10302. }
  10303. server_thread.join();
  10304. EXPECT_EQ(total_received, DATA_SIZE)
  10305. << "With content_receiver, the client should read all " << DATA_SIZE
  10306. << " bytes despite the default 100MB payload_max_length, but only read "
  10307. << total_received << " bytes.";
  10308. }
  10309. // Verify that an explicit set_payload_max_length smaller than the response is
  10310. // enforced even when a content_receiver is used.
  10311. TEST(ClientVulnerabilityTest,
  10312. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10313. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10314. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10315. #ifndef _WIN32
  10316. signal(SIGPIPE, SIG_IGN);
  10317. #endif
  10318. auto server_thread = std::thread([] {
  10319. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10320. default_socket_options(srv);
  10321. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10322. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10323. sockaddr_in addr{};
  10324. addr.sin_family = AF_INET;
  10325. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10326. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10327. int opt = 1;
  10328. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10329. #ifdef _WIN32
  10330. reinterpret_cast<const char *>(&opt),
  10331. #else
  10332. &opt,
  10333. #endif
  10334. sizeof(opt));
  10335. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10336. ::listen(srv, 1);
  10337. sockaddr_in cli_addr{};
  10338. socklen_t cli_len = sizeof(cli_addr);
  10339. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10340. if (cli != INVALID_SOCKET) {
  10341. char buf[4096];
  10342. ::recv(cli, buf, sizeof(buf), 0);
  10343. auto content_length = std::to_string(DATA_SIZE);
  10344. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10345. "Content-Length: " +
  10346. content_length +
  10347. "\r\n"
  10348. "Connection: close\r\n"
  10349. "\r\n";
  10350. ::send(cli,
  10351. #ifdef _WIN32
  10352. static_cast<const char *>(response_header.c_str()),
  10353. static_cast<int>(response_header.size()),
  10354. #else
  10355. response_header.c_str(), response_header.size(),
  10356. #endif
  10357. 0);
  10358. std::string chunk(64 * 1024, 'A');
  10359. size_t total_sent = 0;
  10360. while (total_sent < DATA_SIZE) {
  10361. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10362. auto sent = ::send(cli,
  10363. #ifdef _WIN32
  10364. static_cast<const char *>(chunk.c_str()),
  10365. static_cast<int>(to_send),
  10366. #else
  10367. chunk.c_str(), to_send,
  10368. #endif
  10369. 0);
  10370. if (sent <= 0) break;
  10371. total_sent += static_cast<size_t>(sent);
  10372. }
  10373. detail::close_socket(cli);
  10374. }
  10375. detail::close_socket(srv);
  10376. });
  10377. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10378. size_t total_received = 0;
  10379. {
  10380. Client cli("127.0.0.1", PORT + 2);
  10381. cli.set_read_timeout(10, 0);
  10382. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10383. auto res =
  10384. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10385. total_received += data_length;
  10386. return true;
  10387. });
  10388. // Should fail because 200MB exceeds the explicit 150MB limit
  10389. EXPECT_FALSE(res);
  10390. }
  10391. server_thread.join();
  10392. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10393. << "Client with content_receiver should respect the explicit "
  10394. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10395. << total_received << " bytes.";
  10396. }
  10397. // Verify that an explicit set_payload_max_length larger than the response
  10398. // allows the content_receiver to read all data successfully.
  10399. TEST(ClientVulnerabilityTest,
  10400. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10401. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10402. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10403. #ifndef _WIN32
  10404. signal(SIGPIPE, SIG_IGN);
  10405. #endif
  10406. auto server_thread = std::thread([] {
  10407. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10408. default_socket_options(srv);
  10409. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10410. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10411. sockaddr_in addr{};
  10412. addr.sin_family = AF_INET;
  10413. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10414. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10415. int opt = 1;
  10416. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10417. #ifdef _WIN32
  10418. reinterpret_cast<const char *>(&opt),
  10419. #else
  10420. &opt,
  10421. #endif
  10422. sizeof(opt));
  10423. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10424. ::listen(srv, 1);
  10425. sockaddr_in cli_addr{};
  10426. socklen_t cli_len = sizeof(cli_addr);
  10427. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10428. if (cli != INVALID_SOCKET) {
  10429. char buf[4096];
  10430. ::recv(cli, buf, sizeof(buf), 0);
  10431. auto content_length = std::to_string(DATA_SIZE);
  10432. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10433. "Content-Length: " +
  10434. content_length +
  10435. "\r\n"
  10436. "Connection: close\r\n"
  10437. "\r\n";
  10438. ::send(cli,
  10439. #ifdef _WIN32
  10440. static_cast<const char *>(response_header.c_str()),
  10441. static_cast<int>(response_header.size()),
  10442. #else
  10443. response_header.c_str(), response_header.size(),
  10444. #endif
  10445. 0);
  10446. std::string chunk(64 * 1024, 'A');
  10447. size_t total_sent = 0;
  10448. while (total_sent < DATA_SIZE) {
  10449. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10450. auto sent = ::send(cli,
  10451. #ifdef _WIN32
  10452. static_cast<const char *>(chunk.c_str()),
  10453. static_cast<int>(to_send),
  10454. #else
  10455. chunk.c_str(), to_send,
  10456. #endif
  10457. 0);
  10458. if (sent <= 0) break;
  10459. total_sent += static_cast<size_t>(sent);
  10460. }
  10461. #ifdef _WIN32
  10462. ::shutdown(cli, SD_SEND);
  10463. #else
  10464. ::shutdown(cli, SHUT_WR);
  10465. #endif
  10466. char drain[1024];
  10467. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10468. detail::close_socket(cli);
  10469. }
  10470. detail::close_socket(srv);
  10471. });
  10472. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10473. size_t total_received = 0;
  10474. {
  10475. Client cli("127.0.0.1", PORT + 2);
  10476. cli.set_read_timeout(10, 0);
  10477. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10478. auto res =
  10479. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10480. total_received += data_length;
  10481. return true;
  10482. });
  10483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10484. EXPECT_EQ(StatusCode::OK_200, res->status);
  10485. }
  10486. server_thread.join();
  10487. EXPECT_EQ(total_received, DATA_SIZE)
  10488. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10489. << " bytes (larger than " << DATA_SIZE
  10490. << " bytes response), content_receiver should read all data, but only "
  10491. "read "
  10492. << total_received << " bytes.";
  10493. }
  10494. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10495. // Regression test for "zip bomb" attack on the client side: a malicious server
  10496. // sends a small gzip-compressed response that decompresses to a huge payload.
  10497. // The client must enforce payload_max_length on the decompressed size.
  10498. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10499. constexpr size_t DECOMPRESSED_SIZE =
  10500. 10 * 1024 * 1024; // 10MB after decompression
  10501. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10502. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10503. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10504. std::string compressed;
  10505. {
  10506. httplib::detail::gzip_compressor compressor;
  10507. bool ok =
  10508. compressor.compress(uncompressed.data(), uncompressed.size(),
  10509. /*last=*/true, [&](const char *buf, size_t len) {
  10510. compressed.append(buf, len);
  10511. return true;
  10512. });
  10513. ASSERT_TRUE(ok);
  10514. }
  10515. // Sanity: compressed data should be much smaller than the decompressed size
  10516. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10517. #ifndef _WIN32
  10518. signal(SIGPIPE, SIG_IGN);
  10519. #endif
  10520. // Set up the listening socket in the main thread so the server is guaranteed
  10521. // to be ready before the client connects (eliminates race condition).
  10522. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10523. default_socket_options(srv);
  10524. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10526. sockaddr_in addr{};
  10527. addr.sin_family = AF_INET;
  10528. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10529. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10530. int opt = 1;
  10531. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10532. #ifdef _WIN32
  10533. reinterpret_cast<const char *>(&opt),
  10534. #else
  10535. &opt,
  10536. #endif
  10537. sizeof(opt));
  10538. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10539. ASSERT_EQ(0, ::listen(srv, 1));
  10540. auto server_thread = std::thread([&compressed, srv] {
  10541. sockaddr_in cli_addr{};
  10542. socklen_t cli_len = sizeof(cli_addr);
  10543. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10544. if (cli != INVALID_SOCKET) {
  10545. // Read the full HTTP request (until \r\n\r\n)
  10546. char buf[4096];
  10547. size_t total = 0;
  10548. while (total < sizeof(buf)) {
  10549. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10550. if (n <= 0) break;
  10551. total += static_cast<size_t>(n);
  10552. // Check for end of headers
  10553. if (total >= 4) {
  10554. std::string req(buf, total);
  10555. if (req.find("\r\n\r\n") != std::string::npos) break;
  10556. }
  10557. }
  10558. // Malicious response: gzip-compressed body, no Content-Length
  10559. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10560. "Content-Encoding: gzip\r\n"
  10561. "Connection: close\r\n"
  10562. "\r\n";
  10563. ::send(cli,
  10564. #ifdef _WIN32
  10565. static_cast<const char *>(response_header.c_str()),
  10566. static_cast<int>(response_header.size()),
  10567. #else
  10568. response_header.c_str(), response_header.size(),
  10569. #endif
  10570. 0);
  10571. // Send the compressed payload (small on the wire, huge when decompressed)
  10572. size_t total_sent = 0;
  10573. while (total_sent < compressed.size()) {
  10574. auto to_send = std::min(compressed.size() - total_sent,
  10575. static_cast<size_t>(64 * 1024));
  10576. auto sent =
  10577. ::send(cli,
  10578. #ifdef _WIN32
  10579. static_cast<const char *>(compressed.c_str() + total_sent),
  10580. static_cast<int>(to_send),
  10581. #else
  10582. compressed.c_str() + total_sent, to_send,
  10583. #endif
  10584. 0);
  10585. if (sent <= 0) break;
  10586. total_sent += static_cast<size_t>(sent);
  10587. }
  10588. detail::close_socket(cli);
  10589. }
  10590. });
  10591. auto se = detail::scope_exit([&] {
  10592. detail::close_socket(srv);
  10593. server_thread.join();
  10594. });
  10595. size_t total_decompressed = 0;
  10596. {
  10597. Client cli("127.0.0.1", PORT + 3);
  10598. cli.set_read_timeout(5, 0);
  10599. cli.set_decompress(true);
  10600. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10601. auto stream = cli.open_stream("GET", "/zipbomb");
  10602. ASSERT_TRUE(stream.is_valid());
  10603. char buffer[64 * 1024];
  10604. ssize_t n;
  10605. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10606. total_decompressed += static_cast<size_t>(n);
  10607. }
  10608. }
  10609. // The decompressed size must be capped by payload_max_length. Without
  10610. // protection, the client would decompress the full 10MB from a tiny
  10611. // compressed payload, enabling a zip bomb DoS attack.
  10612. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10613. << "Client decompressed " << total_decompressed
  10614. << " bytes from a gzip response. The decompressed size should be "
  10615. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10616. }
  10617. #endif
  10618. TEST(HostAndPortPropertiesTest, NoSSL) {
  10619. httplib::Client cli("www.google.com", 1234);
  10620. ASSERT_EQ("www.google.com", cli.host());
  10621. ASSERT_EQ(1234, cli.port());
  10622. }
  10623. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10624. httplib::Client cli("www.google.com:1234");
  10625. ASSERT_EQ("www.google.com", cli.host());
  10626. ASSERT_EQ(1234, cli.port());
  10627. }
  10628. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10629. // Port number that overflows int — should not crash, client becomes invalid
  10630. httplib::Client cli("http://www.google.com:99999999999999999999");
  10631. ASSERT_FALSE(cli.is_valid());
  10632. }
  10633. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10634. // Port 99999 exceeds valid range (1-65535) — should not crash
  10635. httplib::Client cli("http://www.google.com:99999");
  10636. ASSERT_FALSE(cli.is_valid());
  10637. }
  10638. #ifdef CPPHTTPLIB_SSL_ENABLED
  10639. TEST(HostAndPortPropertiesTest, SSL) {
  10640. httplib::SSLClient cli("www.google.com");
  10641. ASSERT_EQ("www.google.com", cli.host());
  10642. ASSERT_EQ(443, cli.port());
  10643. }
  10644. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10645. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10646. std::string cert;
  10647. read_file(CA_CERT_FILE, cert);
  10648. httplib::SSLClient httplib_client("www.google.com");
  10649. // Load CA store first time
  10650. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10651. // Load CA store second time (update)
  10652. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10653. // Verify client is still valid and can make connections
  10654. httplib_client.enable_server_certificate_verification(true);
  10655. auto res = httplib_client.Get("/");
  10656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10657. // Google may return 200 or 301 depending on various factors
  10658. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10659. res->status == StatusCode::MovedPermanently_301);
  10660. }
  10661. TEST(SSLClientTest, ServerNameIndication_Online) {
  10662. auto host = "httpbingo.org";
  10663. auto path = std::string{"/get"};
  10664. SSLClient cli(host, 443);
  10665. auto res = cli.Get(path);
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. ASSERT_EQ(StatusCode::OK_200, res->status);
  10668. }
  10669. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10670. // Use a site that will cause SSL verification failure due to self-signed cert
  10671. SSLClient cli("self-signed.badssl.com", 443);
  10672. cli.enable_server_certificate_verification(true);
  10673. auto res = cli.Get("/");
  10674. ASSERT_TRUE(!res);
  10675. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10676. // Verify backend error is captured for SSLServerVerification
  10677. // This occurs when certificate verification fails
  10678. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10679. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10680. EXPECT_NE(0UL, res.ssl_backend_error());
  10681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10682. // For OpenSSL, ssl_error is 0 for verification errors
  10683. EXPECT_EQ(0, res.ssl_error());
  10684. #if !defined(_WIN32) || \
  10685. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10686. // On non-Windows or when Windows Schannel is disabled, the error comes
  10687. // from OpenSSL's verification
  10688. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10689. res.ssl_backend_error());
  10690. #endif
  10691. #endif
  10692. }
  10693. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10694. // Use a site where hostname doesn't match the certificate
  10695. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10696. SSLClient cli("wrong.host.badssl.com", 443);
  10697. cli.enable_server_certificate_verification(true);
  10698. cli.enable_server_hostname_verification(true);
  10699. auto res = cli.Get("/");
  10700. ASSERT_TRUE(!res);
  10701. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10702. // Verify backend error is captured for hostname verification failure
  10703. EXPECT_NE(0UL, res.ssl_backend_error());
  10704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10705. // For OpenSSL, ssl_error is 0 for verification errors
  10706. EXPECT_EQ(0, res.ssl_error());
  10707. #if !defined(_WIN32) || \
  10708. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10709. // On non-Windows or when Windows Schannel is disabled, the error comes
  10710. // from OpenSSL's hostname verification
  10711. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10712. res.ssl_backend_error());
  10713. #endif
  10714. #endif
  10715. }
  10716. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10717. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10718. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10719. SSLClient cli("www.google.com", 443);
  10720. cli.enable_server_certificate_verification(true);
  10721. auto res = cli.Get("/");
  10722. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10723. }
  10724. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10725. SSLClient cli("www.google.com", 443);
  10726. cli.enable_server_certificate_verification(true);
  10727. cli.enable_windows_certificate_verification(false);
  10728. auto res = cli.Get("/");
  10729. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10730. }
  10731. #endif
  10732. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10733. Client cli("https://google.com");
  10734. auto res = cli.Get("/");
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10737. }
  10738. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10739. SSLClient cli("google.com");
  10740. cli.set_ca_cert_path(CA_CERT_FILE);
  10741. auto res = cli.Get("/");
  10742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10743. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10744. }
  10745. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10746. SSLClient cli("google.com");
  10747. cli.enable_server_certificate_verification(true);
  10748. cli.set_ca_cert_path("hello");
  10749. auto res = cli.Get("/");
  10750. ASSERT_TRUE(!res);
  10751. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10752. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10753. // should be set
  10754. EXPECT_EQ(0, res.ssl_error());
  10755. // Verify backend error is captured for SSLLoadingCerts
  10756. // This error occurs when loading CA certificates fails
  10757. EXPECT_NE(0UL, res.ssl_backend_error());
  10758. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10759. // OpenSSL specific error codes:
  10760. // > openssl errstr 0x80000002
  10761. // error:80000002:system library::No such file or directory
  10762. // > openssl errstr 0xA000126
  10763. // error:0A000126:SSL routines::unexpected eof while reading
  10764. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10765. res.ssl_backend_error() == 0xA000126);
  10766. #endif
  10767. }
  10768. TEST(SSLClientTest, ServerCertificateVerification4) {
  10769. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10770. ASSERT_TRUE(svr.is_valid());
  10771. svr.Get("/test", [&](const Request &, Response &res) {
  10772. res.set_content("test", "text/plain");
  10773. svr.stop();
  10774. ASSERT_TRUE(true);
  10775. });
  10776. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10777. auto se = detail::scope_exit([&] {
  10778. t.join();
  10779. ASSERT_FALSE(svr.is_running());
  10780. });
  10781. svr.wait_until_ready();
  10782. SSLClient cli("127.0.0.1", PORT);
  10783. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10784. cli.enable_server_certificate_verification(true);
  10785. cli.set_connection_timeout(30);
  10786. auto res = cli.Get("/test");
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. ASSERT_EQ(StatusCode::OK_200, res->status);
  10789. }
  10790. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10791. std::string cert;
  10792. read_file(CA_CERT_FILE, cert);
  10793. SSLClient cli("google.com");
  10794. cli.load_ca_cert_store(cert.data(), cert.size());
  10795. const auto res = cli.Get("/");
  10796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10797. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10798. }
  10799. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10800. // clang-format off
  10801. static constexpr char cert[] =
  10802. "GlobalSign Root CA\n"
  10803. "==================\n"
  10804. "-----BEGIN CERTIFICATE-----\n"
  10805. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10806. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10807. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10808. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10809. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10810. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10811. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10812. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10813. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10814. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10815. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10816. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10817. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10818. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10819. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10820. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10821. "-----END CERTIFICATE-----\n";
  10822. // clang-format on
  10823. SSLClient cli("google.com");
  10824. cli.load_ca_cert_store(cert, sizeof(cert));
  10825. const auto res = cli.Get("/");
  10826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10827. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10828. }
  10829. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10830. SSLClient cli("www.youtube.com");
  10831. cli.set_ca_cert_path(CA_CERT_FILE);
  10832. cli.enable_server_certificate_verification(true);
  10833. cli.set_follow_location(true);
  10834. auto res = cli.Get("/");
  10835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10836. ASSERT_EQ(StatusCode::OK_200, res->status);
  10837. }
  10838. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10839. SSLClient cli("wWw.YouTube.Com");
  10840. cli.set_ca_cert_path(CA_CERT_FILE);
  10841. cli.enable_server_certificate_verification(true);
  10842. cli.enable_server_hostname_verification(true);
  10843. cli.set_follow_location(true);
  10844. auto res = cli.Get("/");
  10845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10846. ASSERT_EQ(StatusCode::OK_200, res->status);
  10847. }
  10848. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10849. SSLClient cli("gOoGlE.COm");
  10850. cli.enable_server_certificate_verification(true);
  10851. cli.enable_server_hostname_verification(true);
  10852. cli.set_follow_location(true);
  10853. auto res = cli.Get("/");
  10854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10855. ASSERT_EQ(StatusCode::OK_200, res->status);
  10856. }
  10857. TEST(SSLClientTest, Issue2004_Online) {
  10858. Client client("https://google.com");
  10859. client.set_follow_location(true);
  10860. auto res = client.Get("/");
  10861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10862. ASSERT_EQ(StatusCode::OK_200, res->status);
  10863. auto body = res->body;
  10864. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10865. }
  10866. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10867. // Create SSLClient with invalid cert/key to make is_valid() return false
  10868. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10869. "nonexistent_key.pem");
  10870. // is_valid() should be false due to cert loading failure
  10871. ASSERT_FALSE(cli.is_valid());
  10872. auto res = cli.Get("/");
  10873. ASSERT_FALSE(res);
  10874. EXPECT_EQ(Error::SSLConnection, res.error());
  10875. }
  10876. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10877. // Test for Issue #2251: SSL error not properly reported when client cert
  10878. // and key paths are swapped or mismatched
  10879. // This simulates the scenario where user accidentally swaps the cert and key
  10880. // files
  10881. // Using client cert file as private key and vice versa (completely wrong)
  10882. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10883. // Should fail validation due to cert/key mismatch
  10884. ASSERT_FALSE(cli.is_valid());
  10885. // Attempt to make a request should fail with proper error
  10886. auto res = cli.Get("/");
  10887. ASSERT_FALSE(res);
  10888. EXPECT_EQ(Error::SSLConnection, res.error());
  10889. // SSL error should be recorded in the Result object (this is the key fix for
  10890. // Issue #2251)
  10891. auto backend_error = res.ssl_backend_error();
  10892. EXPECT_NE(0u, backend_error);
  10893. }
  10894. // Tests cert/key mismatch detection at the TLS context level
  10895. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10896. // Test that using mismatched cert/key causes connection failure.
  10897. // We verify this at the SSLClient level rather than through internal
  10898. // TLS API functions.
  10899. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10900. cli.enable_server_certificate_verification(false);
  10901. cli.set_connection_timeout(2);
  10902. // The mismatch should cause a connection or handshake error
  10903. auto res = cli.Get("/test");
  10904. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10905. // Either way, the request should fail
  10906. EXPECT_FALSE(res);
  10907. }
  10908. #endif
  10909. #if 0
  10910. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10911. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10912. ASSERT_TRUE(cli != nullptr);
  10913. cli->set_address_family(AF_INET6);
  10914. cli->set_interface("en0");
  10915. auto res = cli->Get("/get");
  10916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10917. ASSERT_EQ(StatusCode::OK_200, res->status);
  10918. }
  10919. #endif
  10920. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10921. #ifdef CPPHTTPLIB_SSL_ENABLED
  10922. void ClientCertPresent(
  10923. const std::string &client_cert_file,
  10924. const std::string &client_private_key_file,
  10925. const std::string &client_encrypted_private_key_pass = std::string()) {
  10926. using namespace httplib::tls;
  10927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10928. CLIENT_CA_CERT_DIR);
  10929. ASSERT_TRUE(svr.is_valid());
  10930. svr.Get("/test", [&](const Request &req, Response &res) {
  10931. res.set_content("test", "text/plain");
  10932. auto cert = req.peer_cert();
  10933. ASSERT_TRUE(static_cast<bool>(cert));
  10934. std::string common_name = cert.subject_cn();
  10935. EXPECT_EQ("Common Name", common_name);
  10936. });
  10937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10945. client_encrypted_private_key_pass);
  10946. cli.enable_server_certificate_verification(false);
  10947. cli.set_connection_timeout(30);
  10948. auto res = cli.Get("/test");
  10949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10950. ASSERT_EQ(StatusCode::OK_200, res->status);
  10951. }
  10952. TEST(SSLClientServerTest, ClientCertPresent) {
  10953. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10954. }
  10955. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10956. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10957. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10958. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10959. }
  10960. // PEM memory-based constructor tests (works with all TLS backends)
  10961. void PemMemoryClientCertPresent(
  10962. const std::string &client_cert_file,
  10963. const std::string &client_private_key_file,
  10964. const std::string &client_encrypted_private_key_pass = std::string()) {
  10965. // Read PEM files into memory
  10966. std::string server_cert_pem, server_key_pem;
  10967. std::string client_ca_pem;
  10968. std::string client_cert_pem, client_key_pem;
  10969. read_file(SERVER_CERT_FILE, server_cert_pem);
  10970. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10971. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10972. read_file(client_cert_file, client_cert_pem);
  10973. read_file(client_private_key_file, client_key_pem);
  10974. // Create server with PEM memory
  10975. SSLServer::PemMemory server_pem = {
  10976. server_cert_pem.c_str(),
  10977. server_cert_pem.size(),
  10978. server_key_pem.c_str(),
  10979. server_key_pem.size(),
  10980. client_ca_pem.c_str(),
  10981. client_ca_pem.size(),
  10982. nullptr // no password for server key
  10983. };
  10984. SSLServer svr(server_pem);
  10985. ASSERT_TRUE(svr.is_valid());
  10986. svr.Get("/test", [&](const Request &, Response &res) {
  10987. res.set_content("test", "text/plain");
  10988. });
  10989. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10990. auto se = detail::scope_exit([&] {
  10991. svr.stop();
  10992. t.join();
  10993. ASSERT_FALSE(svr.is_running());
  10994. });
  10995. svr.wait_until_ready();
  10996. // Create client with PEM memory
  10997. const char *password = client_encrypted_private_key_pass.empty()
  10998. ? nullptr
  10999. : client_encrypted_private_key_pass.c_str();
  11000. SSLClient::PemMemory client_pem = {
  11001. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11002. client_key_pem.size(), password};
  11003. SSLClient cli(HOST, PORT, client_pem);
  11004. cli.enable_server_certificate_verification(false);
  11005. cli.set_connection_timeout(30);
  11006. auto res = cli.Get("/test");
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. ASSERT_EQ(StatusCode::OK_200, res->status);
  11009. }
  11010. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11011. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11012. }
  11013. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11014. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11015. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11016. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11017. }
  11018. TEST(SSLClientServerTest, ClientCertMissing) {
  11019. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11020. CLIENT_CA_CERT_DIR);
  11021. ASSERT_TRUE(svr.is_valid());
  11022. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11023. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11024. auto se = detail::scope_exit([&] {
  11025. svr.stop();
  11026. t.join();
  11027. ASSERT_FALSE(svr.is_running());
  11028. });
  11029. svr.wait_until_ready();
  11030. SSLClient cli(HOST, PORT);
  11031. cli.set_connection_timeout(30);
  11032. auto res = cli.Get("/test");
  11033. ASSERT_TRUE(!res);
  11034. // When client cert is missing and server requires it, connection fails
  11035. // Error type depends on backend implementation
  11036. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11037. res.error() == Error::SSLConnection);
  11038. // Verify backend error is captured
  11039. // Note: This test may have different error codes depending on the exact
  11040. // verification failure
  11041. EXPECT_NE(0UL, res.ssl_backend_error());
  11042. }
  11043. TEST(SSLClientServerTest, TrustDirOptional) {
  11044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11045. ASSERT_TRUE(svr.is_valid());
  11046. svr.Get("/test", [&](const Request &, Response &res) {
  11047. res.set_content("test", "text/plain");
  11048. });
  11049. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. t.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11057. cli.enable_server_certificate_verification(false);
  11058. cli.set_connection_timeout(30);
  11059. auto res = cli.Get("/test");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. ASSERT_EQ(StatusCode::OK_200, res->status);
  11062. }
  11063. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11064. class NoListenSSLServer : public SSLServer {
  11065. public:
  11066. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11067. const char *client_ca_cert_file_path,
  11068. const char *client_ca_cert_dir_path = nullptr)
  11069. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11070. client_ca_cert_dir_path),
  11071. stop_(false) {}
  11072. std::atomic_bool stop_;
  11073. private:
  11074. bool process_and_close_socket(socket_t /*sock*/) override {
  11075. // Don't create SSL context
  11076. while (!stop_.load()) {
  11077. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11078. }
  11079. return true;
  11080. }
  11081. };
  11082. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11083. CLIENT_CA_CERT_FILE);
  11084. ASSERT_TRUE(svr.is_valid());
  11085. svr.Get("/test", [&](const Request &, Response &res) {
  11086. res.set_content("test", "text/plain");
  11087. });
  11088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11089. auto se = detail::scope_exit([&] {
  11090. svr.stop_ = true;
  11091. svr.stop();
  11092. t.join();
  11093. ASSERT_FALSE(svr.is_running());
  11094. });
  11095. svr.wait_until_ready();
  11096. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11097. cli.enable_server_certificate_verification(false);
  11098. cli.set_connection_timeout(1);
  11099. auto res = cli.Get("/test");
  11100. ASSERT_TRUE(!res);
  11101. EXPECT_EQ(Error::SSLConnection, res.error());
  11102. // Timeout results in WantRead error code (maps to backend-specific value)
  11103. EXPECT_NE(0, res.ssl_error());
  11104. }
  11105. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11106. // Test SSLServer with client certificate verification using the standard
  11107. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11109. CLIENT_CA_CERT_DIR);
  11110. ASSERT_TRUE(svr.is_valid());
  11111. svr.Get("/test", [&](const Request &req, Response &res) {
  11112. res.set_content("test", "text/plain");
  11113. auto cert = req.peer_cert();
  11114. ASSERT_TRUE(static_cast<bool>(cert));
  11115. auto common_name = cert.subject_cn();
  11116. EXPECT_EQ("Common Name", common_name);
  11117. });
  11118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11126. cli.enable_server_certificate_verification(false);
  11127. cli.set_connection_timeout(30);
  11128. auto res = cli.Get("/test");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. ASSERT_EQ(StatusCode::OK_200, res->status);
  11131. }
  11132. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11133. // Verifies that wildcard matching and exact matching work consistently
  11134. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11135. using namespace httplib::tls;
  11136. // We need a running server to test against
  11137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11138. ASSERT_TRUE(svr.is_valid());
  11139. svr.Get("/test", [](const Request &, Response &res) {
  11140. res.set_content("ok", "text/plain");
  11141. });
  11142. thread t([&]() { svr.listen(HOST, PORT); });
  11143. auto se = detail::scope_exit([&] {
  11144. svr.stop();
  11145. t.join();
  11146. });
  11147. svr.wait_until_ready();
  11148. bool verify_callback_called = false;
  11149. bool verify_result_wrong = false;
  11150. SSLClient cli(HOST, PORT);
  11151. cli.enable_server_certificate_verification(true);
  11152. cli.set_ca_cert_path(CA_CERT_FILE);
  11153. cli.set_connection_timeout(5);
  11154. // Note: Test certificate has CN="Common Name", not "localhost"
  11155. bool verify_result_cn = false;
  11156. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11157. verify_callback_called = true;
  11158. if (!ctx.cert) return false;
  11159. // Test 1: "Common Name" should match (our test server cert CN)
  11160. verify_result_cn = ctx.check_hostname("Common Name");
  11161. // Test 2: wrong hostname should not match
  11162. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11163. return true; // Accept for the purpose of this test
  11164. });
  11165. auto res = cli.Get("/test");
  11166. // The request may succeed or fail depending on cert configuration
  11167. // but the callback should have been called
  11168. ASSERT_TRUE(verify_callback_called)
  11169. << "Verify callback should have been called";
  11170. // CN="Common Name" should match our test certificate
  11171. //
  11172. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11173. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11174. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11175. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11176. // <openssl/base.h>, which is included transitively when
  11177. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11178. #if defined(OPENSSL_IS_BORINGSSL)
  11179. EXPECT_FALSE(verify_result_cn)
  11180. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11181. #else
  11182. EXPECT_TRUE(verify_result_cn)
  11183. << "verify_hostname should match 'Common Name' (certificate CN)";
  11184. #endif
  11185. // Wrong hostname should not match
  11186. EXPECT_FALSE(verify_result_wrong)
  11187. << "verify_hostname should not match 'wronghost.example.com'";
  11188. }
  11189. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11190. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11191. // X509_check_ip behavior and must hold for every backend.
  11192. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11193. using namespace httplib::tls;
  11194. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11195. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11196. ASSERT_TRUE(svr.is_valid());
  11197. svr.Get("/test", [](const Request &, Response &res) {
  11198. res.set_content("ok", "text/plain");
  11199. });
  11200. thread t([&]() { svr.listen(HOST, PORT); });
  11201. auto se = detail::scope_exit([&] {
  11202. svr.stop();
  11203. t.join();
  11204. });
  11205. svr.wait_until_ready();
  11206. bool verify_callback_called = false;
  11207. bool ip_matched_via_cn = 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. // The IP appears only in the CN, so it must NOT be accepted.
  11216. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11217. return true; // Accept for the purpose of this test
  11218. });
  11219. cli.Get("/test");
  11220. ASSERT_TRUE(verify_callback_called)
  11221. << "Verify callback should have been called";
  11222. EXPECT_FALSE(ip_matched_via_cn)
  11223. << "An IP host must not be authenticated via the certificate CN";
  11224. }
  11225. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11226. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11227. using namespace httplib::tls;
  11228. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11229. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11230. ASSERT_TRUE(svr.is_valid());
  11231. svr.Get("/test", [](const Request &, Response &res) {
  11232. res.set_content("ok", "text/plain");
  11233. });
  11234. thread t([&]() { svr.listen(HOST, PORT); });
  11235. auto se = detail::scope_exit([&] {
  11236. svr.stop();
  11237. t.join();
  11238. });
  11239. svr.wait_until_ready();
  11240. bool verify_callback_called = false;
  11241. bool san_matched = false;
  11242. bool wrong_ipv6_matched = true;
  11243. bool cn_ipv6_matched = true;
  11244. SSLClient cli(HOST, PORT);
  11245. cli.enable_server_certificate_verification(true);
  11246. cli.set_ca_cert_path(CA_CERT_FILE);
  11247. cli.set_connection_timeout(5);
  11248. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11249. verify_callback_called = true;
  11250. if (!ctx.cert) return false;
  11251. // Matches the IPv6 iPAddress SAN.
  11252. san_matched = ctx.check_hostname("2001:db8::1");
  11253. // A different IPv6 address must not match.
  11254. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11255. // "::1" lives only in the CN, so it must not be accepted.
  11256. cn_ipv6_matched = ctx.check_hostname("::1");
  11257. return true; // Accept for the purpose of this test
  11258. });
  11259. cli.Get("/test");
  11260. ASSERT_TRUE(verify_callback_called)
  11261. << "Verify callback should have been called";
  11262. EXPECT_TRUE(san_matched)
  11263. << "verify_hostname should match an IPv6 iPAddress SAN";
  11264. EXPECT_FALSE(wrong_ipv6_matched)
  11265. << "verify_hostname should not match a non-matching IPv6 address";
  11266. EXPECT_FALSE(cn_ipv6_matched)
  11267. << "An IPv6 host must not be authenticated via the certificate CN";
  11268. }
  11269. #endif
  11270. // mbedTLS-specific callback constructor test
  11271. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11272. #ifdef CPPHTTPLIB_SSL_ENABLED
  11273. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11275. ASSERT_TRUE(svr.is_valid());
  11276. // Set up a handler to verify client certificate is present
  11277. bool client_cert_verified = false;
  11278. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11279. // Verify that client certificate was provided
  11280. client_cert_verified = true;
  11281. res.set_content("success", "text/plain");
  11282. });
  11283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. t.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. });
  11289. svr.wait_until_ready();
  11290. // Client with certificate
  11291. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11292. cli.enable_server_certificate_verification(false);
  11293. cli.set_connection_timeout(30);
  11294. auto res = cli.Get("/test");
  11295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11296. ASSERT_EQ(StatusCode::OK_200, res->status);
  11297. ASSERT_TRUE(client_cert_verified);
  11298. EXPECT_EQ("success", res->body);
  11299. }
  11300. #endif
  11301. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11302. // backends
  11303. #ifdef CPPHTTPLIB_SSL_ENABLED
  11304. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11305. using namespace httplib::tls;
  11306. // Test that when client CA cert file is provided,
  11307. // the server properly requests and validates client certificates
  11308. // Create a server with client authentication
  11309. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11310. ASSERT_TRUE(svr.is_valid());
  11311. bool handler_called = false;
  11312. svr.Get("/test", [&](const Request &req, Response &res) {
  11313. handler_called = true;
  11314. // Verify that a client certificate was provided
  11315. auto cert = req.peer_cert();
  11316. ASSERT_TRUE(static_cast<bool>(cert));
  11317. // Get the issuer name
  11318. std::string issuer_str = cert.issuer_name();
  11319. ASSERT_FALSE(issuer_str.empty());
  11320. // The client certificate should be issued by our test CA
  11321. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11322. res.set_content("authenticated", "text/plain");
  11323. });
  11324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. });
  11330. svr.wait_until_ready();
  11331. // Connect with a client certificate issued by the CA
  11332. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11333. cli.enable_server_certificate_verification(false);
  11334. cli.set_connection_timeout(30);
  11335. auto res = cli.Get("/test");
  11336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11337. ASSERT_EQ(StatusCode::OK_200, res->status);
  11338. ASSERT_TRUE(handler_called);
  11339. EXPECT_EQ("authenticated", res->body);
  11340. }
  11341. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  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 cert_checked = false;
  11358. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11359. if (ctx.cert) {
  11360. auto sans = ctx.sans();
  11361. // Test certificate may or may not have SANs - just verify the API
  11362. // works If SANs exist, verify the types are valid
  11363. for (const auto &san : sans) {
  11364. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11365. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11366. san.type == SanType::OTHER);
  11367. EXPECT_FALSE(san.value.empty());
  11368. }
  11369. cert_checked = true;
  11370. }
  11371. return true;
  11372. });
  11373. auto res = cli.Get("/test");
  11374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11375. EXPECT_TRUE(cert_checked);
  11376. }
  11377. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11378. using namespace httplib::tls;
  11379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11380. ASSERT_TRUE(svr.is_valid());
  11381. svr.Get("/test", [](const Request &, Response &res) {
  11382. res.set_content("ok", "text/plain");
  11383. });
  11384. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11385. auto se = detail::scope_exit([&] {
  11386. svr.stop();
  11387. t.join();
  11388. });
  11389. svr.wait_until_ready();
  11390. SSLClient cli(HOST, PORT);
  11391. cli.enable_server_certificate_verification(false);
  11392. cli.set_connection_timeout(30);
  11393. bool validity_checked = false;
  11394. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11395. if (ctx.cert) {
  11396. time_t not_before = 0, not_after = 0;
  11397. bool result = ctx.validity(not_before, not_after);
  11398. EXPECT_TRUE(result);
  11399. // Verify that not_before < now < not_after for a valid cert
  11400. time_t now = time(nullptr);
  11401. EXPECT_LT(not_before, now);
  11402. EXPECT_GT(not_after, now);
  11403. validity_checked = true;
  11404. }
  11405. return true;
  11406. });
  11407. auto res = cli.Get("/test");
  11408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11409. EXPECT_TRUE(validity_checked);
  11410. }
  11411. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11412. using namespace httplib::tls;
  11413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11414. ASSERT_TRUE(svr.is_valid());
  11415. svr.Get("/test", [](const Request &, Response &res) {
  11416. res.set_content("ok", "text/plain");
  11417. });
  11418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11419. auto se = detail::scope_exit([&] {
  11420. svr.stop();
  11421. t.join();
  11422. });
  11423. svr.wait_until_ready();
  11424. SSLClient cli(HOST, PORT);
  11425. cli.enable_server_certificate_verification(false);
  11426. cli.set_connection_timeout(30);
  11427. bool serial_checked = false;
  11428. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11429. if (ctx.cert) {
  11430. std::string serial = ctx.serial();
  11431. EXPECT_FALSE(serial.empty());
  11432. // Serial should be a hex string
  11433. for (char c : serial) {
  11434. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11435. (c >= 'a' && c <= 'f'));
  11436. }
  11437. serial_checked = true;
  11438. }
  11439. return true;
  11440. });
  11441. auto res = cli.Get("/test");
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. EXPECT_TRUE(serial_checked);
  11444. }
  11445. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11446. // Test 1: Valid CA file - no error should be recorded
  11447. {
  11448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11449. CLIENT_CA_CERT_FILE);
  11450. ASSERT_TRUE(svr.is_valid());
  11451. // With valid setup, last_ssl_error should be 0
  11452. EXPECT_EQ(0, svr.ssl_last_error());
  11453. }
  11454. // Test 2: Invalid CA file content
  11455. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11456. {
  11457. // Create a temporary file with completely invalid content
  11458. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11459. {
  11460. std::ofstream ofs(temp_invalid_ca);
  11461. ofs << "This is not a certificate file at all\n";
  11462. ofs << "Just plain text content\n";
  11463. }
  11464. // Create server with invalid CA file
  11465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11466. // Clean up temporary file
  11467. std::remove(temp_invalid_ca);
  11468. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11469. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11470. // Note: SSL_CTX_load_verify_locations typically fails first,
  11471. // but our error handling code path is still exercised
  11472. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11473. }
  11474. }
  11475. TEST(VerifyCallbackTest, VerifyContextFields) {
  11476. using namespace httplib::tls;
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. ASSERT_TRUE(svr.is_valid());
  11479. svr.Get("/test", [](const Request &, Response &res) {
  11480. res.set_content("ok", "text/plain");
  11481. });
  11482. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11483. auto se = detail::scope_exit([&] {
  11484. svr.stop();
  11485. t.join();
  11486. });
  11487. svr.wait_until_ready();
  11488. SSLClient cli(HOST, PORT);
  11489. cli.enable_server_certificate_verification(false);
  11490. cli.set_connection_timeout(30);
  11491. int callback_count = 0;
  11492. bool saw_leaf_cert = false;
  11493. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11494. if (ctx.cert) {
  11495. callback_count++;
  11496. // We should see at least one certificate (the leaf)
  11497. std::string cn = ctx.subject_cn();
  11498. if (!cn.empty()) { saw_leaf_cert = true; }
  11499. // Verify context fields are populated
  11500. EXPECT_NE(ctx.session, nullptr);
  11501. EXPECT_GE(ctx.depth, 0);
  11502. }
  11503. return true;
  11504. });
  11505. auto res = cli.Get("/test");
  11506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11507. EXPECT_GT(callback_count, 0);
  11508. EXPECT_TRUE(saw_leaf_cert);
  11509. }
  11510. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11511. using httplib::tls::TlsError;
  11512. // Test that verify_error_to_string returns empty for success
  11513. std::string success_str = TlsError::verify_error_to_string(0);
  11514. EXPECT_TRUE(success_str.empty());
  11515. // Test that verify_error_to_string returns non-empty for error codes
  11516. // Using a common error code (certificate expired)
  11517. std::string error_str =
  11518. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11519. EXPECT_FALSE(error_str.empty());
  11520. }
  11521. TEST(SessionVerifierTest, CertificateAccepted) {
  11522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11523. ASSERT_TRUE(svr.is_valid());
  11524. svr.Get("/test", [](const Request &, Response &res) {
  11525. res.set_content("ok", "text/plain");
  11526. });
  11527. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11528. auto se = detail::scope_exit([&] {
  11529. svr.stop();
  11530. t.join();
  11531. });
  11532. svr.wait_until_ready();
  11533. SSLClient cli(HOST, PORT);
  11534. cli.enable_server_certificate_verification(false);
  11535. cli.set_connection_timeout(30);
  11536. bool callback_called = false;
  11537. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11538. EXPECT_NE(session, nullptr);
  11539. callback_called = true;
  11540. return SSLVerifierResponse::CertificateAccepted;
  11541. });
  11542. auto res = cli.Get("/test");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. EXPECT_EQ(200, res->status);
  11545. EXPECT_TRUE(callback_called);
  11546. }
  11547. TEST(SessionVerifierTest, CertificateRejected) {
  11548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11549. ASSERT_TRUE(svr.is_valid());
  11550. svr.Get("/test", [](const Request &, Response &res) {
  11551. res.set_content("ok", "text/plain");
  11552. });
  11553. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11554. auto se = detail::scope_exit([&] {
  11555. svr.stop();
  11556. t.join();
  11557. });
  11558. svr.wait_until_ready();
  11559. SSLClient cli(HOST, PORT);
  11560. cli.enable_server_certificate_verification(false);
  11561. cli.set_connection_timeout(30);
  11562. bool callback_called = false;
  11563. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11564. EXPECT_NE(session, nullptr);
  11565. callback_called = true;
  11566. return SSLVerifierResponse::CertificateRejected;
  11567. });
  11568. auto res = cli.Get("/test");
  11569. EXPECT_FALSE(res);
  11570. EXPECT_TRUE(callback_called);
  11571. }
  11572. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11574. ASSERT_TRUE(svr.is_valid());
  11575. svr.Get("/test", [](const Request &, Response &res) {
  11576. res.set_content("ok", "text/plain");
  11577. });
  11578. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11579. auto se = detail::scope_exit([&] {
  11580. svr.stop();
  11581. t.join();
  11582. });
  11583. svr.wait_until_ready();
  11584. // NoDecisionMade with verification disabled should succeed (no default check)
  11585. SSLClient cli(HOST, PORT);
  11586. cli.enable_server_certificate_verification(false);
  11587. cli.set_connection_timeout(30);
  11588. bool callback_called = false;
  11589. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11590. EXPECT_NE(session, nullptr);
  11591. callback_called = true;
  11592. return SSLVerifierResponse::NoDecisionMade;
  11593. });
  11594. auto res = cli.Get("/test");
  11595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11596. EXPECT_EQ(200, res->status);
  11597. EXPECT_TRUE(callback_called);
  11598. }
  11599. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11601. ASSERT_TRUE(svr.is_valid());
  11602. svr.Get("/test", [](const Request &, Response &res) {
  11603. res.set_content("ok", "text/plain");
  11604. });
  11605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. t.join();
  11609. });
  11610. svr.wait_until_ready();
  11611. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11612. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11613. // so we only check that the request fails, not whether the callback was
  11614. // called.
  11615. SSLClient cli(HOST, PORT);
  11616. cli.enable_server_certificate_verification(true);
  11617. cli.set_connection_timeout(30);
  11618. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11619. EXPECT_NE(session, nullptr);
  11620. return SSLVerifierResponse::NoDecisionMade;
  11621. });
  11622. auto res = cli.Get("/test");
  11623. EXPECT_FALSE(res);
  11624. }
  11625. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11626. // Test SSL server using PemMemory constructor with client CA certificates
  11627. // Read PEM files
  11628. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11629. read_file(SERVER_CERT_FILE, server_cert_pem);
  11630. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11631. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11632. // Create SSLServer with PemMemory constructor including client CA
  11633. SSLServer::PemMemory server_pem = {
  11634. server_cert_pem.c_str(),
  11635. server_cert_pem.size(),
  11636. server_key_pem.c_str(),
  11637. server_key_pem.size(),
  11638. client_ca_pem.c_str(),
  11639. client_ca_pem.size(),
  11640. nullptr // no password for server key
  11641. };
  11642. SSLServer svr(server_pem);
  11643. ASSERT_TRUE(svr.is_valid());
  11644. // No SSL error should be recorded for valid setup
  11645. EXPECT_EQ(0, svr.ssl_last_error());
  11646. // Set up server endpoints
  11647. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11648. res.set_content("ok", "text/plain");
  11649. });
  11650. // Start server in a thread
  11651. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11652. svr.wait_until_ready();
  11653. // Connect with client certificate (using constructor with paths)
  11654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11655. cli.enable_server_certificate_verification(false);
  11656. auto res = cli.Get("/test-pem-ca");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. EXPECT_EQ(200, res->status);
  11659. EXPECT_EQ("ok", res->body);
  11660. svr.stop();
  11661. server_thread.join();
  11662. }
  11663. #endif
  11664. #ifdef _WIN32
  11665. TEST(CleanupTest, WSACleanup) {
  11666. int ret = WSACleanup();
  11667. ASSERT_EQ(0, ret);
  11668. }
  11669. #endif
  11670. #ifndef CPPHTTPLIB_SSL_ENABLED
  11671. TEST(NoSSLSupport, SimpleInterface) {
  11672. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11673. }
  11674. #endif
  11675. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11676. TEST(InvalidScheme, SimpleInterface) {
  11677. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11678. }
  11679. #endif
  11680. TEST(NoScheme, SimpleInterface) {
  11681. Client cli("yahoo.com:80");
  11682. ASSERT_TRUE(cli.is_valid());
  11683. }
  11684. TEST(SendAPI, SimpleInterface_Online) {
  11685. Client cli("http://yahoo.com");
  11686. Request req;
  11687. req.method = "GET";
  11688. req.path = "/";
  11689. auto res = cli.send(req);
  11690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11691. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11692. }
  11693. TEST(SendAPI, WithParamsInRequest) {
  11694. Server svr;
  11695. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11696. EXPECT_TRUE(req.has_param("test"));
  11697. EXPECT_EQ("test_value", req.get_param_value("test"));
  11698. });
  11699. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11700. auto se = detail::scope_exit([&] {
  11701. svr.stop();
  11702. t.join();
  11703. ASSERT_FALSE(svr.is_running());
  11704. });
  11705. svr.wait_until_ready();
  11706. Client cli(HOST, PORT);
  11707. {
  11708. Request req;
  11709. req.method = "GET";
  11710. req.path = "/";
  11711. req.params.emplace("test", "test_value");
  11712. auto res = cli.send(req);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. }
  11715. {
  11716. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11718. }
  11719. }
  11720. TEST(ClientImplMethods, GetSocketTest) {
  11721. httplib::Server svr;
  11722. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11723. res.status = StatusCode::OK_200;
  11724. });
  11725. auto port = svr.bind_to_any_port("127.0.0.1");
  11726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11727. auto se = detail::scope_exit([&] {
  11728. svr.stop();
  11729. thread.join();
  11730. ASSERT_FALSE(svr.is_running());
  11731. });
  11732. svr.wait_until_ready();
  11733. {
  11734. httplib::Client cli("127.0.0.1", port);
  11735. cli.set_keep_alive(true);
  11736. // Use the behavior of cpp-httplib of opening the connection
  11737. // only when the first request happens. If that changes,
  11738. // this test would be obsolete.
  11739. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11740. // This also implicitly tests the server. But other tests would fail much
  11741. // earlier than this one to be considered.
  11742. auto res = cli.Get("/");
  11743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11744. EXPECT_EQ(StatusCode::OK_200, res->status);
  11745. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11746. }
  11747. }
  11748. #ifdef CPPHTTPLIB_SSL_ENABLED
  11749. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11750. Client cli("http://yahoo.com");
  11751. auto res = cli.Get("/");
  11752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11753. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11754. cli.set_follow_location(true);
  11755. res = cli.Get("/");
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11759. }
  11760. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11761. Client cli("https://yahoo.com");
  11762. auto res = cli.Get("/");
  11763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11764. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11765. cli.set_follow_location(true);
  11766. res = cli.Get("/");
  11767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11768. EXPECT_EQ(StatusCode::OK_200, res->status);
  11769. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11770. }
  11771. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11772. Client cli("https://yahoo.com");
  11773. auto res = cli.Get("/");
  11774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11775. ASSERT_FALSE(!res);
  11776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11777. ASSERT_FALSE(res == nullptr);
  11778. ASSERT_TRUE(res != nullptr);
  11779. EXPECT_EQ(Error::Success, res.error());
  11780. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11781. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11782. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11783. cli.set_follow_location(true);
  11784. res = cli.Get("/");
  11785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11786. EXPECT_EQ(Error::Success, res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11788. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11789. EXPECT_EQ(StatusCode::OK_200, res->status);
  11790. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11791. }
  11792. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11793. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11794. Client cli("https://cdnjs.cloudflare.com");
  11795. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11796. Headers{{"Accept-Encoding", "br"}});
  11797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11798. EXPECT_EQ(StatusCode::OK_200, res->status);
  11799. EXPECT_EQ(287630U, res->body.size());
  11800. EXPECT_EQ("application/javascript; charset=utf-8",
  11801. res->get_header_value("Content-Type"));
  11802. }
  11803. #endif
  11804. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11805. #undef REDIR_HOST // Silence compiler warning
  11806. #define REDIR_HOST "https://httpbingo.org"
  11807. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11808. Client cli(REDIR_HOST);
  11809. cli.set_follow_location(true);
  11810. auto res =
  11811. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11813. EXPECT_EQ(StatusCode::OK_200, res->status);
  11814. }
  11815. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11816. Client cli(REDIR_HOST);
  11817. cli.set_follow_location(true);
  11818. Params params;
  11819. params.emplace("url", "http://example.com");
  11820. params.emplace("status_code", "302");
  11821. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. }
  11825. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11826. Client cli(REDIR_HOST);
  11827. cli.set_follow_location(true);
  11828. Params params;
  11829. params.emplace("url", "http://example.com");
  11830. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11832. EXPECT_EQ(StatusCode::OK_200, res->status);
  11833. }
  11834. TEST(HttpToHttpsRedirectTest, CertFile) {
  11835. auto ssl_port = PORT + 1;
  11836. Server svr;
  11837. ASSERT_TRUE(svr.is_valid());
  11838. svr.Get("/index", [&](const Request &, Response &res) {
  11839. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11840. "/index");
  11841. svr.stop();
  11842. });
  11843. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11844. ASSERT_TRUE(ssl_svr.is_valid());
  11845. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11846. res.set_content("test", "text/plain");
  11847. ssl_svr.stop();
  11848. });
  11849. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11850. thread t2 =
  11851. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11852. auto se = detail::scope_exit([&] {
  11853. t2.join();
  11854. t.join();
  11855. ASSERT_FALSE(svr.is_running());
  11856. });
  11857. svr.wait_until_ready();
  11858. ssl_svr.wait_until_ready();
  11859. Client cli("127.0.0.1", PORT);
  11860. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  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. TEST(SSLClientRedirectTest, CertFile) {
  11869. auto ssl_port = PORT + 1;
  11870. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11871. ASSERT_TRUE(ssl_svr1.is_valid());
  11872. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11873. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11874. "/index");
  11875. ssl_svr1.stop();
  11876. });
  11877. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11878. ASSERT_TRUE(ssl_svr2.is_valid());
  11879. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11880. res.set_content("test", "text/plain");
  11881. ssl_svr2.stop();
  11882. });
  11883. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11884. thread t2 =
  11885. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11886. auto se = detail::scope_exit([&] {
  11887. t2.join();
  11888. t.join();
  11889. ASSERT_FALSE(ssl_svr1.is_running());
  11890. });
  11891. ssl_svr1.wait_until_ready();
  11892. ssl_svr2.wait_until_ready();
  11893. SSLClient cli("127.0.0.1", PORT);
  11894. std::string cert;
  11895. read_file(SERVER_CERT2_FILE, cert);
  11896. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11897. cli.enable_server_certificate_verification(true);
  11898. cli.set_follow_location(true);
  11899. cli.set_connection_timeout(30);
  11900. auto res = cli.Get("/index");
  11901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11902. ASSERT_EQ(StatusCode::OK_200, res->status);
  11903. }
  11904. #endif
  11905. #ifdef CPPHTTPLIB_SSL_ENABLED
  11906. // Test that set_ca_cert_store() skips system certs (consistent with
  11907. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11908. // should be trusted - system certs should NOT be loaded.
  11909. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11910. // Load a specific cert that is NOT a system CA cert
  11911. std::string cert;
  11912. read_file(SERVER_CERT2_FILE, cert);
  11913. SSLClient cli("google.com");
  11914. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11915. cli.enable_server_certificate_verification(true);
  11916. // This should FAIL because:
  11917. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11918. // 2. System certs should NOT be loaded when custom store is set
  11919. // If system certs WERE loaded, this would succeed
  11920. auto res = cli.Get("/");
  11921. ASSERT_FALSE(res);
  11922. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11923. }
  11924. // Same as above, but through the native store handle path. Regression test:
  11925. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11926. // merged system certs into the user-provided store.
  11927. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11928. std::string cert;
  11929. read_file(SERVER_CERT2_FILE, cert);
  11930. SSLClient cli("google.com");
  11931. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11932. cli.enable_server_certificate_verification(true);
  11933. auto res = cli.Get("/");
  11934. ASSERT_FALSE(res);
  11935. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11936. }
  11937. // A custom store set via the native handle must still verify a server whose
  11938. // cert it does contain.
  11939. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11940. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11941. ASSERT_TRUE(svr.is_valid());
  11942. svr.Get("/test", [&](const Request &, Response &res) {
  11943. res.set_content("test", "text/plain");
  11944. });
  11945. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11946. auto se = detail::scope_exit([&] {
  11947. svr.stop();
  11948. t.join();
  11949. ASSERT_FALSE(svr.is_running());
  11950. });
  11951. svr.wait_until_ready();
  11952. SSLClient cli("127.0.0.1", PORT);
  11953. std::string cert;
  11954. read_file(SERVER_CERT2_FILE, cert);
  11955. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11956. cli.enable_server_certificate_verification(true);
  11957. cli.set_connection_timeout(30);
  11958. auto res = cli.Get("/test");
  11959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11960. ASSERT_EQ(StatusCode::OK_200, res->status);
  11961. }
  11962. // CA certs loaded through the universal Client must be transferred to the
  11963. // client created internally for following an HTTPS redirect. Regression test:
  11964. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11965. // the CA data for redirect transfer.
  11966. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11967. auto ssl_port = PORT + 1;
  11968. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11969. ASSERT_TRUE(ssl_svr1.is_valid());
  11970. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11971. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11972. "/index");
  11973. });
  11974. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11975. ASSERT_TRUE(ssl_svr2.is_valid());
  11976. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11977. res.set_content("test", "text/plain");
  11978. });
  11979. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11980. thread t2 =
  11981. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11982. auto se = detail::scope_exit([&] {
  11983. ssl_svr2.stop();
  11984. ssl_svr1.stop();
  11985. t2.join();
  11986. t.join();
  11987. ASSERT_FALSE(ssl_svr1.is_running());
  11988. });
  11989. ssl_svr1.wait_until_ready();
  11990. ssl_svr2.wait_until_ready();
  11991. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11992. std::string cert;
  11993. read_file(SERVER_CERT2_FILE, cert);
  11994. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11995. cli.enable_server_certificate_verification(true);
  11996. cli.set_follow_location(true);
  11997. cli.set_connection_timeout(30);
  11998. auto res = cli.Get("/index");
  11999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12000. ASSERT_EQ(StatusCode::OK_200, res->status);
  12001. }
  12002. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12003. // so a host signed by a system CA verifies even though a custom CA is set
  12004. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12005. std::string cert;
  12006. read_file(SERVER_CERT2_FILE, cert);
  12007. SSLClient cli("google.com");
  12008. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12009. cli.enable_system_ca(true);
  12010. cli.enable_server_certificate_verification(true);
  12011. auto res = cli.Get("/");
  12012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12013. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12014. }
  12015. // The custom CA remains effective when combined with the system CA
  12016. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12017. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12018. ASSERT_TRUE(svr.is_valid());
  12019. svr.Get("/test", [&](const Request &, Response &res) {
  12020. res.set_content("test", "text/plain");
  12021. });
  12022. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12023. auto se = detail::scope_exit([&] {
  12024. svr.stop();
  12025. t.join();
  12026. ASSERT_FALSE(svr.is_running());
  12027. });
  12028. svr.wait_until_ready();
  12029. SSLClient cli("127.0.0.1", PORT);
  12030. std::string cert;
  12031. read_file(SERVER_CERT2_FILE, cert);
  12032. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12033. cli.enable_system_ca(true);
  12034. cli.enable_server_certificate_verification(true);
  12035. cli.set_connection_timeout(30);
  12036. auto res = cli.Get("/test");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. ASSERT_EQ(StatusCode::OK_200, res->status);
  12039. }
  12040. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12041. // skip chain verification entirely (only the certificate identity was
  12042. // checked), so a server presenting an untrusted certificate with a matching
  12043. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12044. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12045. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12046. ASSERT_TRUE(svr.is_valid());
  12047. svr.Get("/test", [&](const Request &, Response &res) {
  12048. res.set_content("test", "text/plain");
  12049. });
  12050. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12051. auto se = detail::scope_exit([&] {
  12052. svr.stop();
  12053. t.join();
  12054. ASSERT_FALSE(svr.is_running());
  12055. });
  12056. svr.wait_until_ready();
  12057. SSLClient cli("127.0.0.1", PORT);
  12058. std::string cert;
  12059. // A trusted CA that did not sign the server certificate. The server cert
  12060. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12061. // this connection.
  12062. read_file(CLIENT_CA_CERT_FILE, cert);
  12063. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12064. cli.enable_server_certificate_verification(true);
  12065. cli.set_connection_timeout(30);
  12066. auto res = cli.Get("/test");
  12067. ASSERT_FALSE(res);
  12068. }
  12069. // enable_system_ca(false) prevents system CA loading entirely
  12070. TEST(SSLClientTest, DisableSystemCa_Online) {
  12071. SSLClient cli("google.com");
  12072. cli.enable_system_ca(false);
  12073. cli.enable_server_certificate_verification(true);
  12074. auto res = cli.Get("/");
  12075. ASSERT_FALSE(res);
  12076. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12077. // itself when the CA chain is empty
  12078. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12079. res.error() == Error::SSLConnection);
  12080. }
  12081. // The universal Client forwards enable_system_ca()
  12082. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12083. std::string cert;
  12084. read_file(SERVER_CERT2_FILE, cert);
  12085. Client cli("https://google.com");
  12086. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12087. cli.enable_system_ca(true);
  12088. cli.enable_server_certificate_verification(true);
  12089. auto res = cli.Get("/");
  12090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12091. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12092. }
  12093. // The system CA policy must carry over to the client created internally for
  12094. // following a cross-host HTTPS redirect
  12095. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12096. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12097. ASSERT_TRUE(svr.is_valid());
  12098. svr.Get("/index", [&](const Request &, Response &res) {
  12099. res.set_redirect("https://www.google.com/");
  12100. });
  12101. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12102. auto se = detail::scope_exit([&] {
  12103. svr.stop();
  12104. t.join();
  12105. ASSERT_FALSE(svr.is_running());
  12106. });
  12107. svr.wait_until_ready();
  12108. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12109. std::string cert;
  12110. read_file(SERVER_CERT2_FILE, cert);
  12111. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12112. cli.enable_system_ca(true);
  12113. cli.enable_server_certificate_verification(true);
  12114. cli.set_follow_location(true);
  12115. cli.set_connection_timeout(30);
  12116. // Receiving any response proves the redirect client completed the TLS
  12117. // handshake with a system-CA-signed host
  12118. auto res = cli.Get("/index");
  12119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12120. }
  12121. TEST(MultipartFormDataTest, LargeData) {
  12122. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12123. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12124. const ContentReader &content_reader) {
  12125. if (req.is_multipart_form_data()) {
  12126. std::vector<FormData> items;
  12127. content_reader(
  12128. [&](const FormData &file) {
  12129. items.push_back(file);
  12130. return true;
  12131. },
  12132. [&](const char *data, size_t data_length) {
  12133. items.back().content.append(data, data_length);
  12134. return true;
  12135. });
  12136. EXPECT_TRUE(std::string(items[0].name) == "document");
  12137. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12138. EXPECT_TRUE(items[0].filename == "2MB_data");
  12139. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12140. EXPECT_TRUE(items[1].name == "hello");
  12141. EXPECT_TRUE(items[1].content == "world");
  12142. EXPECT_TRUE(items[1].filename == "");
  12143. EXPECT_TRUE(items[1].content_type == "");
  12144. } else {
  12145. std::string body;
  12146. content_reader([&](const char *data, size_t data_length) {
  12147. body.append(data, data_length);
  12148. return true;
  12149. });
  12150. }
  12151. });
  12152. auto port = svr.bind_to_any_port(HOST);
  12153. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12154. auto se = detail::scope_exit([&] {
  12155. svr.stop();
  12156. t.join();
  12157. ASSERT_FALSE(svr.is_running());
  12158. });
  12159. svr.wait_until_ready();
  12160. {
  12161. std::string data(1024 * 1024 * 2, '.');
  12162. std::stringstream buffer;
  12163. buffer << data;
  12164. SSLClient cli(HOST, port);
  12165. cli.enable_server_certificate_verification(false);
  12166. UploadFormDataItems items{
  12167. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12168. {"hello", "world", "", ""},
  12169. };
  12170. auto res = cli.Post("/post", items);
  12171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12172. ASSERT_EQ(StatusCode::OK_200, res->status);
  12173. }
  12174. }
  12175. TEST(MultipartFormDataTest, DataProviderItems) {
  12176. std::random_device seed_gen;
  12177. std::mt19937 random(seed_gen());
  12178. std::string rand1;
  12179. rand1.resize(1000);
  12180. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12181. std::string rand2;
  12182. rand2.resize(3000);
  12183. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12185. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12186. const ContentReader &content_reader) {
  12187. ASSERT_FALSE(req.is_multipart_form_data());
  12188. std::string body;
  12189. content_reader([&](const char *data, size_t data_length) {
  12190. body.append(data, data_length);
  12191. return true;
  12192. });
  12193. EXPECT_EQ(body, "");
  12194. });
  12195. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12196. const ContentReader &content_reader) {
  12197. ASSERT_TRUE(req.is_multipart_form_data());
  12198. std::vector<FormData> items;
  12199. content_reader(
  12200. [&](const FormData &file) {
  12201. items.push_back(file);
  12202. return true;
  12203. },
  12204. [&](const char *data, size_t data_length) {
  12205. items.back().content.append(data, data_length);
  12206. return true;
  12207. });
  12208. ASSERT_TRUE(items.size() == 2);
  12209. EXPECT_EQ(std::string(items[0].name), "name1");
  12210. EXPECT_EQ(items[0].content, "Testing123");
  12211. EXPECT_EQ(items[0].filename, "filename1");
  12212. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12213. EXPECT_EQ(items[1].name, "name2");
  12214. EXPECT_EQ(items[1].content, "Testing456");
  12215. EXPECT_EQ(items[1].filename, "");
  12216. EXPECT_EQ(items[1].content_type, "");
  12217. });
  12218. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12219. const ContentReader &content_reader) {
  12220. ASSERT_TRUE(req.is_multipart_form_data());
  12221. std::vector<FormData> items;
  12222. content_reader(
  12223. [&](const FormData &file) {
  12224. items.push_back(file);
  12225. return true;
  12226. },
  12227. [&](const char *data, size_t data_length) {
  12228. items.back().content.append(data, data_length);
  12229. return true;
  12230. });
  12231. ASSERT_TRUE(items.size() == 2);
  12232. EXPECT_EQ(items[0].name, "name3");
  12233. EXPECT_EQ(items[0].content, rand1);
  12234. EXPECT_EQ(items[0].filename, "filename3");
  12235. EXPECT_EQ(items[0].content_type, "");
  12236. EXPECT_EQ(items[1].name, "name4");
  12237. EXPECT_EQ(items[1].content, rand2);
  12238. EXPECT_EQ(items[1].filename, "filename4");
  12239. EXPECT_EQ(items[1].content_type, "");
  12240. });
  12241. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12242. const ContentReader &content_reader) {
  12243. ASSERT_TRUE(req.is_multipart_form_data());
  12244. std::vector<FormData> items;
  12245. content_reader(
  12246. [&](const FormData &file) {
  12247. items.push_back(file);
  12248. return true;
  12249. },
  12250. [&](const char *data, size_t data_length) {
  12251. items.back().content.append(data, data_length);
  12252. return true;
  12253. });
  12254. ASSERT_TRUE(items.size() == 4);
  12255. EXPECT_EQ(std::string(items[0].name), "name1");
  12256. EXPECT_EQ(items[0].content, "Testing123");
  12257. EXPECT_EQ(items[0].filename, "filename1");
  12258. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12259. EXPECT_EQ(items[1].name, "name2");
  12260. EXPECT_EQ(items[1].content, "Testing456");
  12261. EXPECT_EQ(items[1].filename, "");
  12262. EXPECT_EQ(items[1].content_type, "");
  12263. EXPECT_EQ(items[2].name, "name3");
  12264. EXPECT_EQ(items[2].content, rand1);
  12265. EXPECT_EQ(items[2].filename, "filename3");
  12266. EXPECT_EQ(items[2].content_type, "");
  12267. EXPECT_EQ(items[3].name, "name4");
  12268. EXPECT_EQ(items[3].content, rand2);
  12269. EXPECT_EQ(items[3].filename, "filename4");
  12270. EXPECT_EQ(items[3].content_type, "");
  12271. });
  12272. auto port = svr.bind_to_any_port("localhost");
  12273. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. t.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. {
  12281. SSLClient cli("localhost", port);
  12282. cli.enable_server_certificate_verification(false);
  12283. UploadFormDataItems items{
  12284. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12285. {"name2", "Testing456", "", ""}, // not a file
  12286. };
  12287. {
  12288. auto res = cli.Post("/post-none", {}, {}, {});
  12289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12290. ASSERT_EQ(StatusCode::OK_200, res->status);
  12291. }
  12292. FormDataProviderItems providers;
  12293. {
  12294. auto res =
  12295. cli.Post("/post-items", {}, items, providers); // empty providers
  12296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12297. ASSERT_EQ(StatusCode::OK_200, res->status);
  12298. }
  12299. providers.push_back({"name3",
  12300. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12301. // test the offset is given correctly at each step
  12302. if (!offset)
  12303. sink.os.write(rand1.data(), 30);
  12304. else if (offset == 30)
  12305. sink.os.write(rand1.data() + 30, 300);
  12306. else if (offset == 330)
  12307. sink.os.write(rand1.data() + 330, 670);
  12308. else if (offset == rand1.size())
  12309. sink.done();
  12310. return true;
  12311. },
  12312. "filename3",
  12313. {}});
  12314. providers.push_back({"name4",
  12315. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12316. // test the offset is given correctly at each step
  12317. if (!offset)
  12318. sink.os.write(rand2.data(), 2000);
  12319. else if (offset == 2000)
  12320. sink.os.write(rand2.data() + 2000, 1);
  12321. else if (offset == 2001)
  12322. sink.os.write(rand2.data() + 2001, 999);
  12323. else if (offset == rand2.size())
  12324. sink.done();
  12325. return true;
  12326. },
  12327. "filename4",
  12328. {}});
  12329. {
  12330. auto res = cli.Post("/post-providers", {}, {}, providers);
  12331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12332. ASSERT_EQ(StatusCode::OK_200, res->status);
  12333. }
  12334. {
  12335. auto res = cli.Post("/post-both", {}, items, providers);
  12336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12337. ASSERT_EQ(StatusCode::OK_200, res->status);
  12338. }
  12339. }
  12340. }
  12341. TEST(MultipartFormDataTest, BadHeader) {
  12342. Server svr;
  12343. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12344. res.set_content("ok", "text/plain");
  12345. });
  12346. thread t = thread([&] { svr.listen(HOST, PORT); });
  12347. auto se = detail::scope_exit([&] {
  12348. svr.stop();
  12349. t.join();
  12350. ASSERT_FALSE(svr.is_running());
  12351. });
  12352. svr.wait_until_ready();
  12353. const std::string body =
  12354. "This is the preamble. It is to be ignored, though it\r\n"
  12355. "is a handy place for composition agents to include an\r\n"
  12356. "explanatory note to non-MIME conformant readers.\r\n"
  12357. "\r\n"
  12358. "\r\n"
  12359. "--simple boundary\r\n"
  12360. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12361. ": BAD...\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::BadRequest_400, res->status);
  12377. }
  12378. TEST(MultipartFormDataTest, WithPreamble) {
  12379. Server svr;
  12380. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12381. res.set_content("ok", "text/plain");
  12382. });
  12383. thread t = thread([&] { svr.listen(HOST, PORT); });
  12384. auto se = detail::scope_exit([&] {
  12385. svr.stop();
  12386. t.join();
  12387. ASSERT_FALSE(svr.is_running());
  12388. });
  12389. svr.wait_until_ready();
  12390. const std::string body =
  12391. "This is the preamble. It is to be ignored, though it\r\n"
  12392. "is a handy place for composition agents to include an\r\n"
  12393. "explanatory note to non-MIME conformant readers.\r\n"
  12394. "\r\n"
  12395. "\r\n"
  12396. "--simple boundary\r\n"
  12397. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12398. "\r\n"
  12399. "value1\r\n"
  12400. "--simple boundary\r\n"
  12401. "Content-Disposition: form-data; name=\"field2\"; "
  12402. "filename=\"example.txt\"\r\n"
  12403. "\r\n"
  12404. "value2\r\n"
  12405. "--simple boundary--\r\n"
  12406. "This is the epilogue. It is also to be ignored.\r\n";
  12407. std::string content_type =
  12408. R"(multipart/form-data; boundary="simple boundary")";
  12409. Client cli(HOST, PORT);
  12410. auto res = cli.Post("/post", body, content_type.c_str());
  12411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12412. EXPECT_EQ(StatusCode::OK_200, res->status);
  12413. }
  12414. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12416. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12417. const ContentReader &content_reader) {
  12418. if (req.is_multipart_form_data()) {
  12419. std::vector<FormData> items;
  12420. content_reader(
  12421. [&](const FormData &file) {
  12422. items.push_back(file);
  12423. return true;
  12424. },
  12425. [&](const char *data, size_t data_length) {
  12426. items.back().content.append(data, data_length);
  12427. return true;
  12428. });
  12429. EXPECT_TRUE(std::string(items[0].name) == "document");
  12430. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12431. EXPECT_TRUE(items[0].filename == "2MB_data");
  12432. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12433. EXPECT_TRUE(items[1].name == "hello");
  12434. EXPECT_TRUE(items[1].content == "world");
  12435. EXPECT_TRUE(items[1].filename == "");
  12436. EXPECT_TRUE(items[1].content_type == "");
  12437. } else {
  12438. std::string body;
  12439. content_reader([&](const char *data, size_t data_length) {
  12440. body.append(data, data_length);
  12441. return true;
  12442. });
  12443. }
  12444. });
  12445. auto port = svr.bind_to_any_port("localhost");
  12446. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12447. auto se = detail::scope_exit([&] {
  12448. svr.stop();
  12449. t.join();
  12450. ASSERT_FALSE(svr.is_running());
  12451. });
  12452. svr.wait_until_ready();
  12453. {
  12454. std::string data(1024 * 1024 * 2, '.');
  12455. std::stringstream buffer;
  12456. buffer << data;
  12457. SSLClient cli("localhost", port);
  12458. cli.enable_server_certificate_verification(false);
  12459. UploadFormDataItems items{
  12460. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12461. {"hello", "world", "", ""},
  12462. };
  12463. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. ASSERT_EQ(StatusCode::OK_200, res->status);
  12466. }
  12467. }
  12468. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12469. std::string data(1024 * 1024 * 2, '&');
  12470. std::stringstream buffer;
  12471. buffer << data;
  12472. Client cli("https://localhost:8080");
  12473. UploadFormDataItems items{
  12474. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12475. {"hello", "world", "", ""},
  12476. };
  12477. for (const char &c : " \t\r\n") {
  12478. auto res =
  12479. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12480. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12481. ASSERT_FALSE(res);
  12482. }
  12483. }
  12484. TEST(MultipartFormDataTest, PutFormData) {
  12485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12486. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12487. const ContentReader &content_reader) {
  12488. if (req.is_multipart_form_data()) {
  12489. std::vector<FormData> items;
  12490. content_reader(
  12491. [&](const FormData &file) {
  12492. items.push_back(file);
  12493. return true;
  12494. },
  12495. [&](const char *data, size_t data_length) {
  12496. items.back().content.append(data, data_length);
  12497. return true;
  12498. });
  12499. EXPECT_TRUE(std::string(items[0].name) == "document");
  12500. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12501. EXPECT_TRUE(items[0].filename == "2MB_data");
  12502. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12503. EXPECT_TRUE(items[1].name == "hello");
  12504. EXPECT_TRUE(items[1].content == "world");
  12505. EXPECT_TRUE(items[1].filename == "");
  12506. EXPECT_TRUE(items[1].content_type == "");
  12507. } else {
  12508. std::string body;
  12509. content_reader([&](const char *data, size_t data_length) {
  12510. body.append(data, data_length);
  12511. return true;
  12512. });
  12513. }
  12514. });
  12515. auto port = svr.bind_to_any_port("localhost");
  12516. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12517. auto se = detail::scope_exit([&] {
  12518. svr.stop();
  12519. t.join();
  12520. ASSERT_FALSE(svr.is_running());
  12521. });
  12522. svr.wait_until_ready();
  12523. {
  12524. std::string data(1024 * 1024 * 2, '&');
  12525. std::stringstream buffer;
  12526. buffer << data;
  12527. SSLClient cli("localhost", port);
  12528. cli.enable_server_certificate_verification(false);
  12529. UploadFormDataItems items{
  12530. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12531. {"hello", "world", "", ""},
  12532. };
  12533. auto res = cli.Put("/put", items);
  12534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12535. ASSERT_EQ(StatusCode::OK_200, res->status);
  12536. }
  12537. }
  12538. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12540. svr.Put("/put_customboundary",
  12541. [&](const Request &req, const Response & /*res*/,
  12542. const ContentReader &content_reader) {
  12543. if (req.is_multipart_form_data()) {
  12544. std::vector<FormData> items;
  12545. content_reader(
  12546. [&](const FormData &file) {
  12547. items.push_back(file);
  12548. return true;
  12549. },
  12550. [&](const char *data, size_t data_length) {
  12551. items.back().content.append(data, data_length);
  12552. return true;
  12553. });
  12554. EXPECT_TRUE(std::string(items[0].name) == "document");
  12555. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12556. EXPECT_TRUE(items[0].filename == "2MB_data");
  12557. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12558. EXPECT_TRUE(items[1].name == "hello");
  12559. EXPECT_TRUE(items[1].content == "world");
  12560. EXPECT_TRUE(items[1].filename == "");
  12561. EXPECT_TRUE(items[1].content_type == "");
  12562. } else {
  12563. std::string body;
  12564. content_reader([&](const char *data, size_t data_length) {
  12565. body.append(data, data_length);
  12566. return true;
  12567. });
  12568. }
  12569. });
  12570. auto port = svr.bind_to_any_port("localhost");
  12571. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12572. auto se = detail::scope_exit([&] {
  12573. svr.stop();
  12574. t.join();
  12575. ASSERT_FALSE(svr.is_running());
  12576. });
  12577. svr.wait_until_ready();
  12578. {
  12579. std::string data(1024 * 1024 * 2, '&');
  12580. std::stringstream buffer;
  12581. buffer << data;
  12582. SSLClient cli("localhost", port);
  12583. cli.enable_server_certificate_verification(false);
  12584. UploadFormDataItems items{
  12585. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12586. {"hello", "world", "", ""},
  12587. };
  12588. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. ASSERT_EQ(StatusCode::OK_200, res->status);
  12591. }
  12592. }
  12593. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12594. std::string data(1024 * 1024 * 2, '&');
  12595. std::stringstream buffer;
  12596. buffer << data;
  12597. Client cli("https://localhost:8080");
  12598. cli.enable_server_certificate_verification(false);
  12599. UploadFormDataItems items{
  12600. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12601. {"hello", "world", "", ""},
  12602. };
  12603. for (const char &c : " \t\r\n") {
  12604. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12605. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12606. ASSERT_FALSE(res);
  12607. }
  12608. }
  12609. TEST(MultipartFormDataTest, AlternateFilename) {
  12610. auto handled = false;
  12611. Server svr;
  12612. svr.Post("/test", [&](const Request &req, Response &res) {
  12613. ASSERT_EQ(2u, req.form.files.size());
  12614. ASSERT_EQ(1u, req.form.fields.size());
  12615. // Test files
  12616. const auto &file1 = req.form.get_file("file1");
  12617. ASSERT_EQ("file1", file1.name);
  12618. ASSERT_EQ("A.txt", file1.filename);
  12619. ASSERT_EQ("text/plain", file1.content_type);
  12620. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12621. const auto &file2 = req.form.get_file("file2");
  12622. ASSERT_EQ("file2", file2.name);
  12623. ASSERT_EQ("a.html", file2.filename);
  12624. ASSERT_EQ("text/html", file2.content_type);
  12625. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12626. file2.content);
  12627. // Test text field
  12628. const auto &text = req.form.get_field("text");
  12629. ASSERT_EQ("text default", text);
  12630. res.set_content("ok", "text/plain");
  12631. handled = true;
  12632. });
  12633. thread t = thread([&] { svr.listen(HOST, PORT); });
  12634. auto se = detail::scope_exit([&] {
  12635. svr.stop();
  12636. t.join();
  12637. ASSERT_FALSE(svr.is_running());
  12638. ASSERT_TRUE(handled);
  12639. });
  12640. svr.wait_until_ready();
  12641. auto req = "POST /test HTTP/1.1\r\n"
  12642. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12643. "Content-Length: 399\r\n"
  12644. "\r\n"
  12645. "----------\r\n"
  12646. "Content-Disposition: form-data; name=\"text\"\r\n"
  12647. "\r\n"
  12648. "text default\r\n"
  12649. "----------\r\n"
  12650. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12651. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12652. "Content-Type: text/plain\r\n"
  12653. "\r\n"
  12654. "Content of a.txt.\r\n"
  12655. "\r\n"
  12656. "----------\r\n"
  12657. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12658. "\"a.html\"\r\n"
  12659. "Content-Type: text/html\r\n"
  12660. "\r\n"
  12661. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12662. "\r\n"
  12663. "------------\r\n";
  12664. ASSERT_TRUE(send_request(1, req));
  12665. }
  12666. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12667. auto handled = false;
  12668. Server svr;
  12669. svr.Post("/test", [&](const Request &req, Response &res) {
  12670. // Case-insensitive "utf-8''" prefix with a long value
  12671. const auto &file = req.form.get_file("file1");
  12672. ASSERT_EQ("file1", file.name);
  12673. // 8000 chars exercises both the Content-Disposition parser and the
  12674. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12675. // Prior to the fix, std::regex_match on this header would cause O(N)
  12676. // stack recursion in libstdc++, leading to SIGSEGV.
  12677. std::string expected_filename(8000, 'A');
  12678. ASSERT_EQ(expected_filename, file.filename);
  12679. res.set_content("ok", "text/plain");
  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. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12691. // Regression test for GHSA-qq6v-r583-3h69
  12692. std::string long_filename(8000, 'A');
  12693. std::string body = "----------\r\n"
  12694. "Content-Disposition: form-data; name=\"file1\"; "
  12695. "filename*=\"Utf-8''" +
  12696. long_filename +
  12697. "\"\r\n"
  12698. "\r\n"
  12699. "hello\r\n"
  12700. "------------\r\n";
  12701. auto req = "POST /test HTTP/1.1\r\n"
  12702. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12703. "Content-Length: " +
  12704. std::to_string(body.size()) + "\r\n\r\n" + body;
  12705. ASSERT_TRUE(send_request(1, req));
  12706. }
  12707. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12708. auto handled = false;
  12709. Server svr;
  12710. svr.Post("/test", [&](const Request &req, Response &) {
  12711. ASSERT_EQ(2u, req.form.fields.size());
  12712. const auto &text1 = req.form.get_field("text1");
  12713. ASSERT_EQ("text1", text1);
  12714. const auto &text2 = req.form.get_field("text2");
  12715. ASSERT_EQ("text2", text2);
  12716. handled = true;
  12717. });
  12718. thread t = thread([&] { svr.listen(HOST, PORT); });
  12719. auto se = detail::scope_exit([&] {
  12720. svr.stop();
  12721. t.join();
  12722. ASSERT_FALSE(svr.is_running());
  12723. ASSERT_TRUE(handled);
  12724. });
  12725. svr.wait_until_ready();
  12726. auto req = "POST /test HTTP/1.1\r\n"
  12727. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12728. "Content-Length: 146\r\n"
  12729. "\r\n----------\r\n"
  12730. "Content-Disposition: form-data; name=\"text1\"\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------------";
  12738. std::string response;
  12739. ASSERT_TRUE(send_request(1, req, &response));
  12740. ASSERT_EQ("200", response.substr(9, 3));
  12741. }
  12742. TEST(MultipartFormDataTest, ContentLength) {
  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. const auto &text2 = req.form.get_field("text2");
  12750. ASSERT_EQ("text2", text2);
  12751. handled = true;
  12752. });
  12753. thread t = thread([&] { svr.listen(HOST, PORT); });
  12754. auto se = detail::scope_exit([&] {
  12755. svr.stop();
  12756. t.join();
  12757. ASSERT_FALSE(svr.is_running());
  12758. ASSERT_TRUE(handled);
  12759. });
  12760. svr.wait_until_ready();
  12761. auto req = "POST /test HTTP/1.1\r\n"
  12762. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12763. "Content-Length: 167\r\n"
  12764. "\r\n----------\r\n"
  12765. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12766. "Content-Length: 5\r\n"
  12767. "\r\n"
  12768. "text1"
  12769. "\r\n----------\r\n"
  12770. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12771. "\r\n"
  12772. "text2"
  12773. "\r\n------------\r\n";
  12774. std::string response;
  12775. ASSERT_TRUE(send_request(1, req, &response));
  12776. ASSERT_EQ("200", response.substr(9, 3));
  12777. }
  12778. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12779. auto handled = false;
  12780. Server svr;
  12781. svr.Post("/test", [&](const Request &req, Response &) {
  12782. ASSERT_EQ(2u, req.form.fields.size());
  12783. const auto &text1 = req.form.get_field("text1");
  12784. ASSERT_EQ("text1", text1);
  12785. // TODO: Add header access for text fields if needed
  12786. const auto &text2 = req.form.get_field("text2");
  12787. ASSERT_EQ("text2", text2);
  12788. // TODO: Header access for text fields needs to be implemented
  12789. // auto &headers = it->second.headers;
  12790. // ASSERT_EQ(3U, headers.size());
  12791. // auto custom_header = headers.find("x-whatever");
  12792. // ASSERT_TRUE(custom_header != headers.end());
  12793. // ASSERT_NE("customvalue", custom_header->second);
  12794. // ASSERT_EQ("CustomValue", custom_header->second);
  12795. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12796. handled = true;
  12797. });
  12798. thread t = thread([&] { svr.listen(HOST, PORT); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. ASSERT_FALSE(svr.is_running());
  12803. ASSERT_TRUE(handled);
  12804. });
  12805. svr.wait_until_ready();
  12806. auto req = "POST /test HTTP/1.1\r\n"
  12807. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12808. "Content-Length: 232\r\n"
  12809. "\r\n----------\r\n"
  12810. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12811. "Content-Length: 5\r\n"
  12812. "X-Test: 1\r\n"
  12813. "\r\n"
  12814. "text1"
  12815. "\r\n----------\r\n"
  12816. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12817. "Content-Type: text/plain\r\n"
  12818. "X-Whatever: CustomValue\r\n"
  12819. "\r\n"
  12820. "text2"
  12821. "\r\n------------\r\n"
  12822. "That should be disregarded. Not even read";
  12823. std::string response;
  12824. ASSERT_TRUE(send_request(1, req, &response));
  12825. ASSERT_EQ("200", response.substr(9, 3));
  12826. }
  12827. TEST(MultipartFormDataTest, LargeHeader) {
  12828. auto handled = false;
  12829. Server svr;
  12830. svr.Post("/test", [&](const Request &req, Response &) {
  12831. ASSERT_EQ(1u, req.form.fields.size());
  12832. const auto &text = req.form.get_field("name1");
  12833. ASSERT_EQ("text1", text);
  12834. handled = true;
  12835. });
  12836. thread t = thread([&] { svr.listen(HOST, PORT); });
  12837. auto se = detail::scope_exit([&] {
  12838. svr.stop();
  12839. t.join();
  12840. ASSERT_FALSE(svr.is_running());
  12841. ASSERT_TRUE(handled);
  12842. });
  12843. svr.wait_until_ready();
  12844. auto boundary = std::string("cpp-httplib-multipart-data");
  12845. std::string content = "--" + boundary +
  12846. "\r\n"
  12847. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12848. "\r\n"
  12849. "text1\r\n"
  12850. "--" +
  12851. boundary + "--\r\n";
  12852. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12853. "Content-Type: multipart/form-data;boundary=" +
  12854. boundary +
  12855. "\r\n"
  12856. "Content-Length: " +
  12857. std::to_string(content.size()) +
  12858. "\r\n"
  12859. "Dummy-Header: ";
  12860. std::string header_suffix = "\r\n"
  12861. "\r\n";
  12862. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12863. size_t header_dummy_size =
  12864. read_buff_size -
  12865. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12866. auto header_dummy = std::string(header_dummy_size, '@');
  12867. auto req = header_prefix + header_dummy + header_suffix + content;
  12868. std::string response;
  12869. ASSERT_TRUE(send_request(1, req, &response));
  12870. ASSERT_EQ("200", response.substr(9, 3));
  12871. }
  12872. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12873. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12874. // (not chunked Transfer-Encoding) after the streaming refactor.
  12875. auto handled = false;
  12876. Server svr;
  12877. svr.Post("/upload", [&](const Request &req, Response &res) {
  12878. auto cl_it = req.headers.find("Content-Length");
  12879. EXPECT_TRUE(cl_it != req.headers.end());
  12880. auto te_it = req.headers.find("Transfer-Encoding");
  12881. EXPECT_TRUE(te_it == req.headers.end());
  12882. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12883. res.set_content("ok", "text/plain");
  12884. handled = true;
  12885. });
  12886. auto port = svr.bind_to_any_port(HOST);
  12887. auto t = thread([&] { svr.listen_after_bind(); });
  12888. auto se = detail::scope_exit([&] {
  12889. svr.stop();
  12890. t.join();
  12891. ASSERT_FALSE(svr.is_running());
  12892. ASSERT_TRUE(handled);
  12893. });
  12894. svr.wait_until_ready();
  12895. UploadFormDataItems items = {
  12896. {"field1", "hello", "", "text/plain"},
  12897. {"file1", "world", "test.txt", "application/octet-stream"},
  12898. };
  12899. Client cli(HOST, port);
  12900. auto res = cli.Post("/upload", {}, items);
  12901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12902. EXPECT_EQ(StatusCode::OK_200, res->status);
  12903. }
  12904. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12905. // Verify that make_multipart_content_provider coalesces many small segments
  12906. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12907. constexpr size_t kItemCount = 1000;
  12908. UploadFormDataItems items;
  12909. items.reserve(kItemCount);
  12910. for (size_t i = 0; i < kItemCount; i++) {
  12911. items.push_back(
  12912. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12913. }
  12914. const std::string boundary = "----test-boundary";
  12915. auto content_length = detail::get_multipart_content_length(items, boundary);
  12916. auto provider = detail::make_multipart_content_provider(items, boundary);
  12917. // Drive the provider the same way write_content_with_progress does
  12918. size_t write_count = 0;
  12919. size_t total_bytes = 0;
  12920. DataSink sink;
  12921. size_t offset = 0;
  12922. sink.write = [&](const char *d, size_t l) -> bool {
  12923. (void)d;
  12924. write_count++;
  12925. total_bytes += l;
  12926. offset += l;
  12927. return true;
  12928. };
  12929. sink.is_writable = []() -> bool { return true; };
  12930. while (offset < content_length) {
  12931. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12932. }
  12933. EXPECT_EQ(content_length, total_bytes);
  12934. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12935. // With buffering into 64KB blocks, write_count should be much smaller.
  12936. auto segment_count = 3 * kItemCount + 1;
  12937. EXPECT_LT(write_count, segment_count / 10);
  12938. }
  12939. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12940. // Integration test: send many UploadFormDataItems and verify the server
  12941. // receives all of them correctly (#2410).
  12942. constexpr size_t kItemCount = 500;
  12943. auto handled = false;
  12944. Server svr;
  12945. svr.Post("/upload", [&](const Request &req, Response &res) {
  12946. EXPECT_EQ(kItemCount, req.form.fields.size());
  12947. for (size_t i = 0; i < kItemCount; i++) {
  12948. auto key = "field" + std::to_string(i);
  12949. auto val = "value" + std::to_string(i);
  12950. auto it = req.form.fields.find(key);
  12951. if (it != req.form.fields.end()) {
  12952. EXPECT_EQ(val, it->second.content);
  12953. } else {
  12954. ADD_FAILURE() << "Missing field: " << key;
  12955. }
  12956. }
  12957. res.set_content("ok", "text/plain");
  12958. handled = true;
  12959. });
  12960. auto port = svr.bind_to_any_port(HOST);
  12961. auto t = thread([&] { svr.listen_after_bind(); });
  12962. auto se = detail::scope_exit([&] {
  12963. svr.stop();
  12964. t.join();
  12965. ASSERT_FALSE(svr.is_running());
  12966. ASSERT_TRUE(handled);
  12967. });
  12968. svr.wait_until_ready();
  12969. UploadFormDataItems items;
  12970. items.reserve(kItemCount);
  12971. for (size_t i = 0; i < kItemCount; i++) {
  12972. items.push_back(
  12973. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12974. }
  12975. Client cli(HOST, port);
  12976. auto res = cli.Post("/upload", items);
  12977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12978. EXPECT_EQ(StatusCode::OK_200, res->status);
  12979. }
  12980. TEST(MultipartFormDataTest, MakeFileProvider) {
  12981. // Verify make_file_provider sends a file's contents correctly.
  12982. const std::string file_content(4096, 'Z');
  12983. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12984. {
  12985. std::ofstream ofs(tmp_path, std::ios::binary);
  12986. ofs.write(file_content.data(),
  12987. static_cast<std::streamsize>(file_content.size()));
  12988. }
  12989. auto handled = false;
  12990. Server svr;
  12991. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12992. const ContentReader &content_reader) {
  12993. ASSERT_TRUE(req.is_multipart_form_data());
  12994. std::vector<FormData> items;
  12995. content_reader(
  12996. [&](const FormData &file) {
  12997. items.push_back(file);
  12998. return true;
  12999. },
  13000. [&](const char *data, size_t data_length) {
  13001. items.back().content.append(data, data_length);
  13002. return true;
  13003. });
  13004. ASSERT_EQ(1u, items.size());
  13005. EXPECT_EQ("myfile", items[0].name);
  13006. EXPECT_EQ("data.bin", items[0].filename);
  13007. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13008. EXPECT_EQ(file_content, items[0].content);
  13009. handled = true;
  13010. });
  13011. auto port = svr.bind_to_any_port(HOST);
  13012. auto t = thread([&] { svr.listen_after_bind(); });
  13013. auto se = detail::scope_exit([&] {
  13014. svr.stop();
  13015. t.join();
  13016. ASSERT_FALSE(svr.is_running());
  13017. ASSERT_TRUE(handled);
  13018. std::remove(tmp_path.c_str());
  13019. });
  13020. svr.wait_until_ready();
  13021. FormDataProviderItems providers;
  13022. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13023. "application/octet-stream"));
  13024. Client cli(HOST, port);
  13025. auto res = cli.Post("/upload", {}, {}, providers);
  13026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13027. EXPECT_EQ(StatusCode::OK_200, res->status);
  13028. }
  13029. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13030. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13031. // (100) headers is rejected with a 400 Bad Request response.
  13032. Server svr;
  13033. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13034. res.set_content("ok", "text/plain");
  13035. });
  13036. thread t = thread([&] { svr.listen(HOST, PORT); });
  13037. auto se = detail::scope_exit([&] {
  13038. svr.stop();
  13039. t.join();
  13040. ASSERT_FALSE(svr.is_running());
  13041. });
  13042. svr.wait_until_ready();
  13043. // Build a multipart part with 101 custom headers (exceeding
  13044. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13045. std::stringstream body;
  13046. body << "--simpleboundary\r\n"
  13047. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13048. for (int i = 0; i < 101; i++) {
  13049. body << "X-Custom-Header-" << i << ": value\r\n";
  13050. }
  13051. body << "\r\n"
  13052. << "value1\r\n"
  13053. << "--simpleboundary--\r\n";
  13054. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13055. Client cli(HOST, PORT);
  13056. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13058. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13059. }
  13060. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13061. // A body that never contains the declared boundary must not be accumulated
  13062. // while the parser waits for it. Buffering it would also make every read
  13063. // rescan everything seen so far, which is quadratic in the body size.
  13064. Server svr;
  13065. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13066. res.set_content("ok", "text/plain");
  13067. });
  13068. auto port = svr.bind_to_any_port(HOST);
  13069. thread t = thread([&] { svr.listen_after_bind(); });
  13070. auto se = detail::scope_exit([&] {
  13071. svr.stop();
  13072. t.join();
  13073. ASSERT_FALSE(svr.is_running());
  13074. });
  13075. svr.wait_until_ready();
  13076. Client cli(HOST, port);
  13077. cli.set_read_timeout(60, 0);
  13078. cli.set_write_timeout(60, 0);
  13079. // '-' is the worst case: it matches the first character of the boundary, so
  13080. // every position has to be checked against it.
  13081. auto post_dashes = [&](size_t size) {
  13082. const std::string body(size, '-');
  13083. auto start = std::chrono::steady_clock::now();
  13084. auto res =
  13085. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13086. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13087. std::chrono::steady_clock::now() - start)
  13088. .count();
  13089. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13090. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13091. return ms;
  13092. };
  13093. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13094. // Windows.
  13095. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13096. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13097. // Comparing the two sizes rather than checking an absolute duration keeps
  13098. // this meaningful across build types and CI load, both of which move the
  13099. // absolute numbers by more than an order of magnitude. Four times the bytes
  13100. // costs about four times the time when parsing is linear, and about sixteen
  13101. // times when the body is buffered and rescanned.
  13102. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13103. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13104. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13105. << "ms, which suggests the body is being buffered and rescanned";
  13106. }
  13107. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13108. // A boundary can only be followed by CRLF or by "--", so anything else is
  13109. // malformed no matter what comes next. The parser must say so right away
  13110. // instead of buffering the rest of the declared body.
  13111. Server svr;
  13112. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13113. res.set_content("ok", "text/plain");
  13114. });
  13115. auto port = svr.bind_to_any_port(HOST);
  13116. thread t = thread([&] { svr.listen_after_bind(); });
  13117. auto se = detail::scope_exit([&] {
  13118. svr.stop();
  13119. t.join();
  13120. ASSERT_FALSE(svr.is_running());
  13121. });
  13122. svr.wait_until_ready();
  13123. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13124. // buffers instead of failing would still be waiting for the remaining bytes.
  13125. const std::string body = "--zzzz\r\n"
  13126. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13127. "\r\n"
  13128. "text1"
  13129. "\r\n--zzzzXX";
  13130. const std::string req = "POST /post HTTP/1.1\r\n"
  13131. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13132. "Content-Length: 1048576\r\n"
  13133. "\r\n" +
  13134. body;
  13135. std::string response;
  13136. ASSERT_TRUE(send_request(3, req, &response, port));
  13137. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13138. EXPECT_EQ("400", response.substr(9, 3));
  13139. }
  13140. // Posts a multipart body split into two writes, so that the server sees the
  13141. // split at whatever offset the caller chose, and expects the single "text1"
  13142. // field to come through.
  13143. static void expect_split_multipart_ok(const std::string &body1,
  13144. const std::string &body2) {
  13145. auto handled = false;
  13146. Server svr;
  13147. svr.Post("/post", [&](const Request &req, Response &) {
  13148. EXPECT_EQ(1u, req.form.fields.size());
  13149. EXPECT_EQ("text1", req.form.get_field("text1"));
  13150. handled = true;
  13151. });
  13152. auto port = svr.bind_to_any_port(HOST);
  13153. thread t = thread([&] { svr.listen_after_bind(); });
  13154. auto se = detail::scope_exit([&] {
  13155. svr.stop();
  13156. t.join();
  13157. ASSERT_FALSE(svr.is_running());
  13158. ASSERT_TRUE(handled);
  13159. });
  13160. svr.wait_until_ready();
  13161. // "Connection: close" makes the server close once it has answered, so the
  13162. // response drain ends immediately instead of idling until the read timeout.
  13163. const std::string head =
  13164. "POST /post HTTP/1.1\r\n"
  13165. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13166. "Connection: close\r\n"
  13167. "Content-Length: " +
  13168. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13169. std::string response;
  13170. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13171. ASSERT_GE(response.size(), 12u) << "no response";
  13172. EXPECT_EQ("200", response.substr(9, 3));
  13173. }
  13174. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13175. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13176. // ignored, including when it does not arrive in the same read as the
  13177. // close-delimiter itself.
  13178. expect_split_multipart_ok("--zzzz\r\n"
  13179. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13180. "\r\n"
  13181. "text1"
  13182. "\r\n--zzzz--",
  13183. "\r\nthis epilogue must be ignored\r\n");
  13184. }
  13185. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13186. // The initial boundary may be preceded by a preamble of any length and may
  13187. // straddle a read boundary. Discarding data while waiting for it must not
  13188. // throw away a partial boundary sitting at the end of the buffer.
  13189. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13190. "zz\r\n"
  13191. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13192. "\r\n"
  13193. "text1"
  13194. "\r\n--zzzz--\r\n");
  13195. }
  13196. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13197. // The received boundary was only checked for being non-empty, so it could be
  13198. // as long as a header is allowed to be. The parser scans the body for
  13199. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13200. // costs a nearly full comparison at nearly every position, making the
  13201. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13202. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13203. Server svr;
  13204. svr.Post("/post", [](const Request &req, Response &res) {
  13205. EXPECT_EQ(1u, req.form.fields.size());
  13206. EXPECT_EQ("text1", req.form.get_field("text1"));
  13207. res.set_content("ok", "text/plain");
  13208. });
  13209. auto port = svr.bind_to_any_port(HOST);
  13210. thread t = thread([&] { svr.listen_after_bind(); });
  13211. auto se = detail::scope_exit([&] {
  13212. svr.stop();
  13213. t.join();
  13214. ASSERT_FALSE(svr.is_running());
  13215. });
  13216. svr.wait_until_ready();
  13217. Client cli(HOST, port);
  13218. auto post_with_boundary_of_length = [&](size_t len) {
  13219. const std::string boundary(len, 'a');
  13220. const std::string body =
  13221. "--" + boundary +
  13222. "\r\n"
  13223. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13224. "\r\n"
  13225. "text1"
  13226. "\r\n--" +
  13227. boundary + "--\r\n";
  13228. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13229. };
  13230. auto res = post_with_boundary_of_length(70);
  13231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13232. EXPECT_EQ(StatusCode::OK_200, res->status);
  13233. res = post_with_boundary_of_length(71);
  13234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13235. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13236. }
  13237. TEST(MakeFileBodyTest, Basic) {
  13238. const std::string file_content(4096, 'Z');
  13239. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13240. {
  13241. std::ofstream ofs(tmp_path, std::ios::binary);
  13242. ofs.write(file_content.data(),
  13243. static_cast<std::streamsize>(file_content.size()));
  13244. }
  13245. auto handled = false;
  13246. Server svr;
  13247. svr.Post("/upload", [&](const Request &req, Response &res) {
  13248. EXPECT_EQ(file_content, req.body);
  13249. handled = true;
  13250. res.status = StatusCode::OK_200;
  13251. });
  13252. auto port = svr.bind_to_any_port(HOST);
  13253. auto t = thread([&] { svr.listen_after_bind(); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. ASSERT_TRUE(handled);
  13259. std::remove(tmp_path.c_str());
  13260. });
  13261. svr.wait_until_ready();
  13262. auto fb = make_file_body(tmp_path);
  13263. ASSERT_GT(fb.first, 0u);
  13264. Client cli(HOST, port);
  13265. auto res =
  13266. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. }
  13270. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13271. static constexpr unsigned int number_of_tasks{1000000};
  13272. std::atomic_uint count{0};
  13273. std::unique_ptr<TaskQueue> task_queue{
  13274. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13275. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13276. auto queued = task_queue->enqueue(
  13277. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13278. EXPECT_TRUE(queued);
  13279. }
  13280. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13281. task_queue->shutdown();
  13282. #else
  13283. EXPECT_NO_THROW(task_queue->shutdown());
  13284. #endif
  13285. EXPECT_EQ(number_of_tasks, count.load());
  13286. }
  13287. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13288. static constexpr unsigned int number_of_tasks{1000000};
  13289. static constexpr unsigned int qlimit{2};
  13290. unsigned int queued_count{0};
  13291. std::atomic_uint count{0};
  13292. std::unique_ptr<TaskQueue> task_queue{
  13293. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13294. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13295. if (task_queue->enqueue(
  13296. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13297. queued_count++;
  13298. }
  13299. }
  13300. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13301. task_queue->shutdown();
  13302. #else
  13303. EXPECT_NO_THROW(task_queue->shutdown());
  13304. #endif
  13305. EXPECT_EQ(queued_count, count.load());
  13306. EXPECT_TRUE(queued_count <= number_of_tasks);
  13307. EXPECT_TRUE(queued_count >= qlimit);
  13308. }
  13309. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13310. // Use a short idle timeout so a dynamic thread spawns, times out and
  13311. // exits during the test, and the pool keeps working afterwards.
  13312. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13313. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13314. /*idle_timeout_sec=*/1}};
  13315. std::atomic_uint count{0};
  13316. std::condition_variable cv;
  13317. std::mutex mtx;
  13318. bool release = false;
  13319. // Block the base thread so the second task spawns a dynamic thread.
  13320. EXPECT_TRUE(task_queue->enqueue([&] {
  13321. std::unique_lock<std::mutex> lock(mtx);
  13322. while (!release) {
  13323. cv.wait(lock);
  13324. }
  13325. count++;
  13326. }));
  13327. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13328. // Let the dynamic thread finish its task and exceed the idle timeout.
  13329. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13330. {
  13331. std::unique_lock<std::mutex> lock(mtx);
  13332. release = true;
  13333. }
  13334. cv.notify_all();
  13335. // The pool must still accept and run tasks after the dynamic thread exited.
  13336. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13337. task_queue->shutdown();
  13338. EXPECT_EQ(3u, count.load());
  13339. }
  13340. TEST(TaskQueueTest, MaxQueuedRequests) {
  13341. static constexpr unsigned int qlimit{3};
  13342. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13343. std::condition_variable sem_cv;
  13344. std::mutex sem_mtx;
  13345. int credits = 0;
  13346. bool queued;
  13347. /* Fill up the queue with tasks that will block until we give them credits to
  13348. * complete. */
  13349. for (unsigned int n = 0; n <= qlimit;) {
  13350. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13351. std::unique_lock<std::mutex> lock(sem_mtx);
  13352. while (credits <= 0) {
  13353. sem_cv.wait(lock);
  13354. }
  13355. /* Consume the credit and signal the test code if they are all gone. */
  13356. if (--credits == 0) { sem_cv.notify_one(); }
  13357. });
  13358. if (n < qlimit) {
  13359. /* The first qlimit enqueues must succeed. */
  13360. EXPECT_TRUE(queued);
  13361. } else {
  13362. /* The last one will succeed only when the worker thread
  13363. * starts and dequeues the first blocking task. Although
  13364. * not necessary for the correctness of this test, we sleep for
  13365. * a short while to avoid busy waiting. */
  13366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13367. }
  13368. if (queued) { n++; }
  13369. }
  13370. /* Further enqueues must fail since the queue is full. */
  13371. for (auto i = 0; i < 4; i++) {
  13372. queued = task_queue->enqueue([] {});
  13373. EXPECT_FALSE(queued);
  13374. }
  13375. /* Give the credits to allow the previous tasks to complete. */
  13376. {
  13377. std::unique_lock<std::mutex> lock(sem_mtx);
  13378. credits += qlimit + 1;
  13379. }
  13380. sem_cv.notify_all();
  13381. /* Wait for all the credits to be consumed. */
  13382. {
  13383. std::unique_lock<std::mutex> lock(sem_mtx);
  13384. while (credits > 0) {
  13385. sem_cv.wait(lock);
  13386. }
  13387. }
  13388. /* Check that we are able again to enqueue at least qlimit tasks. */
  13389. for (unsigned int i = 0; i < qlimit; i++) {
  13390. queued = task_queue->enqueue([] {});
  13391. EXPECT_TRUE(queued);
  13392. }
  13393. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13394. task_queue->shutdown();
  13395. #else
  13396. EXPECT_NO_THROW(task_queue->shutdown());
  13397. #endif
  13398. }
  13399. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13400. Server svr;
  13401. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13402. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13403. });
  13404. svr.Get("/hello", [](const Request &req, Response &res) {
  13405. res.set_content(req.get_param_value("key"), "text/plain");
  13406. });
  13407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13408. auto se = detail::scope_exit([&] {
  13409. svr.stop();
  13410. thread.join();
  13411. ASSERT_FALSE(svr.is_running());
  13412. });
  13413. svr.wait_until_ready();
  13414. {
  13415. Client cli(HOST, PORT);
  13416. cli.set_follow_location(true);
  13417. auto res = cli.Get("/");
  13418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13419. EXPECT_EQ(StatusCode::OK_200, res->status);
  13420. EXPECT_EQ("val&key2=val2", res->body);
  13421. }
  13422. }
  13423. #endif
  13424. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13425. Server svr;
  13426. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13427. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13428. });
  13429. svr.Get("/hello", [](const Request &req, Response &res) {
  13430. res.set_content(req.get_param_value("key"), "text/plain");
  13431. });
  13432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13433. auto se = detail::scope_exit([&] {
  13434. svr.stop();
  13435. thread.join();
  13436. ASSERT_FALSE(svr.is_running());
  13437. });
  13438. svr.wait_until_ready();
  13439. {
  13440. Client cli(HOST, PORT);
  13441. cli.set_follow_location(true);
  13442. auto res = cli.Get("/");
  13443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13444. EXPECT_EQ(StatusCode::OK_200, res->status);
  13445. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13446. }
  13447. }
  13448. TEST(RedirectTest, RedirectWithPlusInPath) {
  13449. Server svr;
  13450. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13451. res.set_redirect("/a+b");
  13452. });
  13453. // Route pattern uses regex; escape + as \\+
  13454. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13455. res.set_content(req.path, "text/plain");
  13456. });
  13457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13458. auto se = detail::scope_exit([&] {
  13459. svr.stop();
  13460. thread.join();
  13461. ASSERT_FALSE(svr.is_running());
  13462. });
  13463. svr.wait_until_ready();
  13464. {
  13465. Client cli(HOST, PORT);
  13466. cli.set_follow_location(true);
  13467. auto res = cli.Get("/");
  13468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13469. EXPECT_EQ(StatusCode::OK_200, res->status);
  13470. EXPECT_EQ("/a+b", res->body);
  13471. }
  13472. }
  13473. #ifdef CPPHTTPLIB_SSL_ENABLED
  13474. TEST(RedirectTest, Issue2185_Online) {
  13475. SSLClient client("github.com");
  13476. client.set_follow_location(true);
  13477. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13478. "Coollab-Windows.zip");
  13479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13480. EXPECT_EQ(StatusCode::OK_200, res->status);
  13481. EXPECT_EQ(9920427U, res->body.size());
  13482. }
  13483. #endif
  13484. TEST(VulnerabilityTest, CRLFInjection) {
  13485. Server svr;
  13486. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13487. res.set_content("Hello 1", "text/plain");
  13488. });
  13489. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13490. res.set_content("Hello 2", "text/plain");
  13491. });
  13492. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13493. res.set_content("Hello 3", "text/plain");
  13494. });
  13495. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13496. res.set_content("Hello 4", "text/plain");
  13497. });
  13498. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13499. for (const auto &x : req.headers) {
  13500. auto key = x.first;
  13501. EXPECT_STRNE("evil", key.c_str());
  13502. }
  13503. });
  13504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13505. auto se = detail::scope_exit([&] {
  13506. svr.stop();
  13507. thread.join();
  13508. ASSERT_FALSE(svr.is_running());
  13509. });
  13510. svr.wait_until_ready();
  13511. {
  13512. Client cli(HOST, PORT);
  13513. cli.Post("/test1", "A=B",
  13514. "application/x-www-form-urlencoded\r\nevil: hello1");
  13515. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13516. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13517. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13518. }
  13519. }
  13520. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13521. auto server_thread = std::thread([] {
  13522. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13523. default_socket_options(srv);
  13524. sockaddr_in addr{};
  13525. addr.sin_family = AF_INET;
  13526. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13528. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13529. ::listen(srv, 1);
  13530. sockaddr_in cli_addr{};
  13531. socklen_t cli_len = sizeof(cli_addr);
  13532. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13533. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13534. std::string buf_all;
  13535. char buf[2048];
  13536. ssize_t n;
  13537. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13538. buf_all.append(buf, static_cast<size_t>(n));
  13539. size_t pos;
  13540. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13541. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13542. auto e = request_block.find("\r\n");
  13543. if (e != std::string::npos) {
  13544. auto request_line = request_block.substr(0, e);
  13545. std::string msg =
  13546. "CRLF injection detected in request line: '" + request_line + "'";
  13547. EXPECT_FALSE(true) << msg;
  13548. }
  13549. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13550. ::send(cli,
  13551. #ifdef _WIN32
  13552. static_cast<const char *>(resp.c_str()),
  13553. static_cast<int>(resp.size()),
  13554. #else
  13555. resp.c_str(), resp.size(),
  13556. #endif
  13557. 0);
  13558. buf_all.erase(0, pos + 4);
  13559. }
  13560. }
  13561. detail::close_socket(cli);
  13562. detail::close_socket(srv);
  13563. });
  13564. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13565. auto cli = Client("127.0.0.1", PORT + 1);
  13566. auto headers = Headers{
  13567. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13568. {"Connection", "keep-alive"}};
  13569. auto res = cli.Get("/hi", headers);
  13570. EXPECT_FALSE(res);
  13571. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13572. server_thread.join();
  13573. }
  13574. TEST(PathParamsTest, StaticMatch) {
  13575. const auto pattern = "/users/all";
  13576. detail::PathParamsMatcher matcher(pattern);
  13577. Request request;
  13578. request.path = "/users/all";
  13579. ASSERT_TRUE(matcher.match(request));
  13580. std::unordered_map<std::string, std::string> expected_params = {};
  13581. EXPECT_EQ(request.path_params, expected_params);
  13582. }
  13583. TEST(PathParamsTest, StaticMismatch) {
  13584. const auto pattern = "/users/all";
  13585. detail::PathParamsMatcher matcher(pattern);
  13586. Request request;
  13587. request.path = "/users/1";
  13588. ASSERT_FALSE(matcher.match(request));
  13589. }
  13590. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13591. const auto pattern = "/users/:id/subscriptions";
  13592. detail::PathParamsMatcher matcher(pattern);
  13593. Request request;
  13594. request.path = "/users/42/subscriptions";
  13595. ASSERT_TRUE(matcher.match(request));
  13596. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13597. EXPECT_EQ(request.path_params, expected_params);
  13598. }
  13599. TEST(PathParamsTest, SingleParamInTheEnd) {
  13600. const auto pattern = "/users/:id";
  13601. detail::PathParamsMatcher matcher(pattern);
  13602. Request request;
  13603. request.path = "/users/24";
  13604. ASSERT_TRUE(matcher.match(request));
  13605. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13606. EXPECT_EQ(request.path_params, expected_params);
  13607. }
  13608. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13609. const auto pattern = "/users/:id/";
  13610. detail::PathParamsMatcher matcher(pattern);
  13611. Request request;
  13612. request.path = "/users/42/";
  13613. ASSERT_TRUE(matcher.match(request));
  13614. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13615. EXPECT_EQ(request.path_params, expected_params);
  13616. }
  13617. TEST(PathParamsTest, EmptyParam) {
  13618. const auto pattern = "/users/:id/";
  13619. detail::PathParamsMatcher matcher(pattern);
  13620. Request request;
  13621. request.path = "/users//";
  13622. ASSERT_TRUE(matcher.match(request));
  13623. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13624. EXPECT_EQ(request.path_params, expected_params);
  13625. }
  13626. TEST(PathParamsTest, FragmentMismatch) {
  13627. const auto pattern = "/users/:id/";
  13628. detail::PathParamsMatcher matcher(pattern);
  13629. Request request;
  13630. request.path = "/admins/24/";
  13631. ASSERT_FALSE(matcher.match(request));
  13632. }
  13633. TEST(PathParamsTest, ExtraFragments) {
  13634. const auto pattern = "/users/:id";
  13635. detail::PathParamsMatcher matcher(pattern);
  13636. Request request;
  13637. request.path = "/users/42/subscriptions";
  13638. ASSERT_FALSE(matcher.match(request));
  13639. }
  13640. TEST(PathParamsTest, MissingTrailingParam) {
  13641. const auto pattern = "/users/:id";
  13642. detail::PathParamsMatcher matcher(pattern);
  13643. Request request;
  13644. request.path = "/users";
  13645. ASSERT_FALSE(matcher.match(request));
  13646. }
  13647. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13648. const auto pattern = "/users/:id/subscriptions";
  13649. detail::PathParamsMatcher matcher(pattern);
  13650. Request request;
  13651. request.path = "/users/subscriptions";
  13652. ASSERT_FALSE(matcher.match(request));
  13653. }
  13654. TEST(PathParamsTest, MultipleParams) {
  13655. const auto pattern = "/users/:userid/subscriptions/:subid";
  13656. detail::PathParamsMatcher matcher(pattern);
  13657. Request request;
  13658. request.path = "/users/42/subscriptions/2";
  13659. ASSERT_TRUE(matcher.match(request));
  13660. std::unordered_map<std::string, std::string> expected_params = {
  13661. {"userid", "42"}, {"subid", "2"}};
  13662. EXPECT_EQ(request.path_params, expected_params);
  13663. }
  13664. TEST(PathParamsTest, SequenceOfParams) {
  13665. const auto pattern = "/values/:x/:y/:z";
  13666. detail::PathParamsMatcher matcher(pattern);
  13667. Request request;
  13668. request.path = "/values/1/2/3";
  13669. ASSERT_TRUE(matcher.match(request));
  13670. std::unordered_map<std::string, std::string> expected_params = {
  13671. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13672. EXPECT_EQ(request.path_params, expected_params);
  13673. }
  13674. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13675. const auto pattern = "/prefix:suffix";
  13676. detail::PathParamsMatcher matcher(pattern);
  13677. Request request;
  13678. request.path = "/prefix:suffix";
  13679. ASSERT_TRUE(matcher.match(request));
  13680. const std::unordered_map<std::string, std::string> expected_params = {};
  13681. EXPECT_EQ(request.path_params, expected_params);
  13682. }
  13683. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13684. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13685. // calling thread's stack on a long enough path for a quantified pattern;
  13686. // RegexMatcher must refuse to run regex matching on paths beyond
  13687. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13688. detail::RegexMatcher matcher("/files/(.*)");
  13689. Request within_limit;
  13690. within_limit.path = "/files/" + std::string(10, 'A');
  13691. EXPECT_TRUE(matcher.match(within_limit));
  13692. Request over_limit;
  13693. over_limit.path =
  13694. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13695. EXPECT_FALSE(matcher.match(over_limit));
  13696. }
  13697. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13698. Server svr;
  13699. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13700. res.set_content("ok", "text/plain");
  13701. });
  13702. auto port = svr.bind_to_any_port(HOST);
  13703. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13704. auto se = detail::scope_exit([&] {
  13705. svr.stop();
  13706. thread.join();
  13707. ASSERT_FALSE(svr.is_running());
  13708. });
  13709. svr.wait_until_ready();
  13710. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13711. // request URI limit; this used to be able to crash the process.
  13712. std::string path =
  13713. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13714. std::string req = "GET " + path +
  13715. " HTTP/1.1\r\n"
  13716. "Host: " +
  13717. std::string(HOST) + ":" + std::to_string(port) +
  13718. "\r\n"
  13719. "Connection: close\r\n"
  13720. "\r\n";
  13721. std::string response;
  13722. ASSERT_TRUE(send_request(5, req, &response, port));
  13723. EXPECT_NE(std::string::npos, response.find("404"));
  13724. }
  13725. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13726. Server svr;
  13727. auto handler = [](const Request & /*req*/, Response &res) {
  13728. res.set_content("hit", "text/plain");
  13729. };
  13730. // No regex metacharacter, so this one is compared literally
  13731. svr.Get("/literal/route", handler);
  13732. // '.' is a regex metacharacter, so this one must keep regex semantics
  13733. svr.Get("/a.c", handler);
  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. struct {
  13744. const char *path;
  13745. int status;
  13746. } cases[] = {
  13747. {"/literal/route", StatusCode::OK_200},
  13748. {"/literal/routes", StatusCode::NotFound_404},
  13749. {"/literal/rout", StatusCode::NotFound_404},
  13750. {"/abc", StatusCode::OK_200},
  13751. {"/a.c", StatusCode::OK_200},
  13752. };
  13753. for (const auto &x : cases) {
  13754. auto res = cli.Get(x.path);
  13755. ASSERT_TRUE(res) << x.path;
  13756. EXPECT_EQ(x.status, res->status) << x.path;
  13757. }
  13758. }
  13759. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13760. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13761. // from exhausting the stack, so it must only constrain routes that actually
  13762. // run a regular expression. A literal route is matched by comparison and
  13763. // stays usable at any length.
  13764. Server svr;
  13765. const std::string pattern =
  13766. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13767. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13768. res.set_content("hit", "text/plain");
  13769. });
  13770. auto port = svr.bind_to_any_port(HOST);
  13771. std::thread t([&]() { svr.listen_after_bind(); });
  13772. auto se = detail::scope_exit([&] {
  13773. svr.stop();
  13774. t.join();
  13775. ASSERT_FALSE(svr.is_running());
  13776. });
  13777. svr.wait_until_ready();
  13778. Client cli(HOST, port);
  13779. auto res = cli.Get(pattern);
  13780. ASSERT_TRUE(res);
  13781. EXPECT_EQ(StatusCode::OK_200, res->status);
  13782. }
  13783. TEST(ParseUrlTest, VariousPatterns) {
  13784. {
  13785. detail::UrlComponents uc;
  13786. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13787. EXPECT_EQ("http", uc.scheme);
  13788. EXPECT_EQ("example.com", uc.host);
  13789. EXPECT_EQ("8080", uc.port);
  13790. EXPECT_EQ("/path", uc.path);
  13791. EXPECT_EQ("?q=1", uc.query);
  13792. }
  13793. {
  13794. detail::UrlComponents uc;
  13795. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13796. EXPECT_EQ("https", uc.scheme);
  13797. EXPECT_EQ("example.com", uc.host);
  13798. EXPECT_TRUE(uc.port.empty());
  13799. EXPECT_EQ("/path", uc.path);
  13800. }
  13801. {
  13802. detail::UrlComponents uc;
  13803. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13804. EXPECT_EQ("::1", uc.host);
  13805. EXPECT_EQ("8080", uc.port);
  13806. EXPECT_EQ("/path", uc.path);
  13807. }
  13808. {
  13809. detail::UrlComponents uc;
  13810. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13811. }
  13812. {
  13813. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13814. // the path while the connection still targets the bracketed host.
  13815. detail::UrlComponents uc;
  13816. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13817. }
  13818. {
  13819. detail::UrlComponents uc;
  13820. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13821. }
  13822. {
  13823. detail::UrlComponents uc;
  13824. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13825. EXPECT_EQ("::1", uc.host);
  13826. EXPECT_TRUE(uc.port.empty());
  13827. EXPECT_EQ("/path", uc.path);
  13828. }
  13829. {
  13830. detail::UrlComponents uc;
  13831. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13832. EXPECT_TRUE(uc.scheme.empty());
  13833. EXPECT_EQ("example.com", uc.host);
  13834. EXPECT_EQ("/path", uc.path);
  13835. EXPECT_EQ("?q=1", uc.query);
  13836. }
  13837. {
  13838. detail::UrlComponents uc;
  13839. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13840. EXPECT_TRUE(uc.host.empty());
  13841. EXPECT_EQ("/path", uc.path);
  13842. EXPECT_EQ("?q=1", uc.query);
  13843. }
  13844. {
  13845. detail::UrlComponents uc;
  13846. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13847. EXPECT_EQ("example.com", uc.host);
  13848. EXPECT_EQ("8080", uc.port);
  13849. }
  13850. {
  13851. // Unix socket path — must not be parsed as host
  13852. detail::UrlComponents uc;
  13853. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13854. EXPECT_TRUE(uc.host.empty());
  13855. }
  13856. {
  13857. detail::UrlComponents uc;
  13858. ASSERT_TRUE(detail::parse_url("", uc));
  13859. EXPECT_TRUE(uc.host.empty());
  13860. EXPECT_TRUE(uc.path.empty());
  13861. }
  13862. {
  13863. detail::UrlComponents uc;
  13864. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13865. }
  13866. {
  13867. detail::UrlComponents uc;
  13868. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13869. }
  13870. {
  13871. // Accepted by parse_url; callers restrict to http/https
  13872. detail::UrlComponents uc;
  13873. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13874. EXPECT_EQ("ftp", uc.scheme);
  13875. }
  13876. {
  13877. detail::UrlComponents uc;
  13878. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13879. }
  13880. {
  13881. detail::UrlComponents uc;
  13882. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13883. }
  13884. }
  13885. TEST(ParseUrlTest, FragmentHandling) {
  13886. {
  13887. detail::UrlComponents uc;
  13888. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13889. EXPECT_EQ("/path", uc.path);
  13890. EXPECT_TRUE(uc.query.empty());
  13891. }
  13892. {
  13893. detail::UrlComponents uc;
  13894. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13895. EXPECT_TRUE(uc.path.empty());
  13896. EXPECT_TRUE(uc.query.empty());
  13897. }
  13898. }
  13899. TEST(ParseUrlTest, UserinfoHandling) {
  13900. // Userinfo with @ but no colon — host includes @
  13901. detail::UrlComponents uc;
  13902. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13903. EXPECT_EQ("user@host.com", uc.host);
  13904. EXPECT_EQ("/path", uc.path);
  13905. }
  13906. TEST(ParseUrlTest, IPv6EdgeCases) {
  13907. {
  13908. detail::UrlComponents uc;
  13909. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13910. EXPECT_TRUE(uc.scheme.empty());
  13911. EXPECT_EQ("::1", uc.host);
  13912. EXPECT_EQ("8080", uc.port);
  13913. }
  13914. {
  13915. // Zone ID '%25' is not in [a-fA-F0-9:]
  13916. detail::UrlComponents uc;
  13917. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13918. }
  13919. }
  13920. TEST(ParseUrlTest, SchemeEdgeCases) {
  13921. {
  13922. detail::UrlComponents uc;
  13923. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13924. }
  13925. {
  13926. detail::UrlComponents uc;
  13927. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13928. }
  13929. {
  13930. detail::UrlComponents uc;
  13931. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13932. }
  13933. }
  13934. TEST(ParseUrlTest, PortEdgeCases) {
  13935. {
  13936. detail::UrlComponents uc;
  13937. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13938. EXPECT_TRUE(uc.port.empty());
  13939. EXPECT_EQ("/path", uc.path);
  13940. }
  13941. {
  13942. // parse_url accepts any port string; validation is done by parse_port
  13943. detail::UrlComponents uc;
  13944. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13945. EXPECT_EQ("abc", uc.port);
  13946. }
  13947. }
  13948. TEST(ParseUrlTest, WebSocketPatterns) {
  13949. {
  13950. detail::UrlComponents uc;
  13951. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13952. EXPECT_EQ("ws", uc.scheme);
  13953. EXPECT_EQ("echo.example.com", uc.host);
  13954. EXPECT_EQ("8080", uc.port);
  13955. EXPECT_EQ("/ws", uc.path);
  13956. }
  13957. {
  13958. detail::UrlComponents uc;
  13959. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13960. EXPECT_EQ("wss", uc.scheme);
  13961. EXPECT_EQ("echo.example.com", uc.host);
  13962. EXPECT_TRUE(uc.port.empty());
  13963. EXPECT_EQ("/ws", uc.path);
  13964. }
  13965. }
  13966. TEST(ParseUrlTest, QueryOnly) {
  13967. detail::UrlComponents uc;
  13968. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13969. EXPECT_TRUE(uc.host.empty());
  13970. EXPECT_TRUE(uc.path.empty());
  13971. EXPECT_EQ("?q=1&r=2", uc.query);
  13972. }
  13973. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13974. detail::UrlComponents uc;
  13975. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13976. EXPECT_TRUE(uc.scheme.empty());
  13977. EXPECT_EQ("example.com", uc.host);
  13978. EXPECT_EQ("443", uc.port);
  13979. EXPECT_EQ("/path", uc.path);
  13980. }
  13981. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13982. // If ipv6 regex working, regex match codepath is taken.
  13983. // else port will default to 80 in Client impl
  13984. int clientImplMagicPort = 80;
  13985. int port = 4321;
  13986. // above ports must be different to avoid false negative
  13987. EXPECT_NE(clientImplMagicPort, port);
  13988. std::string ipV6TestURL = "http://[ff06::c3]";
  13989. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13990. CLIENT_PRIVATE_KEY_FILE);
  13991. EXPECT_EQ(cli.port(), port);
  13992. }
  13993. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13994. auto file_path = "./www/dir/index.html";
  13995. auto dir_path = "./www/dir";
  13996. detail::FileStat stat_file(file_path);
  13997. EXPECT_TRUE(stat_file.is_file());
  13998. EXPECT_FALSE(stat_file.is_dir());
  13999. detail::FileStat stat_dir(dir_path);
  14000. EXPECT_FALSE(stat_dir.is_file());
  14001. EXPECT_TRUE(stat_dir.is_dir());
  14002. }
  14003. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14004. // IPv4 with default HTTP port (80)
  14005. EXPECT_EQ("example.com",
  14006. detail::make_host_and_port_string("example.com", 80, false));
  14007. // IPv4 with default HTTPS port (443)
  14008. EXPECT_EQ("example.com",
  14009. detail::make_host_and_port_string("example.com", 443, true));
  14010. // IPv4 with non-default HTTP port
  14011. EXPECT_EQ("example.com:8080",
  14012. detail::make_host_and_port_string("example.com", 8080, false));
  14013. // IPv4 with non-default HTTPS port
  14014. EXPECT_EQ("example.com:8443",
  14015. detail::make_host_and_port_string("example.com", 8443, true));
  14016. // IPv6 with default HTTP port (80)
  14017. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14018. // IPv6 with default HTTPS port (443)
  14019. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14020. // IPv6 with non-default HTTP port
  14021. EXPECT_EQ("[::1]:8080",
  14022. detail::make_host_and_port_string("::1", 8080, false));
  14023. // IPv6 with non-default HTTPS port
  14024. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14025. // IPv6 full address with default port
  14026. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14027. detail::make_host_and_port_string(
  14028. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14029. // IPv6 full address with non-default port
  14030. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14031. detail::make_host_and_port_string(
  14032. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14033. // IPv6 localhost with non-default port
  14034. EXPECT_EQ("[::1]:3000",
  14035. detail::make_host_and_port_string("::1", 3000, false));
  14036. // IPv6 with zone ID (link-local address) with default port
  14037. EXPECT_EQ("[fe80::1%eth0]",
  14038. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14039. // IPv6 with zone ID (link-local address) with non-default port
  14040. EXPECT_EQ("[fe80::1%eth0]:8080",
  14041. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14042. // Edge case: Port 443 with is_ssl=false (should add port)
  14043. EXPECT_EQ("example.com:443",
  14044. detail::make_host_and_port_string("example.com", 443, false));
  14045. // Edge case: Port 80 with is_ssl=true (should add port)
  14046. EXPECT_EQ("example.com:80",
  14047. detail::make_host_and_port_string("example.com", 80, true));
  14048. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14049. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14050. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14051. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14052. // Security fix: Already bracketed IPv6 should not get double brackets
  14053. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14054. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14055. EXPECT_EQ("[::1]:8080",
  14056. detail::make_host_and_port_string("[::1]", 8080, false));
  14057. EXPECT_EQ("[2001:db8::1]:8080",
  14058. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14059. EXPECT_EQ("[fe80::1%eth0]",
  14060. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14061. EXPECT_EQ("[fe80::1%eth0]:8080",
  14062. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14063. // Edge case: Empty host (should return as-is)
  14064. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14065. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14066. // This is a known limitation but shouldn't crash
  14067. EXPECT_EQ("[host:name]",
  14068. detail::make_host_and_port_string("host:name", 80, false));
  14069. // Port number edge cases (no validation, but should not crash)
  14070. EXPECT_EQ("example.com:0",
  14071. detail::make_host_and_port_string("example.com", 0, false));
  14072. EXPECT_EQ("example.com:-1",
  14073. detail::make_host_and_port_string("example.com", -1, false));
  14074. EXPECT_EQ("example.com:65535",
  14075. detail::make_host_and_port_string("example.com", 65535, false));
  14076. EXPECT_EQ("example.com:65536",
  14077. detail::make_host_and_port_string("example.com", 65536, false));
  14078. }
  14079. #ifdef CPPHTTPLIB_SSL_ENABLED
  14080. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14081. httplib::SSLClient cli("roblox.com", 443);
  14082. cli.set_follow_location(true);
  14083. auto res = cli.Get("/");
  14084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14085. EXPECT_EQ(StatusCode::OK_200, res->status);
  14086. }
  14087. #endif
  14088. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14089. Server svr;
  14090. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14091. EXPECT_EQ(res.status, 400);
  14092. });
  14093. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. thread.join();
  14097. ASSERT_FALSE(svr.is_running());
  14098. });
  14099. svr.wait_until_ready();
  14100. Client cli(HOST, PORT);
  14101. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14102. }
  14103. TEST(InvalidHeaderCharsTest, is_field_name) {
  14104. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14105. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14106. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14107. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14108. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14109. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14110. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14111. EXPECT_FALSE(detail::fields::is_field_name(""));
  14112. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14113. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14114. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14115. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14116. }
  14117. TEST(InvalidHeaderCharsTest, is_field_value) {
  14118. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14119. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14120. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14121. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14122. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14123. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14124. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14125. EXPECT_TRUE(detail::fields::is_field_value(""));
  14126. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14127. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14128. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14129. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14130. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14131. }
  14132. TEST(InvalidHeaderCharsTest, OnServer) {
  14133. Server svr;
  14134. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14135. std::string header = "Not Set";
  14136. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14137. res.set_header(header, "value");
  14138. res.set_content("Page Content Page Content", "text/plain");
  14139. });
  14140. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14141. std::string header = "Not Set";
  14142. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14143. res.set_header("X-Test", header);
  14144. res.set_content("Page Content Page Content", "text/plain");
  14145. });
  14146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14147. auto se = detail::scope_exit([&] {
  14148. svr.stop();
  14149. thread.join();
  14150. ASSERT_FALSE(svr.is_running());
  14151. });
  14152. svr.wait_until_ready();
  14153. Client cli(HOST, PORT);
  14154. {
  14155. auto res = cli.Get(
  14156. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14158. EXPECT_EQ("Page Content Page Content", res->body);
  14159. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14160. }
  14161. {
  14162. auto res = cli.Get(
  14163. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14165. EXPECT_EQ("Page Content Page Content", res->body);
  14166. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14167. }
  14168. }
  14169. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14170. auto handled = false;
  14171. Server svr;
  14172. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14173. thread t = thread([&] { svr.listen(HOST, PORT); });
  14174. auto se = detail::scope_exit([&] {
  14175. svr.stop();
  14176. t.join();
  14177. ASSERT_FALSE(svr.is_running());
  14178. ASSERT_FALSE(handled);
  14179. });
  14180. svr.wait_until_ready();
  14181. auto req = "POST /test HTTP/1.1\r\n"
  14182. "Content-Length: x\r\n"
  14183. "\r\n";
  14184. std::string response;
  14185. ASSERT_TRUE(send_request(1, req, &response));
  14186. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14187. response.substr(0, response.find("\r\n")));
  14188. }
  14189. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14190. // case-insensitive, and a server that receives a 100-continue expectation in
  14191. // an HTTP/1.0 request MUST ignore it.
  14192. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14193. std::string response;
  14194. ASSERT_TRUE(send_request(1, req, &response, port));
  14195. *got_100 = response.find("100 Continue") != std::string::npos;
  14196. }
  14197. class ExpectTokenTest : public ::testing::Test {
  14198. protected:
  14199. void SetUp() override {
  14200. svr_.Post("/p", [](const Request &, Response &res) {
  14201. res.set_content("ok", "text/plain");
  14202. });
  14203. port_ = svr_.bind_to_any_port(HOST);
  14204. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14205. svr_.wait_until_ready();
  14206. }
  14207. void TearDown() override {
  14208. svr_.stop();
  14209. if (thread_.joinable()) { thread_.join(); }
  14210. }
  14211. std::string request(const char *version, const char *expect_value) const {
  14212. return std::string("POST /p ") + version +
  14213. "\r\n"
  14214. "Host: localhost\r\n"
  14215. "Content-Length: 2\r\n"
  14216. "Connection: close\r\n"
  14217. "Expect: " +
  14218. expect_value +
  14219. "\r\n"
  14220. "\r\n"
  14221. "hi";
  14222. }
  14223. Server svr_;
  14224. int port_ = 0;
  14225. thread thread_;
  14226. };
  14227. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14228. bool got_100 = false;
  14229. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14230. EXPECT_TRUE(got_100);
  14231. }
  14232. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14233. bool got_100 = true;
  14234. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14235. EXPECT_FALSE(got_100);
  14236. }
  14237. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14238. bool got_100 = false;
  14239. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14240. EXPECT_TRUE(got_100);
  14241. }
  14242. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14243. bool got_100 = false;
  14244. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14245. EXPECT_TRUE(got_100);
  14246. }
  14247. #ifndef _WIN32
  14248. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14249. static constexpr char reject[] = "Unauthorized";
  14250. static constexpr char accept[] = "Upload accepted";
  14251. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14252. Server svr;
  14253. svr.set_expect_100_continue_handler(
  14254. [](const Request & /*req*/, Response &res) {
  14255. res.status = StatusCode::Unauthorized_401;
  14256. res.set_content(reject, "text/plain");
  14257. return res.status;
  14258. });
  14259. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14260. res.set_content(accept, "text/plain");
  14261. });
  14262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. thread.join();
  14266. ASSERT_FALSE(svr.is_running());
  14267. });
  14268. svr.wait_until_ready();
  14269. {
  14270. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14271. curl_easy_init(), &curl_easy_cleanup};
  14272. ASSERT_NE(curl, nullptr);
  14273. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14274. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14275. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14276. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14277. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14278. &curl_slist_free_all};
  14279. ASSERT_NE(list, nullptr);
  14280. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14281. struct read_data {
  14282. size_t read_size;
  14283. size_t total_size;
  14284. } data = {0, total_size};
  14285. using read_callback_t =
  14286. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14287. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14288. void *userdata) -> size_t {
  14289. read_data *d = (read_data *)userdata;
  14290. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14291. std::fill_n(ptr, size * nmemb, 'A');
  14292. d->read_size += size * nmemb;
  14293. return size * nmemb;
  14294. };
  14295. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14296. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14297. std::vector<char> buffer;
  14298. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14299. using write_callback_t =
  14300. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14301. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14302. void *userdata) -> size_t {
  14303. std::vector<char> *buf = (std::vector<char> *)userdata;
  14304. buf->reserve(buf->size() + size * nmemb + 1);
  14305. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14306. return size * nmemb;
  14307. };
  14308. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14309. {
  14310. const auto res = curl_easy_perform(curl.get());
  14311. ASSERT_EQ(res, CURLE_OK);
  14312. }
  14313. {
  14314. auto response_code = long{};
  14315. const auto res =
  14316. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14317. ASSERT_EQ(res, CURLE_OK);
  14318. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14319. }
  14320. {
  14321. auto dl = curl_off_t{};
  14322. const auto res =
  14323. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14324. ASSERT_EQ(res, CURLE_OK);
  14325. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14326. }
  14327. {
  14328. buffer.push_back('\0');
  14329. ASSERT_STRCASEEQ(buffer.data(), reject);
  14330. }
  14331. }
  14332. }
  14333. #endif
  14334. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14335. // Regression test for #2458.
  14336. //
  14337. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14338. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14339. // ticket can make the client socket spuriously readable during the
  14340. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14341. // the client withholds the body and then blocks reading a response that never
  14342. // comes, failing with `Failed to read connection`.
  14343. //
  14344. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14345. // within the timeout. This raw OpenSSL server deliberately never sends
  14346. // `100 Continue`; the client must still deliver the body and receive 200.
  14347. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14348. signal(SIGPIPE, SIG_IGN);
  14349. const auto port = PORT + 4;
  14350. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14351. ASSERT_NE(srv, INVALID_SOCKET);
  14352. int opt = 1;
  14353. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14354. sockaddr_in addr{};
  14355. addr.sin_family = AF_INET;
  14356. addr.sin_port = htons(static_cast<uint16_t>(port));
  14357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14358. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14359. ASSERT_EQ(0, ::listen(srv, 1));
  14360. std::atomic<size_t> server_body_bytes{0};
  14361. auto server_thread = std::thread([&] {
  14362. sockaddr_in cli_addr{};
  14363. socklen_t cli_len = sizeof(cli_addr);
  14364. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14365. if (cli == INVALID_SOCKET) { return; }
  14366. // Bound the lifetime of the server side so a buggy client (which never
  14367. // sends the body) cannot make this thread block forever on join.
  14368. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14369. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14370. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14371. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14372. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14373. SSL *ssl = SSL_new(ctx);
  14374. SSL_set_fd(ssl, static_cast<int>(cli));
  14375. if (SSL_accept(ssl) > 0) {
  14376. // Read the request headers. Reading here also flushes the TLS 1.3
  14377. // session tickets to the client. Deliberately do NOT send
  14378. // `100 Continue`.
  14379. std::string buf;
  14380. char tmp[1024];
  14381. while (buf.find("\r\n\r\n") == std::string::npos) {
  14382. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14383. if (n <= 0) { break; }
  14384. buf.append(tmp, static_cast<size_t>(n));
  14385. }
  14386. // A correct client sends the body now; count what arrives.
  14387. auto pos = buf.find("\r\n\r\n");
  14388. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14389. while (body < 4096) {
  14390. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14391. if (n <= 0) { break; }
  14392. body += static_cast<size_t>(n);
  14393. }
  14394. server_body_bytes = body;
  14395. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14396. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14397. SSL_shutdown(ssl);
  14398. }
  14399. SSL_free(ssl);
  14400. detail::close_socket(cli);
  14401. SSL_CTX_free(ctx);
  14402. });
  14403. auto se = detail::scope_exit([&] {
  14404. server_thread.join();
  14405. detail::close_socket(srv);
  14406. });
  14407. SSLClient cli("127.0.0.1", port);
  14408. cli.enable_server_certificate_verification(false);
  14409. cli.set_connection_timeout(5, 0);
  14410. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14411. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14412. std::string body(4096, 'A');
  14413. auto res = cli.Put("/api/test", body, "application/json");
  14414. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14415. EXPECT_EQ(StatusCode::OK_200, res->status);
  14416. EXPECT_EQ(body.size(), server_body_bytes.load());
  14417. }
  14418. #endif
  14419. template <typename S, typename C>
  14420. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14421. svr.Get("/stream", [&](const Request &, Response &res) {
  14422. auto data = new std::string("01234567890123456789");
  14423. res.set_content_provider(
  14424. data->size(), "text/plain",
  14425. [&, data](size_t offset, size_t length, DataSink &sink) {
  14426. const size_t DATA_CHUNK_SIZE = 4;
  14427. const auto &d = *data;
  14428. std::this_thread::sleep_for(std::chrono::seconds(1));
  14429. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14430. return true;
  14431. },
  14432. [data](bool success) {
  14433. EXPECT_FALSE(success);
  14434. delete data;
  14435. });
  14436. });
  14437. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14438. auto i = new size_t(0);
  14439. res.set_content_provider(
  14440. "text/plain",
  14441. [i](size_t, DataSink &sink) {
  14442. if (*i < 5) {
  14443. std::this_thread::sleep_for(std::chrono::seconds(1));
  14444. sink.write("abcd", 4);
  14445. (*i)++;
  14446. } else {
  14447. sink.done();
  14448. }
  14449. return true;
  14450. },
  14451. [i](bool success) {
  14452. EXPECT_FALSE(success);
  14453. delete i;
  14454. });
  14455. });
  14456. svr.Get("/chunked", [&](const Request &, Response &res) {
  14457. auto i = new size_t(0);
  14458. res.set_chunked_content_provider(
  14459. "text/plain",
  14460. [i](size_t, DataSink &sink) {
  14461. if (*i < 5) {
  14462. std::this_thread::sleep_for(std::chrono::seconds(1));
  14463. sink.os << "abcd";
  14464. (*i)++;
  14465. } else {
  14466. sink.done();
  14467. }
  14468. return true;
  14469. },
  14470. [i](bool success) {
  14471. EXPECT_FALSE(success);
  14472. delete i;
  14473. });
  14474. });
  14475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14476. auto se = detail::scope_exit([&] {
  14477. svr.stop();
  14478. listen_thread.join();
  14479. ASSERT_FALSE(svr.is_running());
  14480. });
  14481. svr.wait_until_ready();
  14482. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14483. {
  14484. auto start = std::chrono::steady_clock::now();
  14485. auto res = cli.Get("/stream");
  14486. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14487. std::chrono::steady_clock::now() - start)
  14488. .count();
  14489. ASSERT_FALSE(res);
  14490. EXPECT_EQ(Error::Read, res.error());
  14491. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14492. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14493. }
  14494. {
  14495. auto start = std::chrono::steady_clock::now();
  14496. auto res = cli.Get("/stream_without_length");
  14497. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14498. std::chrono::steady_clock::now() - start)
  14499. .count();
  14500. ASSERT_FALSE(res);
  14501. EXPECT_EQ(Error::Read, res.error());
  14502. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14503. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14504. }
  14505. {
  14506. auto start = std::chrono::steady_clock::now();
  14507. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14508. EXPECT_EQ("abcd", string(data, data_length));
  14509. return true;
  14510. });
  14511. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14512. std::chrono::steady_clock::now() - start)
  14513. .count();
  14514. ASSERT_FALSE(res);
  14515. EXPECT_EQ(Error::Read, res.error());
  14516. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14517. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14518. }
  14519. }
  14520. TEST(MaxTimeoutTest, ContentStream) {
  14521. time_t timeout = 2000;
  14522. time_t threshold = 200;
  14523. Server svr;
  14524. Client cli("localhost", PORT);
  14525. max_timeout_test(svr, cli, timeout, threshold);
  14526. }
  14527. #ifdef CPPHTTPLIB_SSL_ENABLED
  14528. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14529. time_t timeout = 2000;
  14530. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14532. SSLClient cli("localhost", PORT);
  14533. cli.enable_server_certificate_verification(false);
  14534. max_timeout_test(svr, cli, timeout, threshold);
  14535. }
  14536. #endif
  14537. class EventDispatcher {
  14538. public:
  14539. EventDispatcher() {}
  14540. bool wait_event(DataSink *sink) {
  14541. unique_lock<mutex> lk(m_);
  14542. int id = id_;
  14543. // Wait with timeout to prevent hanging if client disconnects
  14544. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14545. [&] { return cid_ == id; })) {
  14546. return false; // Timeout occurred
  14547. }
  14548. sink->write(message_.data(), message_.size());
  14549. return true;
  14550. }
  14551. void send_event(const string &message) {
  14552. lock_guard<mutex> lk(m_);
  14553. cid_ = id_++;
  14554. message_ = message;
  14555. cv_.notify_all();
  14556. }
  14557. private:
  14558. mutex m_;
  14559. condition_variable cv_;
  14560. atomic_int id_{0};
  14561. atomic_int cid_{-1};
  14562. string message_;
  14563. };
  14564. TEST(ClientInThreadTest, Issue2068) {
  14565. EventDispatcher ed;
  14566. Server svr;
  14567. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14568. res.set_chunked_content_provider("text/event-stream",
  14569. [&](size_t /*offset*/, DataSink &sink) {
  14570. return ed.wait_event(&sink);
  14571. });
  14572. });
  14573. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14574. svr.wait_until_ready();
  14575. thread event_thread([&] {
  14576. int id = 0;
  14577. while (svr.is_running()) {
  14578. this_thread::sleep_for(chrono::milliseconds(500));
  14579. std::stringstream ss;
  14580. ss << "data: " << id << "\n\n";
  14581. ed.send_event(ss.str());
  14582. id++;
  14583. }
  14584. });
  14585. auto se = detail::scope_exit([&] {
  14586. svr.stop();
  14587. listen_thread.join();
  14588. event_thread.join();
  14589. ASSERT_FALSE(svr.is_running());
  14590. });
  14591. {
  14592. auto client = detail::make_unique<Client>(HOST, PORT);
  14593. client->set_read_timeout(std::chrono::minutes(10));
  14594. std::atomic<bool> stop{false};
  14595. std::thread t([&] {
  14596. client->Get("/event1",
  14597. [&](const char *, size_t) -> bool { return !stop; });
  14598. });
  14599. std::this_thread::sleep_for(std::chrono::seconds(2));
  14600. stop = true;
  14601. client->stop();
  14602. t.join();
  14603. // Reset client after thread has finished
  14604. client.reset();
  14605. }
  14606. }
  14607. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14608. auto handled = false;
  14609. Server svr;
  14610. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14611. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14612. auto se = detail::scope_exit([&] {
  14613. svr.stop();
  14614. t.join();
  14615. ASSERT_FALSE(svr.is_running());
  14616. ASSERT_FALSE(handled);
  14617. });
  14618. svr.wait_until_ready();
  14619. // Two Content-Length headers with different values — must be rejected
  14620. auto req = "POST /test HTTP/1.1\r\n"
  14621. "Content-Length: 5\r\n"
  14622. "Content-Length: 10\r\n"
  14623. "\r\n"
  14624. "hello";
  14625. std::string response;
  14626. ASSERT_TRUE(send_request(1, req, &response));
  14627. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14628. response.substr(0, response.find("\r\n")));
  14629. }
  14630. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14631. auto handled = false;
  14632. Server svr;
  14633. svr.Post("/test", [&](const Request &, Response &res) {
  14634. handled = true;
  14635. res.set_content("ok", "text/plain");
  14636. });
  14637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14638. auto se = detail::scope_exit([&] {
  14639. svr.stop();
  14640. t.join();
  14641. ASSERT_FALSE(svr.is_running());
  14642. ASSERT_TRUE(handled);
  14643. });
  14644. svr.wait_until_ready();
  14645. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14646. auto req = "POST /test HTTP/1.1\r\n"
  14647. "Content-Length: 5\r\n"
  14648. "Content-Length: 5\r\n"
  14649. "\r\n"
  14650. "hello";
  14651. std::string response;
  14652. ASSERT_TRUE(send_request(1, req, &response));
  14653. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14654. }
  14655. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14656. Server svr;
  14657. svr.Get("/", [](const Request &req, Response &res) {
  14658. EXPECT_EQ(2U, req.trailers.size());
  14659. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14660. // Denied
  14661. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14662. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14663. // Accepted
  14664. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14665. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14666. EXPECT_TRUE(req.has_trailer("X-World"));
  14667. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14668. res.set_content("ok", "text/plain");
  14669. });
  14670. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14671. auto se = detail::scope_exit([&] {
  14672. svr.stop();
  14673. t.join();
  14674. ASSERT_FALSE(svr.is_running());
  14675. });
  14676. svr.wait_until_ready();
  14677. const std::string req = "GET / HTTP/1.1\r\n"
  14678. "Transfer-Encoding: chunked\r\n"
  14679. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14680. "\r\n"
  14681. "0\r\n"
  14682. "Content-Length: 10\r\n"
  14683. "Host: internal.local\r\n"
  14684. "Content-Type: malicious/content\r\n"
  14685. "Cookie: any\r\n"
  14686. "Set-Cookie: any\r\n"
  14687. "X-Forwarded-For: attacker.com\r\n"
  14688. "X-Real-Ip: 1.1.1.1\r\n"
  14689. "X-Hello: hello\r\n"
  14690. "X-World: world\r\n"
  14691. "\r\n";
  14692. std::string res;
  14693. ASSERT_TRUE(send_request(1, req, &res));
  14694. }
  14695. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14696. // several field lines, and the combined value is what has to be parsed. A
  14697. // Trailer field split across lines therefore declares every name it lists;
  14698. // reading only the first line silently drops the trailers the later lines
  14699. // declare. The prohibited-trailer filter still applies to every line.
  14700. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14701. Server svr;
  14702. size_t observed_trailer_count = 0;
  14703. std::string observed_hello;
  14704. std::string observed_world;
  14705. bool observed_content_length = true;
  14706. svr.Get("/", [&](const Request &req, Response &res) {
  14707. observed_trailer_count = req.trailers.size();
  14708. observed_hello = req.get_trailer_value("X-Hello");
  14709. observed_world = req.get_trailer_value("X-World");
  14710. observed_content_length = req.has_trailer("Content-Length");
  14711. res.set_content("ok", "text/plain");
  14712. });
  14713. auto port = svr.bind_to_any_port(HOST);
  14714. thread t = thread([&]() { svr.listen_after_bind(); });
  14715. auto se = detail::scope_exit([&] {
  14716. svr.stop();
  14717. t.join();
  14718. ASSERT_FALSE(svr.is_running());
  14719. });
  14720. svr.wait_until_ready();
  14721. const std::string req = "GET / HTTP/1.1\r\n"
  14722. "Transfer-Encoding: chunked\r\n"
  14723. "Trailer: X-Hello\r\n"
  14724. "Trailer: X-World, Content-Length\r\n"
  14725. "\r\n"
  14726. "0\r\n"
  14727. "X-Hello: hello\r\n"
  14728. "X-World: world\r\n"
  14729. "Content-Length: 10\r\n"
  14730. "\r\n";
  14731. std::string res;
  14732. ASSERT_TRUE(send_request(1, req, &res, port));
  14733. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14734. // Accepted: both field lines contribute to the declared set
  14735. EXPECT_EQ(2U, observed_trailer_count);
  14736. EXPECT_EQ(observed_hello, "hello");
  14737. EXPECT_EQ(observed_world, "world");
  14738. // Denied: a prohibited name stays prohibited on a later field line
  14739. EXPECT_FALSE(observed_content_length);
  14740. }
  14741. // A direct client that is not listed in trusted_proxies must not be able to
  14742. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14743. // the peer address on the actual TCP connection determines whether the
  14744. // header is honored.
  14745. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14746. Server svr;
  14747. // Deliberately does NOT include the loopback address the test client
  14748. // actually connects from, so the direct connection is not a trusted proxy.
  14749. svr.set_trusted_proxies({"203.0.113.66"});
  14750. std::string observed_remote_addr;
  14751. svr.Get("/ip", [&](const Request &req, Response &res) {
  14752. observed_remote_addr = req.remote_addr;
  14753. res.set_content("ok", "text/plain");
  14754. });
  14755. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. });
  14761. svr.wait_until_ready();
  14762. Client cli(HOST, PORT);
  14763. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14765. EXPECT_EQ(StatusCode::OK_200, res->status);
  14766. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14767. // ignored entirely and the real connection-level address retained.
  14768. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14769. observed_remote_addr == "127.0.0.1");
  14770. }
  14771. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14772. Server svr;
  14773. std::string observed_remote_addr;
  14774. std::string observed_xff;
  14775. svr.Get("/ip", [&](const Request &req, Response &res) {
  14776. observed_remote_addr = req.remote_addr;
  14777. observed_xff = req.get_header_value("X-Forwarded-For");
  14778. res.set_content("ok", "text/plain");
  14779. });
  14780. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14781. auto se = detail::scope_exit([&] {
  14782. svr.stop();
  14783. t.join();
  14784. ASSERT_FALSE(svr.is_running());
  14785. });
  14786. svr.wait_until_ready();
  14787. Client cli(HOST, PORT);
  14788. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14790. EXPECT_EQ(StatusCode::OK_200, res->status);
  14791. EXPECT_EQ(observed_xff, "203.0.113.66");
  14792. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14793. observed_remote_addr == "127.0.0.1");
  14794. }
  14795. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14796. Server svr;
  14797. svr.set_trusted_proxies({"203.0.113.66"});
  14798. std::string observed_remote_addr;
  14799. std::string observed_xff;
  14800. svr.Get("/ip", [&](const Request &req, Response &res) {
  14801. observed_remote_addr = req.remote_addr;
  14802. observed_xff = req.get_header_value("X-Forwarded-For");
  14803. res.set_content("ok", "text/plain");
  14804. });
  14805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14806. auto se = detail::scope_exit([&] {
  14807. svr.stop();
  14808. t.join();
  14809. ASSERT_FALSE(svr.is_running());
  14810. });
  14811. svr.wait_until_ready();
  14812. Client cli(HOST, PORT);
  14813. auto res = cli.Get("/ip");
  14814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14815. EXPECT_EQ(StatusCode::OK_200, res->status);
  14816. EXPECT_EQ(observed_xff, "");
  14817. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14818. observed_remote_addr == "127.0.0.1");
  14819. }
  14820. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14821. Server svr;
  14822. // Include the loopback address the test client actually connects from, so
  14823. // the direct connection itself is recognized as the trusted proxy hop.
  14824. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14825. std::string observed_remote_addr;
  14826. std::string observed_xff;
  14827. svr.Get("/ip", [&](const Request &req, Response &res) {
  14828. observed_remote_addr = req.remote_addr;
  14829. observed_xff = req.get_header_value("X-Forwarded-For");
  14830. res.set_content("ok", "text/plain");
  14831. });
  14832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14833. auto se = detail::scope_exit([&] {
  14834. svr.stop();
  14835. t.join();
  14836. ASSERT_FALSE(svr.is_running());
  14837. });
  14838. svr.wait_until_ready();
  14839. Client cli(HOST, PORT);
  14840. auto res = cli.Get(
  14841. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14843. EXPECT_EQ(StatusCode::OK_200, res->status);
  14844. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14845. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14846. }
  14847. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14848. Server svr;
  14849. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14850. std::string observed_remote_addr;
  14851. std::string observed_xff;
  14852. svr.Get("/ip", [&](const Request &req, Response &res) {
  14853. observed_remote_addr = req.remote_addr;
  14854. observed_xff = req.get_header_value("X-Forwarded-For");
  14855. res.set_content("ok", "text/plain");
  14856. });
  14857. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14858. auto se = detail::scope_exit([&] {
  14859. svr.stop();
  14860. t.join();
  14861. ASSERT_FALSE(svr.is_running());
  14862. });
  14863. svr.wait_until_ready();
  14864. Client cli(HOST, PORT);
  14865. auto res = cli.Get(
  14866. "/ip",
  14867. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14869. EXPECT_EQ(StatusCode::OK_200, res->status);
  14870. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14871. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14872. }
  14873. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14874. Server svr;
  14875. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14876. std::string observed_remote_addr;
  14877. std::string observed_xff;
  14878. svr.Get("/ip", [&](const Request &req, Response &res) {
  14879. observed_remote_addr = req.remote_addr;
  14880. observed_xff = req.get_header_value("X-Forwarded-For");
  14881. res.set_content("ok", "text/plain");
  14882. });
  14883. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14884. auto se = detail::scope_exit([&] {
  14885. svr.stop();
  14886. t.join();
  14887. ASSERT_FALSE(svr.is_running());
  14888. });
  14889. svr.wait_until_ready();
  14890. Client cli(HOST, PORT);
  14891. auto res = cli.Get(
  14892. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14894. EXPECT_EQ(StatusCode::OK_200, res->status);
  14895. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14896. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14897. // and must not be selected.
  14898. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14899. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14900. }
  14901. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14902. Server svr;
  14903. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14904. std::string observed_remote_addr;
  14905. svr.Get("/ip", [&](const Request &req, Response &res) {
  14906. observed_remote_addr = req.remote_addr;
  14907. res.set_content("ok", "text/plain");
  14908. });
  14909. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14910. auto se = detail::scope_exit([&] {
  14911. svr.stop();
  14912. t.join();
  14913. ASSERT_FALSE(svr.is_running());
  14914. });
  14915. svr.wait_until_ready();
  14916. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14917. // a forged address and the trusted proxy's own address; the forged value must
  14918. // not win over the address the trusted proxy actually recorded.
  14919. Client cli(HOST, PORT);
  14920. auto res = cli.Get(
  14921. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14923. EXPECT_EQ(StatusCode::OK_200, res->status);
  14924. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14925. }
  14926. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14927. Server svr;
  14928. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14929. std::string observed_remote_addr;
  14930. std::string observed_xff;
  14931. svr.Get("/ip", [&](const Request &req, Response &res) {
  14932. observed_remote_addr = req.remote_addr;
  14933. observed_xff = req.get_header_value("X-Forwarded-For");
  14934. res.set_content("ok", "text/plain");
  14935. });
  14936. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14937. auto se = detail::scope_exit([&] {
  14938. svr.stop();
  14939. t.join();
  14940. ASSERT_FALSE(svr.is_running());
  14941. });
  14942. svr.wait_until_ready();
  14943. Client cli(HOST, PORT);
  14944. auto res = cli.Get(
  14945. "/ip",
  14946. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14948. EXPECT_EQ(StatusCode::OK_200, res->status);
  14949. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14950. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14951. }
  14952. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14953. Server svr;
  14954. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14955. std::string observed_remote_addr;
  14956. std::string observed_xff;
  14957. svr.Get("/ip", [&](const Request &req, Response &res) {
  14958. observed_remote_addr = req.remote_addr;
  14959. observed_xff = req.get_header_value("X-Forwarded-For");
  14960. res.set_content("ok", "text/plain");
  14961. });
  14962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. std::string raw_req =
  14970. "GET /ip HTTP/1.1\r\n"
  14971. "Host: localhost\r\n"
  14972. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14973. "Connection: close\r\n"
  14974. "\r\n";
  14975. std::string out;
  14976. ASSERT_TRUE(send_request(5, raw_req, &out));
  14977. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14978. // Header parser trims surrounding whitespace of the header value
  14979. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14980. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14981. }
  14982. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14983. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14984. // their own X-Forwarded-For as a separate field line rather than extending the
  14985. // one the client sent, so every occurrence has to be taken into account.
  14986. // Reading only the first one hands back the address the client chose.
  14987. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14988. Server svr;
  14989. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14990. std::string observed_remote_addr;
  14991. size_t observed_xff_count = 0;
  14992. svr.Get("/ip", [&](const Request &req, Response &res) {
  14993. observed_remote_addr = req.remote_addr;
  14994. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14995. res.set_content("ok", "text/plain");
  14996. });
  14997. auto port = svr.bind_to_any_port(HOST);
  14998. thread t = thread([&]() { svr.listen_after_bind(); });
  14999. auto se = detail::scope_exit([&] {
  15000. svr.stop();
  15001. t.join();
  15002. ASSERT_FALSE(svr.is_running());
  15003. });
  15004. svr.wait_until_ready();
  15005. // The client supplies the first field line; the trusted proxy appends the
  15006. // address it observed as a second one.
  15007. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15008. "Host: localhost\r\n"
  15009. "X-Forwarded-For: 1.2.3.4\r\n"
  15010. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15011. "Connection: close\r\n"
  15012. "\r\n";
  15013. std::string out;
  15014. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15015. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15016. EXPECT_EQ(observed_xff_count, 2U);
  15017. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15018. // The same chain spread over one field line per hop derives the same client
  15019. // address, i.e. the split and the comma-joined representations agree.
  15020. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15021. "Host: localhost\r\n"
  15022. "X-Forwarded-For: 1.2.3.4\r\n"
  15023. "X-Forwarded-For: 198.51.100.23\r\n"
  15024. "X-Forwarded-For: 192.0.2.45\r\n"
  15025. "Connection: close\r\n"
  15026. "\r\n";
  15027. out.clear();
  15028. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15029. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15030. EXPECT_EQ(observed_xff_count, 3U);
  15031. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15032. }
  15033. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15034. // crash the server (it used to call front() on an empty vector inside
  15035. // get_client_ip). The connection-level remote address must be retained instead.
  15036. static void run_malformed_xff_test(const std::string &xff_value) {
  15037. Server svr;
  15038. svr.set_trusted_proxies({"192.0.2.45"});
  15039. std::string observed_remote_addr;
  15040. svr.Get("/ip", [&](const Request &req, Response &res) {
  15041. observed_remote_addr = req.remote_addr;
  15042. res.set_content("ok", "text/plain");
  15043. });
  15044. int port = 0;
  15045. thread t = thread([&]() {
  15046. port = svr.bind_to_any_port(HOST);
  15047. svr.listen_after_bind();
  15048. });
  15049. auto se = detail::scope_exit([&] {
  15050. svr.stop();
  15051. t.join();
  15052. ASSERT_FALSE(svr.is_running());
  15053. });
  15054. svr.wait_until_ready();
  15055. Client cli(HOST, port);
  15056. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15058. EXPECT_EQ(StatusCode::OK_200, res->status);
  15059. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15060. observed_remote_addr == "127.0.0.1");
  15061. }
  15062. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15063. run_malformed_xff_test("");
  15064. }
  15065. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15066. run_malformed_xff_test(",");
  15067. }
  15068. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15069. run_malformed_xff_test(", , ,");
  15070. }
  15071. // The same rule applies to Accept: a request whose acceptable types are spread
  15072. // over several field lines must be negotiated against all of them.
  15073. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15074. // case-insensitive connection options. Comparing the whole field value against
  15075. // one option misses a client that sends several of them, and misses every
  15076. // casing but the one written in the comparison.
  15077. //
  15078. // Sends req, reads the response, then reuses the same socket for a second
  15079. // request to find out whether the server kept the connection.
  15080. static void probe_connection_reuse(int port, const std::string &req,
  15081. bool *announced_close, bool *reusable) {
  15082. auto error = Error::Success;
  15083. auto sock = detail::create_client_socket(
  15084. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15085. /*connection_timeout_sec=*/5, 0,
  15086. /*read_timeout_sec=*/1, 0,
  15087. /*write_timeout_sec=*/5, 0, std::string(), error);
  15088. ASSERT_NE(sock, INVALID_SOCKET);
  15089. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15090. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15091. "Host: localhost\r\n"
  15092. "Connection: close\r\n"
  15093. "\r\n";
  15094. std::string first_response;
  15095. std::string second_response;
  15096. detail::process_client_socket(
  15097. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15098. [&](Stream &strm) {
  15099. if (strm.write(req.data(), req.size()) !=
  15100. static_cast<ssize_t>(req.size())) {
  15101. return false;
  15102. }
  15103. char buf[512];
  15104. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15105. // Headers plus the two-byte body of the handler below
  15106. while (reader.getline()) {
  15107. first_response += reader.ptr();
  15108. if (first_response.find("ok") != std::string::npos) { break; }
  15109. }
  15110. if (strm.write(second.data(), second.size()) !=
  15111. static_cast<ssize_t>(second.size())) {
  15112. return true;
  15113. }
  15114. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15115. while (reader2.getline()) {
  15116. second_response += reader2.ptr();
  15117. if (second_response.find("ok") != std::string::npos) { break; }
  15118. }
  15119. return true;
  15120. });
  15121. *announced_close =
  15122. first_response.find("Connection: close") != std::string::npos;
  15123. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15124. }
  15125. class ConnectionTokenTest : public ::testing::Test {
  15126. protected:
  15127. void SetUp() override {
  15128. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15129. res.set_content("ok", "text/plain");
  15130. });
  15131. port_ = svr_.bind_to_any_port(HOST);
  15132. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15133. svr_.wait_until_ready();
  15134. }
  15135. void TearDown() override {
  15136. svr_.stop();
  15137. if (thread_.joinable()) { thread_.join(); }
  15138. }
  15139. Server svr_;
  15140. int port_ = 0;
  15141. thread thread_;
  15142. };
  15143. // "close" alongside another option still closes the connection, and the
  15144. // response says so rather than leaving the peer to discover it.
  15145. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15146. bool announced_close = false;
  15147. bool reusable = true;
  15148. probe_connection_reuse(port_,
  15149. "GET /keepalive HTTP/1.1\r\n"
  15150. "Host: localhost\r\n"
  15151. "Connection: keep-alive, close\r\n"
  15152. "\r\n",
  15153. &announced_close, &reusable);
  15154. EXPECT_TRUE(announced_close);
  15155. EXPECT_FALSE(reusable);
  15156. }
  15157. // "close" split over two field lines is the same list, so it is honored too.
  15158. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15159. bool announced_close = false;
  15160. bool reusable = true;
  15161. probe_connection_reuse(port_,
  15162. "GET /keepalive HTTP/1.1\r\n"
  15163. "Host: localhost\r\n"
  15164. "Connection: keep-alive\r\n"
  15165. "Connection: close\r\n"
  15166. "\r\n",
  15167. &announced_close, &reusable);
  15168. EXPECT_TRUE(announced_close);
  15169. EXPECT_FALSE(reusable);
  15170. }
  15171. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15172. // keep-alive in the spelling everyone actually sends keeps its connection.
  15173. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15174. bool announced_close = false;
  15175. bool reusable = false;
  15176. probe_connection_reuse(port_,
  15177. "GET /keepalive HTTP/1.0\r\n"
  15178. "Host: localhost\r\n"
  15179. "Connection: keep-alive\r\n"
  15180. "\r\n",
  15181. &announced_close, &reusable);
  15182. EXPECT_FALSE(announced_close);
  15183. EXPECT_TRUE(reusable);
  15184. }
  15185. // A token the value merely contains is not the token itself.
  15186. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15187. bool announced_close = false;
  15188. bool reusable = false;
  15189. probe_connection_reuse(port_,
  15190. "GET /keepalive HTTP/1.1\r\n"
  15191. "Host: localhost\r\n"
  15192. "Connection: notclose\r\n"
  15193. "\r\n",
  15194. &announced_close, &reusable);
  15195. EXPECT_FALSE(announced_close);
  15196. EXPECT_TRUE(reusable);
  15197. }
  15198. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15199. Server svr;
  15200. std::vector<std::string> observed_types;
  15201. svr.Get("/", [&](const Request &req, Response &res) {
  15202. observed_types = req.accept_content_types;
  15203. res.set_content("ok", "text/plain");
  15204. });
  15205. auto port = svr.bind_to_any_port(HOST);
  15206. thread t = thread([&]() { svr.listen_after_bind(); });
  15207. auto se = detail::scope_exit([&] {
  15208. svr.stop();
  15209. t.join();
  15210. ASSERT_FALSE(svr.is_running());
  15211. });
  15212. svr.wait_until_ready();
  15213. Client cli(HOST, port);
  15214. Headers headers;
  15215. headers.emplace("Accept", "text/plain;q=0.5");
  15216. headers.emplace("Accept", "application/json");
  15217. auto res = cli.Get("/", headers);
  15218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15219. EXPECT_EQ(StatusCode::OK_200, res->status);
  15220. // Sorted by q-value, so the second field line's type comes first
  15221. ASSERT_EQ(2U, observed_types.size());
  15222. EXPECT_EQ("application/json", observed_types[0]);
  15223. EXPECT_EQ("text/plain", observed_types[1]);
  15224. }
  15225. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15226. // empty field line must not contribute a bare comma to the combined value.
  15227. // parse_accept_header() rejects a leading comma outright, so a stray one would
  15228. // turn a legal request into 400 Bad Request.
  15229. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15230. Server svr;
  15231. std::vector<std::string> observed_types;
  15232. svr.Get("/", [&](const Request &req, Response &res) {
  15233. observed_types = req.accept_content_types;
  15234. res.set_content("ok", "text/plain");
  15235. });
  15236. auto port = svr.bind_to_any_port(HOST);
  15237. thread t = thread([&]() { svr.listen_after_bind(); });
  15238. auto se = detail::scope_exit([&] {
  15239. svr.stop();
  15240. t.join();
  15241. ASSERT_FALSE(svr.is_running());
  15242. });
  15243. svr.wait_until_ready();
  15244. // Empty first field line, then a real one
  15245. std::string raw_req = "GET / HTTP/1.1\r\n"
  15246. "Host: localhost\r\n"
  15247. "Accept:\r\n"
  15248. "Accept: application/json\r\n"
  15249. "Connection: close\r\n"
  15250. "\r\n";
  15251. std::string out;
  15252. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15253. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15254. ASSERT_EQ(1U, observed_types.size());
  15255. EXPECT_EQ("application/json", observed_types[0]);
  15256. }
  15257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15258. // An encoding offered on a later Accept-Encoding field line is still offered.
  15259. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15260. Server svr;
  15261. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15262. res.set_content(std::string(1024, 'x'), "text/plain");
  15263. });
  15264. auto port = svr.bind_to_any_port(HOST);
  15265. thread t = thread([&]() { svr.listen_after_bind(); });
  15266. auto se = detail::scope_exit([&] {
  15267. svr.stop();
  15268. t.join();
  15269. ASSERT_FALSE(svr.is_running());
  15270. });
  15271. svr.wait_until_ready();
  15272. Client cli(HOST, port);
  15273. cli.set_decompress(false);
  15274. Headers headers;
  15275. headers.emplace("Accept-Encoding", "identity");
  15276. headers.emplace("Accept-Encoding", "gzip");
  15277. auto res = cli.Get("/", headers);
  15278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15279. EXPECT_EQ(StatusCode::OK_200, res->status);
  15280. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15281. }
  15282. #endif
  15283. #ifndef _WIN32
  15284. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15285. Server svr;
  15286. svr.Post("/post", [&](const Request &req, Response &res) {
  15287. res.set_content(req.body, "text/plain");
  15288. });
  15289. svr.Put("/put", [&](const Request &req, Response &res) {
  15290. res.set_content(req.body, "text/plain");
  15291. });
  15292. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15293. res.set_content(req.body, "text/plain");
  15294. });
  15295. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15296. res.set_content(req.body, "text/plain");
  15297. });
  15298. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15299. auto se = detail::scope_exit([&] {
  15300. svr.stop();
  15301. t.join();
  15302. ASSERT_FALSE(svr.is_running());
  15303. });
  15304. svr.wait_until_ready();
  15305. std::string resp;
  15306. // POST without Content-Length
  15307. ASSERT_TRUE(send_request(5,
  15308. "POST /post HTTP/1.1\r\n"
  15309. "Host: localhost\r\n"
  15310. "Connection: close\r\n"
  15311. "\r\n",
  15312. &resp));
  15313. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15314. // PUT without Content-Length
  15315. resp.clear();
  15316. ASSERT_TRUE(send_request(5,
  15317. "PUT /put HTTP/1.1\r\n"
  15318. "Host: localhost\r\n"
  15319. "Connection: close\r\n"
  15320. "\r\n",
  15321. &resp));
  15322. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15323. // PATCH without Content-Length
  15324. resp.clear();
  15325. ASSERT_TRUE(send_request(5,
  15326. "PATCH /patch HTTP/1.1\r\n"
  15327. "Host: localhost\r\n"
  15328. "Connection: close\r\n"
  15329. "\r\n",
  15330. &resp));
  15331. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15332. // DELETE without Content-Length
  15333. resp.clear();
  15334. ASSERT_TRUE(send_request(5,
  15335. "DELETE /delete HTTP/1.1\r\n"
  15336. "Host: localhost\r\n"
  15337. "Connection: close\r\n"
  15338. "\r\n",
  15339. &resp));
  15340. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15341. }
  15342. #endif
  15343. //==============================================================================
  15344. // open_stream() Tests
  15345. //==============================================================================
  15346. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15347. std::string result;
  15348. char buf[8192];
  15349. ssize_t n;
  15350. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15351. result.append(buf, static_cast<size_t>(n));
  15352. }
  15353. return result;
  15354. }
  15355. // Mock stream for unit tests
  15356. class MockStream : public Stream {
  15357. public:
  15358. std::string data;
  15359. size_t pos = 0;
  15360. ssize_t error_after = -1; // -1 = no error
  15361. explicit MockStream(const std::string &d, ssize_t err = -1)
  15362. : data(d), error_after(err) {}
  15363. bool is_readable() const override { return true; }
  15364. bool wait_readable() const override { return true; }
  15365. bool wait_writable() const override { return true; }
  15366. ssize_t read(char *ptr, size_t size) override {
  15367. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15368. if (pos >= data.size()) return 0;
  15369. size_t limit =
  15370. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15371. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15372. std::memcpy(ptr, data.data() + pos, to_read);
  15373. pos += to_read;
  15374. return static_cast<ssize_t>(to_read);
  15375. }
  15376. ssize_t write(const char *, size_t) override { return -1; }
  15377. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15378. ip = "127.0.0.1";
  15379. port = 0;
  15380. }
  15381. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15382. ip = "127.0.0.1";
  15383. port = 0;
  15384. }
  15385. socket_t socket() const override { return INVALID_SOCKET; }
  15386. time_t duration() const override { return 0; }
  15387. };
  15388. TEST(StreamHandleTest, Basic) {
  15389. ClientImpl::StreamHandle handle;
  15390. EXPECT_FALSE(handle.is_valid());
  15391. handle.response = detail::make_unique<Response>();
  15392. handle.error = Error::Connection;
  15393. EXPECT_FALSE(handle.is_valid());
  15394. handle.error = Error::Success;
  15395. EXPECT_TRUE(handle.is_valid());
  15396. }
  15397. TEST(BodyReaderTest, Basic) {
  15398. MockStream stream("Hello, World!");
  15399. detail::BodyReader reader;
  15400. reader.stream = &stream;
  15401. reader.content_length = 13;
  15402. char buf[32];
  15403. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15404. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15405. EXPECT_TRUE(reader.eof);
  15406. }
  15407. TEST(BodyReaderTest, NoStream) {
  15408. detail::BodyReader reader;
  15409. char buf[32];
  15410. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15411. EXPECT_EQ(Error::Connection, reader.last_error);
  15412. }
  15413. TEST(BodyReaderTest, Error) {
  15414. MockStream stream("Hello, World!", 5);
  15415. detail::BodyReader reader;
  15416. reader.stream = &stream;
  15417. reader.content_length = 13;
  15418. char buf[32];
  15419. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15420. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15421. EXPECT_EQ(Error::Read, reader.last_error);
  15422. }
  15423. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15424. // Mock-based StreamHandle tests relying on private internals are removed.
  15425. class OpenStreamTest : public ::testing::Test {
  15426. protected:
  15427. void SetUp() override {
  15428. svr_.Get("/hello", [](const Request &, Response &res) {
  15429. res.set_content("Hello World!", "text/plain");
  15430. });
  15431. svr_.Get("/large", [](const Request &, Response &res) {
  15432. res.set_content(std::string(10000, 'X'), "text/plain");
  15433. });
  15434. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15435. res.set_content("Hello World!", "image/jpeg");
  15436. res.set_header("Content-Encoding", "UTF-8");
  15437. });
  15438. svr_.Get("/chunked", [](const Request &, Response &res) {
  15439. res.set_chunked_content_provider("text/plain",
  15440. [](size_t offset, DataSink &sink) {
  15441. if (offset < 15) {
  15442. sink.write("chunk", 5);
  15443. return true;
  15444. }
  15445. sink.done();
  15446. return true;
  15447. });
  15448. });
  15449. svr_.Get("/compressible", [](const Request &, Response &res) {
  15450. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15451. DataSink &sink) {
  15452. if (offset < 100 * 1024) {
  15453. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15454. sink.write(chunk.data(), chunk.size());
  15455. return true;
  15456. }
  15457. sink.done();
  15458. return true;
  15459. });
  15460. });
  15461. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15462. [](const Request & /*req*/, Response &res) {
  15463. auto i = new int(0);
  15464. res.set_header("Trailer", "Content-Length, X-Allowed");
  15465. res.set_chunked_content_provider(
  15466. "text/plain",
  15467. [i](size_t /*offset*/, DataSink &sink) {
  15468. switch (*i) {
  15469. case 0: sink.os << "123"; break;
  15470. case 1: sink.os << "456"; break;
  15471. case 2: sink.os << "789"; break;
  15472. case 3: {
  15473. sink.done_with_trailer(
  15474. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15475. } break;
  15476. }
  15477. (*i)++;
  15478. return true;
  15479. },
  15480. [i](bool success) {
  15481. EXPECT_TRUE(success);
  15482. delete i;
  15483. });
  15484. });
  15485. // Echo headers endpoint for header-related tests
  15486. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15487. std::string body;
  15488. for (const auto &h : req.headers) {
  15489. body.append(h.first);
  15490. body.push_back(':');
  15491. body.append(h.second);
  15492. body.push_back('\n');
  15493. }
  15494. res.set_content(body, "text/plain");
  15495. });
  15496. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15497. std::string body;
  15498. for (const auto &h : req.headers) {
  15499. body.append(h.first);
  15500. body.push_back(':');
  15501. body.append(h.second);
  15502. body.push_back('\n');
  15503. }
  15504. res.set_content(body, "text/plain");
  15505. });
  15506. port_ = svr_.bind_to_any_port("127.0.0.1");
  15507. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15508. svr_.wait_until_ready();
  15509. }
  15510. void TearDown() override {
  15511. svr_.stop();
  15512. if (thread_.joinable()) thread_.join();
  15513. }
  15514. Server svr_;
  15515. std::thread thread_;
  15516. int port_ = 0;
  15517. };
  15518. TEST_F(OpenStreamTest, Basic) {
  15519. Client cli("127.0.0.1", port_);
  15520. auto handle = cli.open_stream("GET", "/hello");
  15521. EXPECT_TRUE(handle.is_valid());
  15522. EXPECT_EQ("Hello World!", read_all(handle));
  15523. }
  15524. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15525. Client cli("127.0.0.1", port_);
  15526. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15527. ASSERT_TRUE(handle.is_valid());
  15528. EXPECT_EQ("Hello World!", read_all(handle));
  15529. }
  15530. TEST_F(OpenStreamTest, SmallBuffer) {
  15531. Client cli("127.0.0.1", port_);
  15532. auto handle = cli.open_stream("GET", "/hello");
  15533. std::string result;
  15534. char buf[4];
  15535. ssize_t n;
  15536. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15537. result.append(buf, static_cast<size_t>(n));
  15538. EXPECT_EQ("Hello World!", result);
  15539. }
  15540. TEST_F(OpenStreamTest, DefaultHeaders) {
  15541. Client cli("127.0.0.1", port_);
  15542. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15543. {
  15544. auto handle = cli.open_stream("GET", "/echo-headers");
  15545. ASSERT_TRUE(handle.is_valid());
  15546. auto body = read_all(handle);
  15547. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15548. std::string::npos);
  15549. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15550. std::string::npos);
  15551. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15552. }
  15553. // open_stream POST with body and no explicit content_type should NOT add
  15554. // text/plain Content-Type (behavior differs from non-streaming path), but
  15555. // should include Content-Length
  15556. {
  15557. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15558. ASSERT_TRUE(handle.is_valid());
  15559. auto body = read_all(handle);
  15560. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15561. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15562. }
  15563. // open_stream POST with explicit Content-Type should preserve it
  15564. {
  15565. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15566. {{"Content-Type", "application/custom"}},
  15567. "{}", "application/custom");
  15568. ASSERT_TRUE(handle.is_valid());
  15569. auto body = read_all(handle);
  15570. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15571. }
  15572. // User-specified User-Agent must not be overwritten for stream API
  15573. {
  15574. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15575. {{"User-Agent", "MyAgent/1.2"}});
  15576. ASSERT_TRUE(handle.is_valid());
  15577. auto body = read_all(handle);
  15578. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15579. }
  15580. }
  15581. TEST_F(OpenStreamTest, Large) {
  15582. Client cli("127.0.0.1", port_);
  15583. auto handle = cli.open_stream("GET", "/large");
  15584. EXPECT_EQ(10000u, read_all(handle).size());
  15585. }
  15586. TEST_F(OpenStreamTest, ConnectionError) {
  15587. Client cli("127.0.0.1", 9999);
  15588. auto handle = cli.open_stream("GET", "/hello");
  15589. EXPECT_FALSE(handle.is_valid());
  15590. }
  15591. TEST_F(OpenStreamTest, Chunked) {
  15592. Client cli("127.0.0.1", port_);
  15593. auto handle = cli.open_stream("GET", "/chunked");
  15594. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15595. "Transfer-Encoding") == "chunked");
  15596. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15597. }
  15598. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15599. Client cli("127.0.0.1", port_);
  15600. auto handle =
  15601. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15602. ASSERT_TRUE(handle.is_valid());
  15603. // Consume body to allow trailers to be received/parsed
  15604. auto body = read_all(handle);
  15605. // Explicitly parse trailers (ensure trailers are available for assertion)
  15606. handle.parse_trailers_if_needed();
  15607. EXPECT_EQ(std::string("123456789"), body);
  15608. // The response should include a Trailer header declaring both names
  15609. ASSERT_TRUE(handle.response);
  15610. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15611. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15612. handle.response->get_header_value("Trailer"));
  15613. // Prohibited trailer must not be present
  15614. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15615. // Allowed trailer should be present
  15616. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15617. EXPECT_EQ(std::string("yes"),
  15618. handle.response->get_trailer_value("X-Allowed"));
  15619. // Verify trailers are NOT present as regular headers
  15620. EXPECT_EQ(std::string(""),
  15621. handle.response->get_header_value("Content-Length"));
  15622. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15623. }
  15624. static std::thread serve_single_response(std::promise<int> &port_promise,
  15625. const std::string &response) {
  15626. return std::thread([&port_promise, response] {
  15627. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15628. default_socket_options(srv);
  15629. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15630. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15631. sockaddr_in addr{};
  15632. addr.sin_family = AF_INET;
  15633. addr.sin_port = htons(0); // Let OS assign a free port
  15634. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15635. int opt = 1;
  15636. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15637. #ifdef _WIN32
  15638. reinterpret_cast<const char *>(&opt),
  15639. #else
  15640. &opt,
  15641. #endif
  15642. sizeof(opt));
  15643. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15644. ::listen(srv, 1) != 0) {
  15645. port_promise.set_value(-1);
  15646. detail::close_socket(srv);
  15647. return;
  15648. }
  15649. socklen_t addr_len = sizeof(addr);
  15650. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15651. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15652. sockaddr_in cli_addr{};
  15653. socklen_t cli_len = sizeof(cli_addr);
  15654. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15655. if (cli != INVALID_SOCKET) {
  15656. // Read the complete HTTP request (until the blank line that terminates
  15657. // headers) before sending the response. If the server closes the socket
  15658. // while the client's request data is still unread in the kernel receive
  15659. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15660. // connection on both sides: it discards the client's receive buffer
  15661. // (which already holds our response) and causes any in-progress write on
  15662. // the client to fail with ECONNRESET. Reading all request data first
  15663. // ensures close() emits a graceful FIN.
  15664. {
  15665. char rbuf[256];
  15666. std::string req;
  15667. while (req.find("\r\n\r\n") == std::string::npos) {
  15668. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15669. if (n <= 0) { break; }
  15670. req.append(rbuf, static_cast<size_t>(n));
  15671. }
  15672. }
  15673. ::send(cli,
  15674. #ifdef _WIN32
  15675. static_cast<const char *>(response.c_str()),
  15676. static_cast<int>(response.size()),
  15677. #else
  15678. response.c_str(), response.size(),
  15679. #endif
  15680. 0);
  15681. detail::close_socket(cli);
  15682. }
  15683. detail::close_socket(srv);
  15684. });
  15685. }
  15686. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15687. #ifndef _WIN32
  15688. signal(SIGPIPE, SIG_IGN);
  15689. #endif
  15690. std::promise<int> port_promise;
  15691. auto port_future = port_promise.get_future();
  15692. auto server_thread =
  15693. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15694. "Content-Type: text/plain\r\n"
  15695. "Content-Length: not-a-number\r\n"
  15696. "Connection: close\r\n"
  15697. "\r\n"
  15698. "hello");
  15699. auto port = port_future.get();
  15700. ASSERT_GT(port, 0);
  15701. Client cli("127.0.0.1", port);
  15702. auto handle = cli.open_stream("GET", "/");
  15703. EXPECT_FALSE(handle.is_valid());
  15704. server_thread.join();
  15705. }
  15706. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15707. #ifndef _WIN32
  15708. signal(SIGPIPE, SIG_IGN);
  15709. #endif
  15710. std::promise<int> port_promise;
  15711. auto port_future = port_promise.get_future();
  15712. auto server_thread = serve_single_response(
  15713. port_promise, "HTTP/1.1 200 OK\r\n"
  15714. "Content-Type: text/plain\r\n"
  15715. "Content-Length: 99999999999999999999999999\r\n"
  15716. "Connection: close\r\n"
  15717. "\r\n"
  15718. "hello");
  15719. auto port = port_future.get();
  15720. ASSERT_GT(port, 0);
  15721. // Historically std::stoull would throw std::out_of_range here and crash
  15722. // the process, then parsing silently clamped to a bogus framing length and
  15723. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15724. // so the stream fails to open, matching the not-a-number case above. The
  15725. // process still must NOT terminate.
  15726. Client cli("127.0.0.1", port);
  15727. auto handle = cli.open_stream("GET", "/");
  15728. EXPECT_FALSE(handle.is_valid());
  15729. server_thread.join();
  15730. }
  15731. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15732. TEST_F(OpenStreamTest, Gzip) {
  15733. Client cli("127.0.0.1", port_);
  15734. auto handle = cli.open_stream("GET", "/compressible", {},
  15735. {{"Accept-Encoding", "gzip"}});
  15736. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15737. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15738. }
  15739. #endif
  15740. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15741. TEST_F(OpenStreamTest, Brotli) {
  15742. Client cli("127.0.0.1", port_);
  15743. auto handle =
  15744. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15745. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15746. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15747. }
  15748. #endif
  15749. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15750. TEST_F(OpenStreamTest, Zstd) {
  15751. Client cli("127.0.0.1", port_);
  15752. auto handle = cli.open_stream("GET", "/compressible", {},
  15753. {{"Accept-Encoding", "zstd"}});
  15754. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15755. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15756. }
  15757. #endif
  15758. #ifdef CPPHTTPLIB_SSL_ENABLED
  15759. class SSLOpenStreamTest : public ::testing::Test {
  15760. protected:
  15761. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15762. void SetUp() override {
  15763. svr_.Get("/hello", [](const Request &, Response &res) {
  15764. res.set_content("Hello SSL World!", "text/plain");
  15765. });
  15766. svr_.Get("/chunked", [](const Request &, Response &res) {
  15767. res.set_chunked_content_provider("text/plain",
  15768. [](size_t offset, DataSink &sink) {
  15769. if (offset < 15) {
  15770. sink.write("chunk", 5);
  15771. return true;
  15772. }
  15773. sink.done();
  15774. return true;
  15775. });
  15776. });
  15777. svr_.Post("/echo", [](const Request &req, Response &res) {
  15778. res.set_content(req.body, req.get_header_value("Content-Type"));
  15779. });
  15780. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15781. std::string body = req.body;
  15782. res.set_chunked_content_provider(
  15783. "text/plain", [body](size_t offset, DataSink &sink) {
  15784. if (offset < body.size()) {
  15785. sink.write(body.data() + offset, body.size() - offset);
  15786. }
  15787. sink.done();
  15788. return true;
  15789. });
  15790. });
  15791. port_ = svr_.bind_to_any_port("127.0.0.1");
  15792. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15793. svr_.wait_until_ready();
  15794. }
  15795. void TearDown() override {
  15796. svr_.stop();
  15797. if (thread_.joinable()) thread_.join();
  15798. }
  15799. SSLServer svr_;
  15800. std::thread thread_;
  15801. int port_ = 0;
  15802. };
  15803. TEST_F(SSLOpenStreamTest, Basic) {
  15804. SSLClient cli("127.0.0.1", port_);
  15805. cli.enable_server_certificate_verification(false);
  15806. auto handle = cli.open_stream("GET", "/hello");
  15807. ASSERT_TRUE(handle.is_valid());
  15808. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15809. }
  15810. TEST_F(SSLOpenStreamTest, Chunked) {
  15811. SSLClient cli("127.0.0.1", port_);
  15812. cli.enable_server_certificate_verification(false);
  15813. auto handle = cli.open_stream("GET", "/chunked");
  15814. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15815. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15816. "Transfer-Encoding") == "chunked");
  15817. auto body = read_all(handle);
  15818. EXPECT_EQ("chunkchunkchunk", body);
  15819. }
  15820. TEST_F(SSLOpenStreamTest, Post) {
  15821. SSLClient cli("127.0.0.1", port_);
  15822. cli.enable_server_certificate_verification(false);
  15823. auto handle =
  15824. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15825. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15826. EXPECT_EQ(200, handle.response->status);
  15827. auto body = read_all(handle);
  15828. EXPECT_EQ("Hello SSL POST", body);
  15829. }
  15830. TEST_F(SSLOpenStreamTest, PostChunked) {
  15831. SSLClient cli("127.0.0.1", port_);
  15832. cli.enable_server_certificate_verification(false);
  15833. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15834. "Chunked SSL Data", "text/plain");
  15835. ASSERT_TRUE(handle.is_valid());
  15836. EXPECT_EQ(200, handle.response->status);
  15837. auto body = read_all(handle);
  15838. EXPECT_EQ("Chunked SSL Data", body);
  15839. }
  15840. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15841. // Content-Length is terminated by the server closing the connection. When the
  15842. // SSL peer sends a close_notify after the body, the client must treat it as a
  15843. // clean EOF and return a successful response rather than an error.
  15844. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15846. ASSERT_TRUE(svr.is_valid());
  15847. svr.set_keep_alive_max_count(1);
  15848. const std::string expected_body = "Hello from connection-close response!";
  15849. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15850. res.set_content_provider("text/plain",
  15851. [&](size_t offset, DataSink &sink) -> bool {
  15852. if (offset < expected_body.size()) {
  15853. sink.write(expected_body.data() + offset,
  15854. expected_body.size() - offset);
  15855. }
  15856. sink.done();
  15857. return true;
  15858. });
  15859. });
  15860. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15861. auto se = detail::scope_exit([&] {
  15862. svr.stop();
  15863. listen_thread.join();
  15864. ASSERT_FALSE(svr.is_running());
  15865. });
  15866. svr.wait_until_ready();
  15867. SSLClient cli(HOST, PORT);
  15868. cli.enable_server_certificate_verification(false);
  15869. auto res = cli.Get("/no-content-length");
  15870. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15871. EXPECT_EQ(StatusCode::OK_200, res->status);
  15872. EXPECT_EQ(expected_body, res->body);
  15873. }
  15874. #endif // CPPHTTPLIB_SSL_ENABLED
  15875. //==============================================================================
  15876. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15877. // results for various scenarios.
  15878. //==============================================================================
  15879. TEST(ParityTest, GetVsOpenStream) {
  15880. Server svr;
  15881. const std::string path = "/parity";
  15882. const std::string content = "Parity test content: hello world";
  15883. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15884. res.set_content(content, "text/plain");
  15885. });
  15886. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15887. auto se = detail::scope_exit([&] {
  15888. svr.stop();
  15889. t.join();
  15890. ASSERT_FALSE(svr.is_running());
  15891. });
  15892. svr.wait_until_ready();
  15893. Client cli(HOST, PORT);
  15894. // Non-stream path
  15895. auto r1 = cli.Get(path);
  15896. ASSERT_TRUE(r1);
  15897. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15898. // Stream path
  15899. auto h = cli.open_stream("GET", path);
  15900. ASSERT_TRUE(h.is_valid());
  15901. EXPECT_EQ(r1->body, read_all(h));
  15902. }
  15903. // Helper to compress data with provided compressor type T
  15904. template <typename Compressor>
  15905. static std::string compress_payload_for_parity(const std::string &in) {
  15906. std::string out;
  15907. Compressor compressor;
  15908. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15909. [&](const char *data, size_t n) {
  15910. out.append(data, n);
  15911. return true;
  15912. });
  15913. EXPECT_TRUE(ok);
  15914. return out;
  15915. }
  15916. // Helper function for compression parity tests
  15917. template <typename Compressor>
  15918. static void test_compression_parity(const std::string &original,
  15919. const std::string &path,
  15920. const std::string &encoding) {
  15921. const std::string compressed =
  15922. compress_payload_for_parity<Compressor>(original);
  15923. Server svr;
  15924. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15925. res.set_content(compressed, "application/octet-stream");
  15926. res.set_header("Content-Encoding", encoding);
  15927. });
  15928. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15929. auto se = detail::scope_exit([&] {
  15930. svr.stop();
  15931. t.join();
  15932. ASSERT_FALSE(svr.is_running());
  15933. });
  15934. svr.wait_until_ready();
  15935. Client cli(HOST, PORT);
  15936. // Non-streaming
  15937. {
  15938. auto res = cli.Get(path);
  15939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15940. EXPECT_EQ(StatusCode::OK_200, res->status);
  15941. EXPECT_EQ(original, res->body);
  15942. }
  15943. // Streaming
  15944. {
  15945. auto h = cli.open_stream("GET", path);
  15946. ASSERT_TRUE(h.is_valid());
  15947. EXPECT_EQ(original, read_all(h));
  15948. }
  15949. }
  15950. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15951. TEST(ParityTest, Gzip) {
  15952. test_compression_parity<detail::gzip_compressor>(
  15953. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15954. }
  15955. #endif
  15956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15957. TEST(ParityTest, Brotli) {
  15958. test_compression_parity<detail::brotli_compressor>(
  15959. "Hello, brotli parity test payload", "/parity-br", "br");
  15960. }
  15961. #endif
  15962. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15963. TEST(ParityTest, Zstd) {
  15964. test_compression_parity<detail::zstd_compressor>(
  15965. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15966. }
  15967. #endif
  15968. //==============================================================================
  15969. // New Stream API Tests
  15970. //==============================================================================
  15971. inline std::string read_body(httplib::stream::Result &result) {
  15972. std::string body;
  15973. while (result.next()) {
  15974. body.append(result.data(), result.size());
  15975. }
  15976. return body;
  15977. }
  15978. TEST(ClientConnectionTest, Basic) {
  15979. httplib::ClientConnection conn;
  15980. EXPECT_FALSE(conn.is_open());
  15981. conn.sock = 1;
  15982. EXPECT_TRUE(conn.is_open());
  15983. httplib::ClientConnection conn2(std::move(conn));
  15984. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15985. conn2.sock = INVALID_SOCKET;
  15986. }
  15987. // Unified test server for all stream::* tests
  15988. class StreamApiTest : public ::testing::Test {
  15989. protected:
  15990. void SetUp() override {
  15991. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15992. res.set_content("Hello World!", "text/plain");
  15993. });
  15994. svr_.Get("/echo-params",
  15995. [](const httplib::Request &req, httplib::Response &res) {
  15996. std::string r;
  15997. for (const auto &p : req.params) {
  15998. if (!r.empty()) r += "&";
  15999. r += p.first + "=" + p.second;
  16000. }
  16001. res.set_content(r, "text/plain");
  16002. });
  16003. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16004. res.set_content(req.body, req.get_header_value("Content-Type"));
  16005. });
  16006. svr_.Post("/echo-headers",
  16007. [](const httplib::Request &req, httplib::Response &res) {
  16008. std::string r;
  16009. for (const auto &h : req.headers)
  16010. r += h.first + ": " + h.second + "\n";
  16011. res.set_content(r, "text/plain");
  16012. });
  16013. svr_.Post("/echo-params",
  16014. [](const httplib::Request &req, httplib::Response &res) {
  16015. std::string r = "params:";
  16016. for (const auto &p : req.params)
  16017. r += p.first + "=" + p.second + ";";
  16018. res.set_content(r + " body:" + req.body, "text/plain");
  16019. });
  16020. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16021. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16022. });
  16023. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16024. res.set_content("PUT:" + req.body, "text/plain");
  16025. });
  16026. svr_.Patch("/echo",
  16027. [](const httplib::Request &req, httplib::Response &res) {
  16028. res.set_content("PATCH:" + req.body, "text/plain");
  16029. });
  16030. svr_.Delete(
  16031. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16032. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16033. "text/plain");
  16034. });
  16035. svr_.Get("/head-test",
  16036. [](const httplib::Request &, httplib::Response &res) {
  16037. res.set_content("body for HEAD", "text/plain");
  16038. });
  16039. svr_.Options("/options",
  16040. [](const httplib::Request &, httplib::Response &res) {
  16041. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16042. });
  16043. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16044. svr_.wait_until_ready();
  16045. }
  16046. void TearDown() override {
  16047. svr_.stop();
  16048. if (thread_.joinable()) thread_.join();
  16049. }
  16050. httplib::Server svr_;
  16051. std::thread thread_;
  16052. };
  16053. // stream::Get tests
  16054. TEST_F(StreamApiTest, GetBasic) {
  16055. httplib::Client cli(HOST, PORT);
  16056. auto result = httplib::stream::Get(cli, "/hello");
  16057. ASSERT_TRUE(result.is_valid());
  16058. EXPECT_EQ(200, result.status());
  16059. EXPECT_EQ("Hello World!", read_body(result));
  16060. }
  16061. TEST_F(StreamApiTest, GetWithParams) {
  16062. httplib::Client cli(HOST, PORT);
  16063. httplib::Params params{{"foo", "bar"}};
  16064. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16065. ASSERT_TRUE(result.is_valid());
  16066. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16067. }
  16068. TEST_F(StreamApiTest, GetConnectionError) {
  16069. httplib::Client cli(HOST, 9999);
  16070. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16071. }
  16072. TEST_F(StreamApiTest, Get404) {
  16073. httplib::Client cli(HOST, PORT);
  16074. auto result = httplib::stream::Get(cli, "/nonexistent");
  16075. EXPECT_TRUE(result.is_valid());
  16076. EXPECT_EQ(404, result.status());
  16077. }
  16078. // stream::Post tests
  16079. TEST_F(StreamApiTest, PostBasic) {
  16080. httplib::Client cli(HOST, PORT);
  16081. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16082. "application/json");
  16083. ASSERT_TRUE(result.is_valid());
  16084. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16085. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16086. }
  16087. TEST_F(StreamApiTest, PostWithHeaders) {
  16088. httplib::Client cli(HOST, PORT);
  16089. httplib::Headers headers{{"X-Custom", "value"}};
  16090. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16091. "text/plain");
  16092. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16093. }
  16094. TEST_F(StreamApiTest, PostWithParams) {
  16095. httplib::Client cli(HOST, PORT);
  16096. httplib::Params params{{"k", "v"}};
  16097. auto result =
  16098. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16099. auto body = read_body(result);
  16100. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16101. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16102. }
  16103. TEST_F(StreamApiTest, PostLarge) {
  16104. httplib::Client cli(HOST, PORT);
  16105. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16106. size_t total = 0;
  16107. while (result.next()) {
  16108. total += result.size();
  16109. }
  16110. EXPECT_EQ(100u * 1024u, total);
  16111. }
  16112. // stream::Put/Patch tests
  16113. TEST_F(StreamApiTest, PutAndPatch) {
  16114. httplib::Client cli(HOST, PORT);
  16115. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16116. EXPECT_EQ("PUT:test", read_body(put));
  16117. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16118. EXPECT_EQ("PATCH:test", read_body(patch));
  16119. }
  16120. // stream::Delete tests
  16121. TEST_F(StreamApiTest, Delete) {
  16122. httplib::Client cli(HOST, PORT);
  16123. auto del1 = httplib::stream::Delete(cli, "/resource");
  16124. EXPECT_EQ("Deleted", read_body(del1));
  16125. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16126. EXPECT_EQ("Deleted:data", read_body(del2));
  16127. }
  16128. // stream::Head/Options tests
  16129. TEST_F(StreamApiTest, HeadAndOptions) {
  16130. httplib::Client cli(HOST, PORT);
  16131. auto head = httplib::stream::Head(cli, "/head-test");
  16132. EXPECT_TRUE(head.is_valid());
  16133. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16134. auto opts = httplib::stream::Options(cli, "/options");
  16135. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16136. }
  16137. // SSL stream::* tests
  16138. #ifdef CPPHTTPLIB_SSL_ENABLED
  16139. class SSLStreamApiTest : public ::testing::Test {
  16140. protected:
  16141. void SetUp() override {
  16142. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16143. res.set_content("Hello SSL!", "text/plain");
  16144. });
  16145. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16146. res.set_content(req.body, "text/plain");
  16147. });
  16148. port_ = svr_.bind_to_any_port("127.0.0.1");
  16149. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16150. svr_.wait_until_ready();
  16151. }
  16152. void TearDown() override {
  16153. svr_.stop();
  16154. if (thread_.joinable()) thread_.join();
  16155. }
  16156. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16157. std::thread thread_;
  16158. int port_ = 0;
  16159. };
  16160. TEST_F(SSLStreamApiTest, GetAndPost) {
  16161. httplib::SSLClient cli("127.0.0.1", port_);
  16162. cli.enable_server_certificate_verification(false);
  16163. auto get = httplib::stream::Get(cli, "/hello");
  16164. EXPECT_EQ("Hello SSL!", read_body(get));
  16165. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16166. EXPECT_EQ("test", read_body(post));
  16167. }
  16168. #endif
  16169. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16170. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16171. // BodyReader
  16172. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16173. // Test that read timeout during streaming is detected
  16174. // Use a large content-length response where server delays mid-stream
  16175. Server svr;
  16176. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16177. // Send a large response with delay in the middle
  16178. res.set_content_provider(
  16179. 1000, // content_length
  16180. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16181. if (offset < 100) {
  16182. // Send first 100 bytes immediately
  16183. std::string data(100, 'A');
  16184. sink.write(data.c_str(), data.size());
  16185. return true;
  16186. }
  16187. // Then delay longer than client timeout
  16188. std::this_thread::sleep_for(std::chrono::seconds(3));
  16189. std::string data(900, 'B');
  16190. sink.write(data.c_str(), data.size());
  16191. return true;
  16192. });
  16193. });
  16194. auto port = 8091;
  16195. std::thread t([&]() { svr.listen("localhost", port); });
  16196. svr.wait_until_ready();
  16197. Client cli("localhost", port);
  16198. cli.set_read_timeout(1, 0); // 1 second timeout
  16199. auto handle = cli.open_stream("GET", "/slow-stream");
  16200. ASSERT_TRUE(handle.is_valid());
  16201. char buf[256];
  16202. ssize_t total = 0;
  16203. ssize_t n;
  16204. bool got_error = false;
  16205. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16206. total += n;
  16207. }
  16208. if (n < 0) {
  16209. got_error = true;
  16210. // Should be timeout or read error
  16211. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16212. handle.get_read_error() == Error::Read)
  16213. << "Actual error: " << to_string(handle.get_read_error());
  16214. }
  16215. // Either we got an error, or we got less data than expected
  16216. EXPECT_TRUE(got_error || total < 1000)
  16217. << "Expected timeout but got all " << total << " bytes";
  16218. svr.stop();
  16219. t.join();
  16220. }
  16221. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16222. // Test connection closed detection via BodyReader
  16223. Server svr;
  16224. std::atomic<bool> close_now{false};
  16225. svr.Get("/will-close", [&](const Request &, Response &res) {
  16226. res.set_content_provider(
  16227. 10000, // Large content_length that we won't fully send
  16228. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16229. if (offset < 100) {
  16230. std::string data(100, 'X');
  16231. sink.write(data.c_str(), data.size());
  16232. return true;
  16233. }
  16234. // Wait for signal then abort
  16235. while (!close_now) {
  16236. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16237. }
  16238. return false; // Abort - server will close connection
  16239. });
  16240. });
  16241. auto port = 8092;
  16242. std::thread t([&]() { svr.listen("localhost", port); });
  16243. svr.wait_until_ready();
  16244. Client cli("localhost", port);
  16245. auto handle = cli.open_stream("GET", "/will-close");
  16246. ASSERT_TRUE(handle.is_valid());
  16247. char buf[256];
  16248. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16249. EXPECT_GT(n, 0) << "First read should succeed";
  16250. // Signal server to close
  16251. close_now = true;
  16252. // Keep reading until error or EOF
  16253. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16254. // Keep reading
  16255. }
  16256. // Should get an error since content_length wasn't satisfied
  16257. if (n < 0) {
  16258. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16259. handle.get_read_error() == Error::Read)
  16260. << "Actual error: " << to_string(handle.get_read_error());
  16261. }
  16262. svr.stop();
  16263. t.join();
  16264. }
  16265. #ifdef CPPHTTPLIB_SSL_ENABLED
  16266. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16267. // Test that read timeout during SSL streaming is detected
  16268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16269. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16270. res.set_content_provider(
  16271. 1000, "text/plain",
  16272. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16273. if (offset < 100) {
  16274. std::string data(100, 'A');
  16275. sink.write(data.c_str(), data.size());
  16276. return true;
  16277. }
  16278. std::this_thread::sleep_for(std::chrono::seconds(3));
  16279. std::string data(900, 'B');
  16280. sink.write(data.c_str(), data.size());
  16281. return true;
  16282. });
  16283. });
  16284. auto port = 8093;
  16285. std::thread t([&]() { svr.listen("localhost", port); });
  16286. svr.wait_until_ready();
  16287. SSLClient cli("localhost", port);
  16288. cli.enable_server_certificate_verification(false);
  16289. cli.set_read_timeout(1, 0); // 1 second timeout
  16290. auto handle = cli.open_stream("GET", "/slow-stream");
  16291. ASSERT_TRUE(handle.is_valid());
  16292. char buf[256];
  16293. ssize_t total = 0;
  16294. ssize_t n;
  16295. bool got_error = false;
  16296. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16297. total += n;
  16298. }
  16299. if (n < 0) {
  16300. got_error = true;
  16301. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16302. handle.get_read_error() == Error::Read)
  16303. << "Actual error: " << to_string(handle.get_read_error());
  16304. }
  16305. EXPECT_TRUE(got_error || total < 1000)
  16306. << "Expected timeout but got all " << total << " bytes";
  16307. svr.stop();
  16308. t.join();
  16309. }
  16310. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16311. // Test SSL connection closed detection
  16312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16313. std::atomic<bool> close_now{false};
  16314. svr.Get("/will-close", [&](const Request &, Response &res) {
  16315. res.set_content_provider(
  16316. 10000, "text/plain",
  16317. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16318. if (offset < 100) {
  16319. std::string data(100, 'X');
  16320. sink.write(data.c_str(), data.size());
  16321. return true;
  16322. }
  16323. while (!close_now) {
  16324. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16325. }
  16326. return false;
  16327. });
  16328. });
  16329. auto port = 8094;
  16330. std::thread t([&]() { svr.listen("localhost", port); });
  16331. svr.wait_until_ready();
  16332. SSLClient cli("localhost", port);
  16333. cli.enable_server_certificate_verification(false);
  16334. auto handle = cli.open_stream("GET", "/will-close");
  16335. ASSERT_TRUE(handle.is_valid());
  16336. char buf[256];
  16337. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16338. EXPECT_GT(n, 0);
  16339. // Signal server to close
  16340. close_now = true;
  16341. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16342. // Keep reading
  16343. }
  16344. if (n < 0) {
  16345. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16346. handle.get_read_error() == Error::Read)
  16347. << "Actual error: " << to_string(handle.get_read_error());
  16348. }
  16349. svr.stop();
  16350. t.join();
  16351. }
  16352. #endif
  16353. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16354. using namespace httplib;
  16355. // Create a test file
  16356. const char *fname = "etag_testfile.txt";
  16357. const char *content = "etag-content";
  16358. {
  16359. std::ofstream ofs(fname);
  16360. ofs << content;
  16361. ASSERT_TRUE(ofs.good());
  16362. }
  16363. Server svr;
  16364. svr.set_mount_point("/static", ".");
  16365. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16366. svr.wait_until_ready();
  16367. Client cli(HOST, PORT);
  16368. // First request: should get 200 with ETag header
  16369. auto res1 = cli.Get("/static/etag_testfile.txt");
  16370. ASSERT_TRUE(res1);
  16371. ASSERT_EQ(200, res1->status);
  16372. ASSERT_TRUE(res1->has_header("ETag"));
  16373. std::string etag = res1->get_header_value("ETag");
  16374. EXPECT_FALSE(etag.empty());
  16375. // Verify ETag format: W/"hex-hex"
  16376. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16377. EXPECT_EQ('W', etag[0]);
  16378. EXPECT_EQ('/', etag[1]);
  16379. EXPECT_EQ('"', etag[2]);
  16380. EXPECT_EQ('"', etag.back());
  16381. // Exact match: expect 304 Not Modified
  16382. Headers h2 = {{"If-None-Match", etag}};
  16383. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16384. ASSERT_TRUE(res2);
  16385. EXPECT_EQ(304, res2->status);
  16386. // Wildcard match: expect 304 Not Modified
  16387. Headers h3 = {{"If-None-Match", "*"}};
  16388. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16389. ASSERT_TRUE(res3);
  16390. EXPECT_EQ(304, res3->status);
  16391. // Non-matching ETag: expect 200
  16392. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16393. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16394. ASSERT_TRUE(res4);
  16395. EXPECT_EQ(200, res4->status);
  16396. // Multiple ETags with one matching: expect 304
  16397. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16398. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16399. ASSERT_TRUE(res5);
  16400. EXPECT_EQ(304, res5->status);
  16401. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16402. // that equivalent to the single comma-separated list above, so the match on
  16403. // the second line must still be found.
  16404. Headers h6;
  16405. h6.emplace("If-None-Match", "W/\"other\"");
  16406. h6.emplace("If-None-Match", etag);
  16407. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16408. ASSERT_TRUE(res6);
  16409. EXPECT_EQ(304, res6->status);
  16410. svr.stop();
  16411. t.join();
  16412. std::remove(fname);
  16413. }
  16414. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16415. using namespace httplib;
  16416. Server svr;
  16417. svr.set_mount_point("/static", ".");
  16418. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16419. svr.wait_until_ready();
  16420. Client cli(HOST, PORT);
  16421. // Send If-None-Match: * to a non-existent file
  16422. Headers h = {{"If-None-Match", "*"}};
  16423. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16425. EXPECT_EQ(404, res->status);
  16426. svr.stop();
  16427. t.join();
  16428. }
  16429. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16430. using namespace httplib;
  16431. // Create a test file
  16432. const char *fname = "etag_boundary_testfile.txt";
  16433. const char *content = "boundary-test";
  16434. {
  16435. std::ofstream ofs(fname);
  16436. ofs << content;
  16437. ASSERT_TRUE(ofs.good());
  16438. }
  16439. Server svr;
  16440. svr.set_mount_point("/static", ".");
  16441. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16442. svr.wait_until_ready();
  16443. Client cli(HOST, PORT);
  16444. // Get the actual ETag
  16445. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16446. ASSERT_TRUE(res1);
  16447. ASSERT_EQ(200, res1->status);
  16448. ASSERT_TRUE(res1->has_header("ETag"));
  16449. std::string etag = res1->get_header_value("ETag");
  16450. // Test 1: Very long ETag value (longer than actual ETag)
  16451. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16452. Headers h1 = {{"If-None-Match", "W/"
  16453. "\"very-long-etag-value-that-is-much-longer-"
  16454. "than-the-actual-etag-value\""}};
  16455. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16456. ASSERT_TRUE(res2);
  16457. EXPECT_EQ(200, res2->status); // Should not match
  16458. // Test 2: Long string followed by wildcard
  16459. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16460. // string)
  16461. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16462. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16463. ASSERT_TRUE(res3);
  16464. EXPECT_EQ(304, res3->status); // Should match on "*"
  16465. // Test 3: Wildcard followed by long string
  16466. // Should match on "*" immediately and return 304
  16467. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16468. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16469. ASSERT_TRUE(res4);
  16470. EXPECT_EQ(304, res4->status); // Should match on "*"
  16471. // Test 4: Multiple long non-matching values
  16472. // Should NOT match and return 200 (test that all comparisons are safe)
  16473. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16474. "W/\"second-long-non-matching-value\", "
  16475. "W/\"third-long-non-matching-value\""}};
  16476. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16477. ASSERT_TRUE(res5);
  16478. EXPECT_EQ(200, res5->status); // Should not match
  16479. // Test 5: Single character that is not "*" (edge case)
  16480. Headers h5 = {{"If-None-Match", "X"}};
  16481. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16482. ASSERT_TRUE(res6);
  16483. EXPECT_EQ(200, res6->status); // Should not match
  16484. svr.stop();
  16485. t.join();
  16486. std::remove(fname);
  16487. }
  16488. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16489. using namespace httplib;
  16490. // Create a test file
  16491. const char *fname = "ims_testfile.txt";
  16492. const char *content = "if-modified-since-test";
  16493. {
  16494. std::ofstream ofs(fname);
  16495. ofs << content;
  16496. ASSERT_TRUE(ofs.good());
  16497. }
  16498. Server svr;
  16499. svr.set_mount_point("/static", ".");
  16500. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16501. svr.wait_until_ready();
  16502. Client cli(HOST, PORT);
  16503. // First request: should get 200 with Last-Modified header
  16504. auto res1 = cli.Get("/static/ims_testfile.txt");
  16505. ASSERT_TRUE(res1);
  16506. ASSERT_EQ(200, res1->status);
  16507. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16508. std::string last_modified = res1->get_header_value("Last-Modified");
  16509. EXPECT_FALSE(last_modified.empty());
  16510. // If-Modified-Since with same time: expect 304
  16511. Headers h2 = {{"If-Modified-Since", last_modified}};
  16512. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16513. ASSERT_TRUE(res2);
  16514. EXPECT_EQ(304, res2->status);
  16515. // If-Modified-Since with future time: expect 304
  16516. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16517. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16518. ASSERT_TRUE(res3);
  16519. EXPECT_EQ(304, res3->status);
  16520. // If-Modified-Since with past time: expect 200
  16521. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16522. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16523. ASSERT_TRUE(res4);
  16524. EXPECT_EQ(200, res4->status);
  16525. // If-None-Match takes precedence over If-Modified-Since
  16526. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16527. ASSERT_TRUE(res1->has_header("ETag"));
  16528. std::string etag = res1->get_header_value("ETag");
  16529. Headers h5 = {{"If-None-Match", etag},
  16530. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16531. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16532. ASSERT_TRUE(res5);
  16533. EXPECT_EQ(304, res5->status);
  16534. svr.stop();
  16535. t.join();
  16536. std::remove(fname);
  16537. }
  16538. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16539. using namespace httplib;
  16540. Server svr;
  16541. // Endpoint that returns compressible content
  16542. svr.Get("/compressible", [](const Request &, Response &res) {
  16543. // Return a large enough body to trigger compression
  16544. std::string body(1000, 'a');
  16545. res.set_content(body, "text/plain");
  16546. });
  16547. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16548. svr.wait_until_ready();
  16549. Client cli(HOST, PORT);
  16550. // Request with gzip support: should get Vary header when compressed
  16551. cli.set_compress(true);
  16552. auto res1 = cli.Get("/compressible");
  16553. ASSERT_TRUE(res1);
  16554. EXPECT_EQ(200, res1->status);
  16555. // If Content-Encoding is set, Vary should also be set
  16556. if (res1->has_header("Content-Encoding")) {
  16557. EXPECT_TRUE(res1->has_header("Vary"));
  16558. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16559. }
  16560. // Request without Accept-Encoding header: should not have compression
  16561. Headers h_no_compress;
  16562. auto res2 = cli.Get("/compressible", h_no_compress);
  16563. ASSERT_TRUE(res2);
  16564. EXPECT_EQ(200, res2->status);
  16565. // Verify Vary header is present when compression is applied
  16566. // (the exact behavior depends on server configuration)
  16567. svr.stop();
  16568. t.join();
  16569. }
  16570. TEST(ETagTest, IfRangeWithETag) {
  16571. using namespace httplib;
  16572. // Create a test file with known content
  16573. const char *fname = "if_range_testfile.txt";
  16574. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16575. {
  16576. std::ofstream ofs(fname);
  16577. ofs << content;
  16578. ASSERT_TRUE(ofs.good());
  16579. }
  16580. Server svr;
  16581. svr.set_mount_point("/static", ".");
  16582. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16583. svr.wait_until_ready();
  16584. Client cli(HOST, PORT);
  16585. // First request: get ETag
  16586. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16587. ASSERT_TRUE(res1);
  16588. ASSERT_EQ(200, res1->status);
  16589. ASSERT_TRUE(res1->has_header("ETag"));
  16590. std::string etag = res1->get_header_value("ETag");
  16591. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16592. // Since our server generates weak ETags (W/"..."), If-Range with our
  16593. // ETag should NOT result in partial content - it should return full content.
  16594. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16595. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16596. ASSERT_TRUE(res2);
  16597. // Weak ETag in If-Range -> full content (200), not partial (206)
  16598. EXPECT_EQ(200, res2->status);
  16599. EXPECT_EQ(content, res2->body);
  16600. EXPECT_FALSE(res2->has_header("Content-Range"));
  16601. // Range request with non-matching If-Range (ETag): should get 200 (full
  16602. // content)
  16603. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16604. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16605. ASSERT_TRUE(res3);
  16606. EXPECT_EQ(200, res3->status);
  16607. EXPECT_EQ(content, res3->body);
  16608. EXPECT_FALSE(res3->has_header("Content-Range"));
  16609. // Range request with strong ETag (hypothetical - our server doesn't generate
  16610. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16611. // should return full content)
  16612. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16613. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16614. ASSERT_TRUE(res4);
  16615. EXPECT_EQ(200, res4->status);
  16616. EXPECT_EQ(content, res4->body);
  16617. EXPECT_FALSE(res4->has_header("Content-Range"));
  16618. svr.stop();
  16619. t.join();
  16620. std::remove(fname);
  16621. }
  16622. TEST(ETagTest, IfRangeWithDate) {
  16623. using namespace httplib;
  16624. // Create a test file
  16625. const char *fname = "if_range_date_testfile.txt";
  16626. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16627. {
  16628. std::ofstream ofs(fname);
  16629. ofs << content;
  16630. ASSERT_TRUE(ofs.good());
  16631. }
  16632. Server svr;
  16633. svr.set_mount_point("/static", ".");
  16634. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16635. svr.wait_until_ready();
  16636. Client cli(HOST, PORT);
  16637. // First request: get Last-Modified
  16638. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16639. ASSERT_TRUE(res1);
  16640. ASSERT_EQ(200, res1->status);
  16641. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16642. std::string last_modified = res1->get_header_value("Last-Modified");
  16643. // Range request with matching If-Range (date): should get 206
  16644. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16645. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16646. ASSERT_TRUE(res2);
  16647. EXPECT_EQ(206, res2->status);
  16648. EXPECT_EQ("FGHIJ", res2->body);
  16649. // Range request with old If-Range date: should get 200 (full content)
  16650. Headers h3 = {{"Range", "bytes=5-9"},
  16651. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16652. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16653. ASSERT_TRUE(res3);
  16654. EXPECT_EQ(200, res3->status);
  16655. EXPECT_EQ(content, res3->body);
  16656. // Range request with future If-Range date: should get 206
  16657. Headers h4 = {{"Range", "bytes=0-4"},
  16658. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16659. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16660. ASSERT_TRUE(res4);
  16661. EXPECT_EQ(206, res4->status);
  16662. EXPECT_EQ("ABCDE", res4->body);
  16663. svr.stop();
  16664. t.join();
  16665. std::remove(fname);
  16666. }
  16667. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16668. using namespace httplib;
  16669. const char *fname = "etag_malformed.txt";
  16670. const char *content = "malformed-etag";
  16671. {
  16672. std::ofstream ofs(fname);
  16673. ofs << content;
  16674. ASSERT_TRUE(ofs.good());
  16675. }
  16676. Server svr;
  16677. svr.set_mount_point("/static", ".");
  16678. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16679. svr.wait_until_ready();
  16680. Client cli(HOST, PORT);
  16681. // baseline: should get 200 and an ETag
  16682. auto res1 = cli.Get("/static/etag_malformed.txt");
  16683. ASSERT_TRUE(res1);
  16684. ASSERT_EQ(200, res1->status);
  16685. ASSERT_TRUE(res1->has_header("ETag"));
  16686. // Malformed ETag value (missing quotes) should be treated as non-matching
  16687. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16688. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16689. ASSERT_TRUE(res_bad);
  16690. EXPECT_EQ(200, res_bad->status);
  16691. // Whitespace-only header value should be considered invalid / non-matching
  16692. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16693. "Host: localhost\r\n"
  16694. "If-None-Match: \r\n"
  16695. "Connection: close\r\n"
  16696. "\r\n";
  16697. std::string out;
  16698. ASSERT_TRUE(send_request(5, raw_req, &out));
  16699. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16700. svr.stop();
  16701. t.join();
  16702. std::remove(fname);
  16703. }
  16704. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16705. using namespace httplib;
  16706. const char *fname = "ims_invalid_format.txt";
  16707. const char *content = "ims-bad-format";
  16708. {
  16709. std::ofstream ofs(fname);
  16710. ofs << content;
  16711. ASSERT_TRUE(ofs.good());
  16712. }
  16713. Server svr;
  16714. svr.set_mount_point("/static", ".");
  16715. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16716. svr.wait_until_ready();
  16717. Client cli(HOST, PORT);
  16718. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16719. ASSERT_TRUE(res1);
  16720. ASSERT_EQ(200, res1->status);
  16721. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16722. // If-Modified-Since with invalid format should not result in 304
  16723. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16724. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16725. ASSERT_TRUE(res_bad);
  16726. EXPECT_EQ(200, res_bad->status);
  16727. // If-Range with invalid date format should be treated as mismatch -> full
  16728. // content (200)
  16729. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16730. {"If-Range", "invalid-date"}};
  16731. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16732. ASSERT_TRUE(res_ifrange);
  16733. EXPECT_EQ(200, res_ifrange->status);
  16734. svr.stop();
  16735. t.join();
  16736. std::remove(fname);
  16737. }
  16738. TEST(ETagTest, IfRangeWithMalformedETag) {
  16739. using namespace httplib;
  16740. const char *fname = "ifrange_malformed.txt";
  16741. const std::string content = "0123456789";
  16742. {
  16743. std::ofstream ofs(fname);
  16744. ofs << content;
  16745. ASSERT_TRUE(ofs.good());
  16746. }
  16747. Server svr;
  16748. svr.set_mount_point("/static", ".");
  16749. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16750. svr.wait_until_ready();
  16751. Client cli(HOST, PORT);
  16752. // First request: get ETag
  16753. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16754. ASSERT_TRUE(res1);
  16755. ASSERT_EQ(200, res1->status);
  16756. ASSERT_TRUE(res1->has_header("ETag"));
  16757. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16758. // full content (200)
  16759. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16760. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16761. ASSERT_TRUE(res2);
  16762. EXPECT_EQ(200, res2->status);
  16763. EXPECT_EQ(content, res2->body);
  16764. svr.stop();
  16765. t.join();
  16766. std::remove(fname);
  16767. }
  16768. TEST(ETagTest, ExtremeLargeDateValues) {
  16769. using namespace httplib;
  16770. const char *fname = "ims_extreme_date.txt";
  16771. const char *content = "ims-extreme-date";
  16772. {
  16773. std::ofstream ofs(fname);
  16774. ofs << content;
  16775. ASSERT_TRUE(ofs.good());
  16776. }
  16777. Server svr;
  16778. svr.set_mount_point("/static", ".");
  16779. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16780. svr.wait_until_ready();
  16781. Client cli(HOST, PORT);
  16782. auto res1 = cli.Get(std::string("/static/") + fname);
  16783. ASSERT_TRUE(res1);
  16784. ASSERT_EQ(200, res1->status);
  16785. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16786. // Extremely large year that may overflow date parsing routines.
  16787. Headers h_large_date = {
  16788. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16789. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16790. ASSERT_TRUE(res_bad);
  16791. // Expect server to treat this as invalid/mismatch and return full content
  16792. EXPECT_EQ(200, res_bad->status);
  16793. // If-Range with extremely large date should be treated as mismatch -> full
  16794. // content (200)
  16795. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16796. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16797. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16798. ASSERT_TRUE(res_ifrange);
  16799. EXPECT_EQ(200, res_ifrange->status);
  16800. svr.stop();
  16801. t.join();
  16802. std::remove(fname);
  16803. }
  16804. TEST(ETagTest, NegativeFileModificationTime) {
  16805. using namespace httplib;
  16806. const char *fname = "ims_negative_mtime.txt";
  16807. const std::string content = "negative-mtime";
  16808. {
  16809. std::ofstream ofs(fname);
  16810. ofs << content;
  16811. ASSERT_TRUE(ofs.good());
  16812. }
  16813. // Try to set file mtime to a negative value. This may fail on some
  16814. // platforms/filesystems; if it fails, the test will still verify server
  16815. // behaves safely by performing a regular conditional request.
  16816. #if defined(__APPLE__) || defined(__linux__)
  16817. bool set_negative = false;
  16818. do {
  16819. struct timeval times[2];
  16820. // access time: now
  16821. times[0].tv_sec = time(nullptr);
  16822. times[0].tv_usec = 0;
  16823. // modification time: negative (e.g., -1)
  16824. times[1].tv_sec = -1;
  16825. times[1].tv_usec = 0;
  16826. if (utimes(fname, times) == 0) { set_negative = true; }
  16827. } while (0);
  16828. #else
  16829. bool set_negative = false;
  16830. #endif
  16831. Server svr;
  16832. svr.set_mount_point("/static", ".");
  16833. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16834. svr.wait_until_ready();
  16835. Client cli(HOST, PORT);
  16836. auto res1 = cli.Get(std::string("/static/") + fname);
  16837. ASSERT_TRUE(res1);
  16838. ASSERT_EQ(200, res1->status);
  16839. bool has_last_modified = res1->has_header("Last-Modified");
  16840. std::string last_modified;
  16841. if (has_last_modified) {
  16842. last_modified = res1->get_header_value("Last-Modified");
  16843. }
  16844. if (set_negative) {
  16845. // If we successfully set a negative mtime, ensure server returns a
  16846. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16847. // with an old date and ensure server handles it without crash.
  16848. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16849. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16850. ASSERT_TRUE(res2);
  16851. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16852. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16853. } else {
  16854. // Could not set negative mtime on this platform; fall back to verifying
  16855. // that normal invalid/malformed dates are treated safely (non-304).
  16856. Headers h_bad_date = {
  16857. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16858. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16859. ASSERT_TRUE(res_bad);
  16860. EXPECT_EQ(200, res_bad->status);
  16861. }
  16862. svr.stop();
  16863. t.join();
  16864. std::remove(fname);
  16865. }
  16866. //==============================================================================
  16867. // SSE Parsing Tests
  16868. //==============================================================================
  16869. class SSEParsingTest : public ::testing::Test {
  16870. protected:
  16871. // Test helper that mimics SSE parsing behavior
  16872. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16873. int &retry_ms) {
  16874. // Blank line signals end of event
  16875. if (line.empty() || line == "\r") { return true; }
  16876. // Lines starting with ':' are comments (ignored)
  16877. if (!line.empty() && line[0] == ':') { return false; }
  16878. // Find the colon separator
  16879. auto colon_pos = line.find(':');
  16880. if (colon_pos == std::string::npos) {
  16881. // Line with no colon is treated as field name with empty value
  16882. return false;
  16883. }
  16884. std::string field = line.substr(0, colon_pos);
  16885. std::string value;
  16886. // Value starts after colon, skip optional single space
  16887. if (colon_pos + 1 < line.size()) {
  16888. size_t value_start = colon_pos + 1;
  16889. if (line[value_start] == ' ') { value_start++; }
  16890. value = line.substr(value_start);
  16891. // Remove trailing \r if present
  16892. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16893. }
  16894. // Handle known fields
  16895. if (field == "event") {
  16896. msg.event = value;
  16897. } else if (field == "data") {
  16898. // Multiple data lines are concatenated with newlines
  16899. if (!msg.data.empty()) { msg.data += "\n"; }
  16900. msg.data += value;
  16901. } else if (field == "id") {
  16902. // Empty id is valid (clears the last event ID)
  16903. msg.id = value;
  16904. } else if (field == "retry") {
  16905. // Parse retry interval in milliseconds
  16906. {
  16907. int v = 0;
  16908. auto res =
  16909. detail::from_chars(value.data(), value.data() + value.size(), v);
  16910. if (res.ec == std::errc{}) { retry_ms = v; }
  16911. }
  16912. }
  16913. // Unknown fields are ignored per SSE spec
  16914. return false;
  16915. }
  16916. };
  16917. // Test: Single-line data
  16918. TEST_F(SSEParsingTest, SingleLineData) {
  16919. sse::SSEMessage msg;
  16920. int retry_ms = 3000;
  16921. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16922. EXPECT_EQ(msg.data, "hello");
  16923. EXPECT_EQ(msg.event, "message");
  16924. // Blank line ends event
  16925. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16926. }
  16927. // Test: Multi-line data
  16928. TEST_F(SSEParsingTest, MultiLineData) {
  16929. sse::SSEMessage msg;
  16930. int retry_ms = 3000;
  16931. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16932. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16933. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16934. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16935. }
  16936. // Test: Custom event types
  16937. TEST_F(SSEParsingTest, CustomEventType) {
  16938. sse::SSEMessage msg;
  16939. int retry_ms = 3000;
  16940. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16941. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16942. EXPECT_EQ(msg.event, "update");
  16943. EXPECT_EQ(msg.data, "payload");
  16944. }
  16945. // Test: Event ID handling
  16946. TEST_F(SSEParsingTest, EventIdHandling) {
  16947. sse::SSEMessage msg;
  16948. int retry_ms = 3000;
  16949. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16950. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16951. EXPECT_EQ(msg.id, "12345");
  16952. }
  16953. // Test: Empty event ID (clears last event ID)
  16954. TEST_F(SSEParsingTest, EmptyEventId) {
  16955. sse::SSEMessage msg;
  16956. msg.id = "previous";
  16957. int retry_ms = 3000;
  16958. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16959. EXPECT_EQ(msg.id, "");
  16960. }
  16961. // Test: Retry field parsing
  16962. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16963. sse::SSEMessage msg;
  16964. int retry_ms = 3000;
  16965. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16966. EXPECT_EQ(retry_ms, 5000);
  16967. }
  16968. // Test: Invalid retry value
  16969. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16970. sse::SSEMessage msg;
  16971. int retry_ms = 3000;
  16972. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16973. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16974. }
  16975. // Test: Comments (lines starting with :)
  16976. TEST_F(SSEParsingTest, CommentsIgnored) {
  16977. sse::SSEMessage msg;
  16978. int retry_ms = 3000;
  16979. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16980. EXPECT_EQ(msg.data, "");
  16981. EXPECT_EQ(msg.event, "message");
  16982. }
  16983. // Test: Colon in value
  16984. TEST_F(SSEParsingTest, ColonInValue) {
  16985. sse::SSEMessage msg;
  16986. int retry_ms = 3000;
  16987. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16988. EXPECT_EQ(msg.data, "hello:world:test");
  16989. }
  16990. // Test: Line with no colon (field name only)
  16991. TEST_F(SSEParsingTest, FieldNameOnly) {
  16992. sse::SSEMessage msg;
  16993. int retry_ms = 3000;
  16994. // According to SSE spec, this is treated as field name with empty value
  16995. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16996. // Since we don't recognize "data" without colon, data should be empty
  16997. EXPECT_EQ(msg.data, "");
  16998. }
  16999. // Test: Trailing \r handling
  17000. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17001. sse::SSEMessage msg;
  17002. int retry_ms = 3000;
  17003. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17004. EXPECT_EQ(msg.data, "hello");
  17005. }
  17006. // Test: Unknown fields ignored
  17007. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17008. sse::SSEMessage msg;
  17009. int retry_ms = 3000;
  17010. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17011. EXPECT_EQ(msg.data, "");
  17012. EXPECT_EQ(msg.event, "message");
  17013. }
  17014. // Test: Space after colon is optional
  17015. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17016. sse::SSEMessage msg1, msg2;
  17017. int retry_ms = 3000;
  17018. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17019. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17020. EXPECT_EQ(msg1.data, "hello");
  17021. EXPECT_EQ(msg2.data, "hello");
  17022. }
  17023. // Test: SSEMessage clear
  17024. TEST_F(SSEParsingTest, MessageClear) {
  17025. sse::SSEMessage msg;
  17026. msg.event = "custom";
  17027. msg.data = "some data";
  17028. msg.id = "123";
  17029. msg.clear();
  17030. EXPECT_EQ(msg.event, "message");
  17031. EXPECT_EQ(msg.data, "");
  17032. EXPECT_EQ(msg.id, "");
  17033. }
  17034. // Test: Complete event parsing
  17035. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17036. sse::SSEMessage msg;
  17037. int retry_ms = 3000;
  17038. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17039. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17040. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17041. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17042. // Blank line ends event
  17043. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17044. EXPECT_EQ(msg.event, "notification");
  17045. EXPECT_EQ(msg.id, "evt-42");
  17046. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17047. EXPECT_EQ(retry_ms, 1000);
  17048. }
  17049. //==============================================================================
  17050. // Integration Tests with Server
  17051. //==============================================================================
  17052. class SSEIntegrationTest : public ::testing::Test {
  17053. protected:
  17054. void SetUp() override {
  17055. stop_server_.store(false);
  17056. events_.clear();
  17057. server_ = httplib::detail::make_unique<Server>();
  17058. setup_server();
  17059. start_server();
  17060. }
  17061. void TearDown() override {
  17062. stop_server_.store(true);
  17063. event_cv_.notify_all();
  17064. server_->stop();
  17065. if (server_thread_.joinable()) { server_thread_.join(); }
  17066. }
  17067. void setup_server() {
  17068. // Simple SSE endpoint
  17069. server_->Get("/events", [this](const Request &req, Response &res) {
  17070. auto last_id = req.get_header_value("Last-Event-ID");
  17071. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17072. res.set_chunked_content_provider(
  17073. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17074. std::unique_lock<std::mutex> lock(event_mutex_);
  17075. if (event_cv_.wait_for(
  17076. lock, std::chrono::milliseconds(200), [this] {
  17077. return !events_.empty() || stop_server_.load();
  17078. })) {
  17079. if (stop_server_.load()) { return false; }
  17080. if (!events_.empty()) {
  17081. std::string event = events_.front();
  17082. events_.erase(events_.begin());
  17083. sink.write(event.data(), event.size());
  17084. return true;
  17085. }
  17086. }
  17087. return !stop_server_.load();
  17088. });
  17089. });
  17090. // Endpoint that returns error
  17091. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17092. res.status = 500;
  17093. res.set_content("Internal Server Error", "text/plain");
  17094. });
  17095. // Endpoint for custom event types
  17096. server_->Get("/custom-events", [](const Request &, Response &res) {
  17097. res.set_chunked_content_provider(
  17098. "text/event-stream", [](size_t offset, DataSink &sink) {
  17099. if (offset == 0) {
  17100. std::string event = "event: update\ndata: updated\n\n"
  17101. "event: delete\ndata: deleted\n\n";
  17102. sink.write(event.data(), event.size());
  17103. }
  17104. return false; // End stream after sending
  17105. });
  17106. });
  17107. }
  17108. void start_server() {
  17109. port_ = server_->bind_to_any_port(HOST);
  17110. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17111. // Wait for server to start
  17112. while (!server_->is_running()) {
  17113. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17114. }
  17115. }
  17116. int get_port() const { return port_; }
  17117. void send_event(const std::string &event) {
  17118. std::lock_guard<std::mutex> lock(event_mutex_);
  17119. events_.push_back(event);
  17120. event_cv_.notify_all();
  17121. }
  17122. std::unique_ptr<Server> server_;
  17123. std::thread server_thread_;
  17124. std::mutex event_mutex_;
  17125. std::condition_variable event_cv_;
  17126. std::vector<std::string> events_;
  17127. std::atomic<bool> stop_server_{false};
  17128. std::string last_received_event_id_;
  17129. int port_ = 0;
  17130. };
  17131. // Test: Successful connection and on_open callback
  17132. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17133. // Add a simple endpoint that sends one event and closes
  17134. server_->Get("/simple-event", [](const Request &, Response &res) {
  17135. res.set_chunked_content_provider(
  17136. "text/event-stream", [](size_t offset, DataSink &sink) {
  17137. if (offset == 0) {
  17138. std::string event = "data: hello\n\n";
  17139. sink.write(event.data(), event.size());
  17140. }
  17141. return false; // Close stream after sending
  17142. });
  17143. });
  17144. Client client("localhost", get_port());
  17145. sse::SSEClient sse(client, "/simple-event");
  17146. std::atomic<bool> open_called{false};
  17147. std::atomic<bool> message_received{false};
  17148. sse.on_open([&open_called]() { open_called.store(true); });
  17149. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17150. if (msg.data == "hello") { message_received.store(true); }
  17151. });
  17152. sse.set_reconnect_interval(100);
  17153. sse.set_max_reconnect_attempts(1);
  17154. // Start async
  17155. sse.start_async();
  17156. // Wait for message to be processed
  17157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17158. sse.stop();
  17159. EXPECT_TRUE(open_called.load());
  17160. EXPECT_TRUE(message_received.load());
  17161. }
  17162. // Test: on_message callback
  17163. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17164. // Endpoint that sends multiple events then closes
  17165. server_->Get("/multi-event", [](const Request &, Response &res) {
  17166. res.set_chunked_content_provider(
  17167. "text/event-stream", [](size_t offset, DataSink &sink) {
  17168. if (offset == 0) {
  17169. std::string events = "data: message1\n\ndata: message2\n\n";
  17170. sink.write(events.data(), events.size());
  17171. }
  17172. return false;
  17173. });
  17174. });
  17175. Client client("localhost", get_port());
  17176. sse::SSEClient sse(client, "/multi-event");
  17177. std::vector<std::string> received_messages;
  17178. std::mutex messages_mutex;
  17179. sse.on_message([&](const sse::SSEMessage &msg) {
  17180. std::lock_guard<std::mutex> lock(messages_mutex);
  17181. received_messages.push_back(msg.data);
  17182. });
  17183. sse.set_reconnect_interval(100);
  17184. sse.set_max_reconnect_attempts(1);
  17185. sse.start_async();
  17186. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17187. sse.stop();
  17188. std::lock_guard<std::mutex> lock(messages_mutex);
  17189. EXPECT_GE(received_messages.size(), 2u);
  17190. if (received_messages.size() >= 2) {
  17191. EXPECT_EQ(received_messages[0], "message1");
  17192. EXPECT_EQ(received_messages[1], "message2");
  17193. }
  17194. }
  17195. // Test: on_event for specific types
  17196. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17197. Client client("localhost", get_port());
  17198. sse::SSEClient sse(client, "/custom-events");
  17199. std::atomic<bool> update_received{false};
  17200. std::atomic<bool> delete_received{false};
  17201. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17202. if (msg.data == "updated") { update_received.store(true); }
  17203. });
  17204. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17205. if (msg.data == "deleted") { delete_received.store(true); }
  17206. });
  17207. sse.set_max_reconnect_attempts(1);
  17208. sse.start_async();
  17209. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17210. sse.stop();
  17211. EXPECT_TRUE(update_received.load());
  17212. EXPECT_TRUE(delete_received.load());
  17213. }
  17214. // Test: on_error callback on connection failure
  17215. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17216. // Connect to a non-existent port
  17217. Client client("localhost", 59999);
  17218. sse::SSEClient sse(client, "/events");
  17219. std::atomic<bool> error_called{false};
  17220. Error received_error = Error::Success;
  17221. sse.on_error([&](Error err) {
  17222. error_called.store(true);
  17223. received_error = err;
  17224. });
  17225. sse.set_reconnect_interval(50);
  17226. sse.set_max_reconnect_attempts(1);
  17227. sse.start_async();
  17228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17229. sse.stop();
  17230. EXPECT_TRUE(error_called.load());
  17231. EXPECT_NE(received_error, Error::Success);
  17232. }
  17233. // Test: Last-Event-ID header sent on reconnect
  17234. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17235. // Endpoint that sends event with ID
  17236. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17237. res.set_chunked_content_provider(
  17238. "text/event-stream", [](size_t offset, DataSink &sink) {
  17239. if (offset == 0) {
  17240. std::string event = "id: evt-123\ndata: test\n\n";
  17241. sink.write(event.data(), event.size());
  17242. }
  17243. return false;
  17244. });
  17245. });
  17246. Client client("localhost", get_port());
  17247. sse::SSEClient sse(client, "/event-with-id");
  17248. std::atomic<bool> id_received{false};
  17249. sse.on_message([&](const sse::SSEMessage &msg) {
  17250. if (!msg.id.empty()) { id_received.store(true); }
  17251. });
  17252. sse.set_reconnect_interval(100);
  17253. sse.set_max_reconnect_attempts(1);
  17254. sse.start_async();
  17255. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17256. sse.stop();
  17257. EXPECT_TRUE(id_received.load());
  17258. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17259. }
  17260. // Test: Manual stop
  17261. TEST_F(SSEIntegrationTest, ManualStop) {
  17262. // Endpoint that sends one event and stays open briefly
  17263. std::atomic<bool> handler_running{true};
  17264. server_->Get("/stay-open", [&handler_running](const Request &,
  17265. Response &res) {
  17266. res.set_chunked_content_provider(
  17267. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17268. if (offset == 0) {
  17269. std::string event = "data: connected\n\n";
  17270. sink.write(event.data(), event.size());
  17271. }
  17272. // Keep connection open while handler_running is true
  17273. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17274. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17275. }
  17276. return false;
  17277. });
  17278. });
  17279. Client client("localhost", get_port());
  17280. sse::SSEClient sse(client, "/stay-open");
  17281. std::atomic<bool> connected{false};
  17282. sse.on_open([&connected]() { connected.store(true); });
  17283. sse.set_reconnect_interval(100);
  17284. sse.set_max_reconnect_attempts(1);
  17285. sse.start_async();
  17286. // Wait for connection to establish
  17287. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17288. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17289. }
  17290. EXPECT_TRUE(connected.load());
  17291. EXPECT_TRUE(sse.is_connected());
  17292. // Signal handler to stop
  17293. handler_running.store(false);
  17294. // Stop SSE client
  17295. sse.stop();
  17296. EXPECT_FALSE(sse.is_connected());
  17297. }
  17298. // Test: SSEClient with custom headers
  17299. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17300. // Setup a server endpoint that checks for custom header
  17301. std::atomic<bool> header_received{false};
  17302. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17303. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17304. header_received.store(true);
  17305. }
  17306. res.set_chunked_content_provider("text/event-stream",
  17307. [](size_t, DataSink &) { return false; });
  17308. });
  17309. Client client("localhost", get_port());
  17310. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17311. sse::SSEClient sse(client, "/header-check", headers);
  17312. sse.set_max_reconnect_attempts(1);
  17313. sse.start_async();
  17314. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17315. sse.stop();
  17316. EXPECT_TRUE(header_received.load());
  17317. }
  17318. // Test: Reconnect interval configuration
  17319. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17320. Client client("localhost", get_port());
  17321. sse::SSEClient sse(client, "/events");
  17322. auto &result = sse.set_reconnect_interval(500);
  17323. // Builder pattern should return reference to self
  17324. EXPECT_EQ(&result, &sse);
  17325. }
  17326. // Test: Max reconnect attempts
  17327. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17328. // Connect to non-existent port to force reconnects
  17329. Client client("localhost", 59998);
  17330. sse::SSEClient sse(client, "/events");
  17331. std::atomic<int> error_count{0};
  17332. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17333. sse.set_reconnect_interval(50);
  17334. sse.set_max_reconnect_attempts(2);
  17335. auto start = std::chrono::steady_clock::now();
  17336. sse.start(); // Blocking call
  17337. auto end = std::chrono::steady_clock::now();
  17338. // Should have stopped after 2 failed attempts
  17339. EXPECT_GE(error_count.load(), 2);
  17340. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17341. auto duration =
  17342. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17343. #ifdef _WIN32
  17344. // Windows is much slower for socket connection failures
  17345. EXPECT_LT(duration.count(), 7000);
  17346. #else
  17347. EXPECT_LT(duration.count(), 1000);
  17348. #endif
  17349. }
  17350. // Test: Multi-line data in integration
  17351. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17352. // Endpoint with multi-line data
  17353. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17354. res.set_chunked_content_provider(
  17355. "text/event-stream", [](size_t offset, DataSink &sink) {
  17356. if (offset == 0) {
  17357. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17358. sink.write(event.data(), event.size());
  17359. }
  17360. return false;
  17361. });
  17362. });
  17363. Client client("localhost", get_port());
  17364. sse::SSEClient sse(client, "/multiline-data");
  17365. std::string received_data;
  17366. std::mutex data_mutex;
  17367. sse.on_message([&](const sse::SSEMessage &msg) {
  17368. std::lock_guard<std::mutex> lock(data_mutex);
  17369. received_data = msg.data;
  17370. });
  17371. sse.set_reconnect_interval(100);
  17372. sse.set_max_reconnect_attempts(1);
  17373. sse.start_async();
  17374. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17375. sse.stop();
  17376. std::lock_guard<std::mutex> lock(data_mutex);
  17377. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17378. }
  17379. // Test: Auto-reconnect after server disconnection
  17380. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17381. std::atomic<int> connection_count{0};
  17382. std::atomic<int> message_count{0};
  17383. // Endpoint that sends one event and closes, forcing reconnect
  17384. server_->Get("/reconnect-test",
  17385. [&connection_count](const Request &, Response &res) {
  17386. connection_count.fetch_add(1);
  17387. res.set_chunked_content_provider(
  17388. "text/event-stream", [](size_t offset, DataSink &sink) {
  17389. if (offset == 0) {
  17390. std::string event = "data: hello\n\n";
  17391. sink.write(event.data(), event.size());
  17392. }
  17393. return false; // Close connection after sending
  17394. });
  17395. });
  17396. Client client("localhost", get_port());
  17397. sse::SSEClient sse(client, "/reconnect-test");
  17398. sse.on_message([&message_count](const sse::SSEMessage &) {
  17399. message_count.fetch_add(1);
  17400. });
  17401. sse.set_reconnect_interval(100);
  17402. sse.set_max_reconnect_attempts(3);
  17403. sse.start_async();
  17404. // Wait long enough for multiple reconnects
  17405. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17406. sse.stop();
  17407. // Should have connected multiple times (initial + reconnects)
  17408. EXPECT_GE(connection_count.load(), 2);
  17409. // Should have received messages from multiple connections
  17410. EXPECT_GE(message_count.load(), 2);
  17411. }
  17412. // Test: Last-Event-ID sent on reconnect
  17413. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17414. std::atomic<int> connection_count{0};
  17415. std::vector<std::string> received_last_event_ids;
  17416. std::mutex id_mutex;
  17417. // Endpoint that checks Last-Event-ID header and sends event with ID
  17418. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17419. int conn = connection_count.fetch_add(1);
  17420. // Capture the Last-Event-ID header from each connection
  17421. {
  17422. std::lock_guard<std::mutex> lock(id_mutex);
  17423. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17424. }
  17425. res.set_chunked_content_provider(
  17426. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17427. if (offset == 0) {
  17428. std::string event =
  17429. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17430. sink.write(event.data(), event.size());
  17431. }
  17432. return false;
  17433. });
  17434. });
  17435. Client client("localhost", get_port());
  17436. sse::SSEClient sse(client, "/reconnect-with-id");
  17437. sse.set_reconnect_interval(100);
  17438. sse.set_max_reconnect_attempts(3);
  17439. sse.start_async();
  17440. // Wait for at least 2 connections
  17441. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17442. sse.stop();
  17443. // Verify behavior
  17444. std::lock_guard<std::mutex> lock(id_mutex);
  17445. EXPECT_GE(received_last_event_ids.size(), 2u);
  17446. // First connection should have no Last-Event-ID
  17447. if (!received_last_event_ids.empty()) {
  17448. EXPECT_EQ(received_last_event_ids[0], "");
  17449. }
  17450. // Second connection should have Last-Event-ID from first connection
  17451. if (received_last_event_ids.size() >= 2) {
  17452. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17453. }
  17454. }
  17455. // Test: set_headers updates headers used on reconnect
  17456. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17457. std::vector<std::string> received_tokens;
  17458. std::mutex token_mutex;
  17459. // Endpoint that captures Authorization header
  17460. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17461. {
  17462. std::lock_guard<std::mutex> lock(token_mutex);
  17463. received_tokens.push_back(req.get_header_value("Authorization"));
  17464. }
  17465. res.set_chunked_content_provider(
  17466. "text/event-stream", [](size_t offset, DataSink &sink) {
  17467. if (offset == 0) {
  17468. std::string event = "data: hello\n\n";
  17469. sink.write(event.data(), event.size());
  17470. }
  17471. return false; // Close connection to trigger reconnect
  17472. });
  17473. });
  17474. Client client("localhost", get_port());
  17475. Headers headers = {{"Authorization", "Bearer old-token"}};
  17476. sse::SSEClient sse(client, "/auth-check", headers);
  17477. // Update headers on each successful connection
  17478. sse.on_open(
  17479. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17480. sse.set_reconnect_interval(100);
  17481. sse.set_max_reconnect_attempts(3);
  17482. sse.start_async();
  17483. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17484. sse.stop();
  17485. std::lock_guard<std::mutex> lock(token_mutex);
  17486. ASSERT_GE(received_tokens.size(), 2u);
  17487. // First connection uses original header
  17488. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17489. // Second connection uses updated header from set_headers
  17490. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17491. }
  17492. // Test: 401 allows reconnection (so on_error can refresh headers)
  17493. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17494. std::atomic<int> connection_count{0};
  17495. // Endpoint: returns 401 on first attempt, 200 on second
  17496. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17497. int conn = connection_count.fetch_add(1);
  17498. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17499. res.status = StatusCode::Unauthorized_401;
  17500. res.set_content("Unauthorized", "text/plain");
  17501. return;
  17502. }
  17503. res.set_chunked_content_provider(
  17504. "text/event-stream", [](size_t offset, DataSink &sink) {
  17505. if (offset == 0) {
  17506. std::string event = "data: authenticated\n\n";
  17507. sink.write(event.data(), event.size());
  17508. }
  17509. return false;
  17510. });
  17511. });
  17512. Client client("localhost", get_port());
  17513. Headers headers = {{"Authorization", "Bearer expired"}};
  17514. sse::SSEClient sse(client, "/auth-retry", headers);
  17515. std::atomic<bool> message_received{false};
  17516. // Refresh token on error
  17517. sse.on_error(
  17518. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17519. sse.on_message([&](const sse::SSEMessage &msg) {
  17520. if (msg.data == "authenticated") { message_received.store(true); }
  17521. });
  17522. sse.set_reconnect_interval(100);
  17523. sse.set_max_reconnect_attempts(3);
  17524. sse.start_async();
  17525. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17526. sse.stop();
  17527. // Should have reconnected after 401 and succeeded with new token
  17528. EXPECT_GE(connection_count.load(), 2);
  17529. EXPECT_TRUE(message_received.load());
  17530. }
  17531. TEST(Issue2318Test, EmptyHostString) {
  17532. {
  17533. httplib::Client cli_empty("", PORT);
  17534. auto res = cli_empty.Get("/");
  17535. ASSERT_FALSE(res);
  17536. EXPECT_EQ(httplib::Error::Connection, res.error());
  17537. }
  17538. {
  17539. httplib::Client cli(" ", PORT);
  17540. auto res = cli.Get("/");
  17541. ASSERT_FALSE(res);
  17542. EXPECT_EQ(httplib::Error::Connection, res.error());
  17543. }
  17544. }
  17545. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17546. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17547. Server svr;
  17548. // Set a small payload limit (1KB)
  17549. svr.set_payload_max_length(1024);
  17550. svr.Post("/test", [&](const Request &req, Response &res) {
  17551. res.set_content("Body size: " + std::to_string(req.body.size()),
  17552. "text/plain");
  17553. });
  17554. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17555. auto se = detail::scope_exit([&] {
  17556. svr.stop();
  17557. listen_thread.join();
  17558. });
  17559. svr.wait_until_ready();
  17560. // Create data that compresses well but exceeds limit when decompressed
  17561. // 8KB of repeated null bytes compresses to a very small size
  17562. std::string original_data(8 * 1024, '\0');
  17563. // Compress the data using gzip
  17564. std::string compressed_data;
  17565. detail::gzip_compressor compressor;
  17566. compressor.compress(original_data.data(), original_data.size(), true,
  17567. [&](const char *data, size_t size) {
  17568. compressed_data.append(data, size);
  17569. return true;
  17570. });
  17571. // Verify compression worked (compressed should be much smaller)
  17572. ASSERT_LT(compressed_data.size(), original_data.size());
  17573. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17574. // Send compressed data with Content-Encoding: gzip
  17575. Client cli(HOST, PORT);
  17576. Headers headers = {{"Content-Encoding", "gzip"}};
  17577. auto res =
  17578. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17579. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17581. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17582. }
  17583. #endif
  17584. // ============================================================================
  17585. // OpenSSL-Specific Tests
  17586. // ============================================================================
  17587. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17588. X509 *readCertificate(const std::string &strFileName) {
  17589. std::ifstream inStream(strFileName);
  17590. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17591. std::istreambuf_iterator<char>());
  17592. if (strCertPEM.empty()) return (nullptr);
  17593. BIO *pbCert = BIO_new(BIO_s_mem());
  17594. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17595. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17596. BIO_free(pbCert);
  17597. return (pCert);
  17598. }
  17599. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17600. std::ifstream inStream(strFileName);
  17601. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17602. std::istreambuf_iterator<char>());
  17603. if (strPrivateKeyPEM.empty()) return (nullptr);
  17604. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17605. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17606. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17607. BIO_free(pbPrivKey);
  17608. return (pPrivateKey);
  17609. }
  17610. TEST(BindServerTest, UpdateCerts) {
  17611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17612. int port = svr.bind_to_any_port("0.0.0.0");
  17613. ASSERT_TRUE(svr.is_valid());
  17614. ASSERT_TRUE(port > 0);
  17615. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17616. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17617. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17618. ASSERT_TRUE(cert != nullptr);
  17619. ASSERT_TRUE(ca_cert != nullptr);
  17620. ASSERT_TRUE(key != nullptr);
  17621. X509_STORE *cert_store = X509_STORE_new();
  17622. X509_STORE_add_cert(cert_store, ca_cert);
  17623. // svr.update_certs(cert, key, cert_store); // deprecated
  17624. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17625. CLIENT_CA_CERT_FILE);
  17626. ASSERT_TRUE(svr.is_valid());
  17627. svr.stop();
  17628. X509_STORE_free(cert_store);
  17629. X509_free(cert);
  17630. X509_free(ca_cert);
  17631. EVP_PKEY_free(key);
  17632. }
  17633. // Test that update_certs() updates client CA list correctly
  17634. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17635. // Start with file-based constructor
  17636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17637. ASSERT_TRUE(svr.is_valid());
  17638. // Initially no client CA list should be set
  17639. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17640. ASSERT_TRUE(ssl_ctx != nullptr);
  17641. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17642. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17643. EXPECT_EQ(0, count_before);
  17644. // Now update with client CA (PEM string)
  17645. std::string cert_pem, key_pem, ca_pem;
  17646. read_file(SERVER_CERT_FILE, cert_pem);
  17647. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17648. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17649. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17650. ASSERT_TRUE(svr.is_valid());
  17651. // Now client CA list should be set
  17652. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17653. ASSERT_TRUE(ca_list_after != nullptr);
  17654. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17655. }
  17656. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17657. // Test that the file-path SSLServer constructor properly sets the client CA
  17658. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17660. ASSERT_TRUE(svr.is_valid());
  17661. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17662. ASSERT_TRUE(ssl_ctx != nullptr);
  17663. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17664. ASSERT_TRUE(ca_list != nullptr);
  17665. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17666. }
  17667. #endif
  17668. // ============================================================================
  17669. // MbedTLS-Specific Tests
  17670. // ============================================================================
  17671. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17672. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17673. using namespace httplib::tls;
  17674. // Track if callback was invoked
  17675. bool callback_invoked = false;
  17676. // The callback receives void* ctx which is actually MbedTlsContext*
  17677. // We can access the mbedtls_ssl_config via the context
  17678. auto setup_callback = [&callback_invoked](void *ctx) {
  17679. callback_invoked = true;
  17680. // Cast to MbedTlsContext* to access the ssl config
  17681. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17682. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17683. // Use static variables to hold certificate data (simplified for test)
  17684. static mbedtls_x509_crt own_cert;
  17685. static mbedtls_pk_context own_key;
  17686. static mbedtls_x509_crt ca_chain;
  17687. static bool initialized = false;
  17688. if (!initialized) {
  17689. mbedtls_x509_crt_init(&own_cert);
  17690. mbedtls_pk_init(&own_key);
  17691. mbedtls_x509_crt_init(&ca_chain);
  17692. // Load server certificate
  17693. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17694. return false;
  17695. }
  17696. // Load server private key.
  17697. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17698. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17699. #if MBEDTLS_VERSION_MAJOR == 3
  17700. ,
  17701. mbedtls_ctr_drbg_random, nullptr
  17702. #endif
  17703. ) != 0) {
  17704. return false;
  17705. }
  17706. // Load CA chain for client verification
  17707. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17708. return false;
  17709. }
  17710. initialized = true;
  17711. }
  17712. // Configure the SSL config
  17713. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17714. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17715. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17716. // Set minimum TLS version using mbedTLS native API
  17717. #if MBEDTLS_VERSION_MAJOR >= 3
  17718. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17719. #else
  17720. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17721. MBEDTLS_SSL_MINOR_VERSION_3);
  17722. #endif
  17723. return true;
  17724. };
  17725. SSLServer svr(setup_callback);
  17726. ASSERT_TRUE(svr.is_valid());
  17727. ASSERT_TRUE(callback_invoked);
  17728. svr.Get("/test", [&](const Request &req, Response &res) {
  17729. res.set_content("test", "text/plain");
  17730. auto cert = req.peer_cert();
  17731. ASSERT_TRUE(static_cast<bool>(cert));
  17732. auto common_name = cert.subject_cn();
  17733. EXPECT_EQ("Common Name", common_name);
  17734. });
  17735. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17736. auto se = detail::scope_exit([&] {
  17737. svr.stop();
  17738. t.join();
  17739. ASSERT_FALSE(svr.is_running());
  17740. });
  17741. svr.wait_until_ready();
  17742. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17743. cli.enable_server_certificate_verification(false);
  17744. cli.set_connection_timeout(30);
  17745. auto res = cli.Get("/test");
  17746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17747. ASSERT_EQ(StatusCode::OK_200, res->status);
  17748. }
  17749. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17750. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17751. // keep-alive SSL session, which reads through that config in
  17752. // mbedtls_ssl_close_notify.
  17753. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17755. ASSERT_TRUE(svr.is_valid());
  17756. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17757. res.set_content("test", "text/plain");
  17758. });
  17759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17760. auto se = detail::scope_exit([&] {
  17761. svr.stop();
  17762. t.join();
  17763. ASSERT_FALSE(svr.is_running());
  17764. });
  17765. svr.wait_until_ready();
  17766. {
  17767. SSLClient cli(HOST, PORT);
  17768. cli.enable_server_certificate_verification(false);
  17769. cli.set_keep_alive(true);
  17770. auto res = cli.Get("/test");
  17771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17772. ASSERT_EQ(StatusCode::OK_200, res->status);
  17773. // cli is destructed here with the keep-alive SSL session still open.
  17774. }
  17775. }
  17776. #endif
  17777. // WebSocket Tests
  17778. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17779. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17780. // defining the meaning of these bits has been negotiated.
  17781. auto make_frame = [](uint8_t first_byte) {
  17782. std::string frame;
  17783. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17784. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17785. frame += "Hello";
  17786. return frame;
  17787. };
  17788. // RSV1 set (0x40)
  17789. {
  17790. detail::BufferStream strm;
  17791. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17792. ws::Opcode opcode;
  17793. std::string payload;
  17794. bool fin;
  17795. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17796. false, 1024));
  17797. }
  17798. // RSV2 set (0x20)
  17799. {
  17800. detail::BufferStream strm;
  17801. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17802. ws::Opcode opcode;
  17803. std::string payload;
  17804. bool fin;
  17805. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17806. false, 1024));
  17807. }
  17808. // RSV3 set (0x10)
  17809. {
  17810. detail::BufferStream strm;
  17811. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17812. ws::Opcode opcode;
  17813. std::string payload;
  17814. bool fin;
  17815. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17816. false, 1024));
  17817. }
  17818. // No RSV bits set - should succeed
  17819. {
  17820. detail::BufferStream strm;
  17821. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17822. ws::Opcode opcode;
  17823. std::string payload;
  17824. bool fin;
  17825. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17826. false, 1024));
  17827. EXPECT_EQ(ws::Opcode::Text, opcode);
  17828. EXPECT_EQ("Hello", payload);
  17829. EXPECT_TRUE(fin);
  17830. }
  17831. }
  17832. TEST(WebSocketTest, ControlFrameValidation) {
  17833. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17834. // payload length <= 125.
  17835. // Ping with FIN=0 - must be rejected
  17836. {
  17837. detail::BufferStream strm;
  17838. std::string frame;
  17839. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17840. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17841. strm.write(frame.data(), frame.size());
  17842. ws::Opcode opcode;
  17843. std::string payload;
  17844. bool fin;
  17845. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17846. false, 1024));
  17847. }
  17848. // Close with FIN=0 - must be rejected
  17849. {
  17850. detail::BufferStream strm;
  17851. std::string frame;
  17852. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17853. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17854. strm.write(frame.data(), frame.size());
  17855. ws::Opcode opcode;
  17856. std::string payload;
  17857. bool fin;
  17858. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17859. false, 1024));
  17860. }
  17861. // Ping with payload_len=126 (extended length) - must be rejected
  17862. {
  17863. detail::BufferStream strm;
  17864. std::string frame;
  17865. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17866. frame += static_cast<char>(126); // payload_len=126 (>125)
  17867. frame += static_cast<char>(0x00); // extended length high byte
  17868. frame += static_cast<char>(126); // extended length low byte
  17869. frame += std::string(126, 'x');
  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. // Ping with FIN=1 and payload_len=125 - should succeed
  17878. {
  17879. detail::BufferStream strm;
  17880. std::string frame;
  17881. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17882. frame += static_cast<char>(125); // payload_len=125
  17883. frame += std::string(125, 'x');
  17884. strm.write(frame.data(), frame.size());
  17885. ws::Opcode opcode;
  17886. std::string payload;
  17887. bool fin;
  17888. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17889. false, 1024));
  17890. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17891. EXPECT_EQ(125u, payload.size());
  17892. EXPECT_TRUE(fin);
  17893. }
  17894. }
  17895. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17896. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17897. // length MUST be 0.
  17898. // MSB set - must be rejected
  17899. {
  17900. detail::BufferStream strm;
  17901. std::string frame;
  17902. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17903. frame += static_cast<char>(127); // 64-bit extended length
  17904. frame += static_cast<char>(0x80); // MSB set (invalid)
  17905. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17906. strm.write(frame.data(), frame.size());
  17907. ws::Opcode opcode;
  17908. std::string payload;
  17909. bool fin;
  17910. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17911. false, 1024));
  17912. }
  17913. // MSB clear - should pass length parsing (will be rejected by max_len,
  17914. // but that's a different check; use a small length to verify)
  17915. {
  17916. detail::BufferStream strm;
  17917. std::string frame;
  17918. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17919. frame += static_cast<char>(127); // 64-bit extended length
  17920. frame += std::string(7, '\0'); // high bytes = 0
  17921. frame += static_cast<char>(0x03); // length = 3
  17922. frame += "abc";
  17923. strm.write(frame.data(), frame.size());
  17924. ws::Opcode opcode;
  17925. std::string payload;
  17926. bool fin;
  17927. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17928. false, 1024));
  17929. EXPECT_EQ(ws::Opcode::Text, opcode);
  17930. EXPECT_EQ("abc", payload);
  17931. }
  17932. }
  17933. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17934. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17935. // Valid UTF-8
  17936. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17937. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17938. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17939. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17940. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17941. // Invalid UTF-8
  17942. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17943. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17944. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17945. EXPECT_FALSE(
  17946. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17947. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17948. }
  17949. TEST(WebSocketTest, ConnectAndDisconnect) {
  17950. Server svr;
  17951. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17952. std::string msg;
  17953. while (ws.read(msg)) {}
  17954. });
  17955. auto port = svr.bind_to_any_port(HOST);
  17956. std::thread t([&]() { svr.listen_after_bind(); });
  17957. svr.wait_until_ready();
  17958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17959. auto res = client.connect();
  17960. ASSERT_TRUE(res);
  17961. EXPECT_EQ(Error::Success, res.error());
  17962. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17963. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17964. EXPECT_TRUE(client.is_open());
  17965. client.close();
  17966. EXPECT_FALSE(client.is_open());
  17967. svr.stop();
  17968. t.join();
  17969. }
  17970. TEST(WebSocketTest, ValidURL) {
  17971. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17972. EXPECT_TRUE(ws1.is_valid());
  17973. ws::WebSocketClient ws2("ws://example.com/path");
  17974. EXPECT_TRUE(ws2.is_valid());
  17975. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17976. EXPECT_TRUE(ws3.is_valid());
  17977. #ifdef CPPHTTPLIB_SSL_ENABLED
  17978. ws::WebSocketClient wss1("wss://example.com/path");
  17979. EXPECT_TRUE(wss1.is_valid());
  17980. ws::WebSocketClient wss2("wss://example.com:443/path");
  17981. EXPECT_TRUE(wss2.is_valid());
  17982. #endif
  17983. }
  17984. TEST(WebSocketTest, InvalidURL) {
  17985. // No scheme
  17986. ws::WebSocketClient ws1("localhost:8080/path");
  17987. EXPECT_FALSE(ws1.is_valid());
  17988. // No path
  17989. ws::WebSocketClient ws2("ws://localhost:8080");
  17990. EXPECT_FALSE(ws2.is_valid());
  17991. // Empty string
  17992. ws::WebSocketClient ws3("");
  17993. EXPECT_FALSE(ws3.is_valid());
  17994. // Missing host
  17995. ws::WebSocketClient ws4("ws://:8080/path");
  17996. EXPECT_FALSE(ws4.is_valid());
  17997. // Port number overflow — should not crash
  17998. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17999. EXPECT_FALSE(ws5.is_valid());
  18000. // Port out of range
  18001. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18002. EXPECT_FALSE(ws6.is_valid());
  18003. }
  18004. TEST(WebSocketTest, UnsupportedScheme) {
  18005. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18006. ws::WebSocketClient ws1("http://localhost:8080/path");
  18007. EXPECT_FALSE(ws1.is_valid());
  18008. ws::WebSocketClient ws2("https://localhost:8080/path");
  18009. EXPECT_FALSE(ws2.is_valid());
  18010. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18011. EXPECT_FALSE(ws3.is_valid());
  18012. #else
  18013. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18014. std::invalid_argument);
  18015. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18016. std::invalid_argument);
  18017. #endif
  18018. }
  18019. TEST(WebSocketTest, ConnectWhenInvalid) {
  18020. ws::WebSocketClient ws("not a valid url");
  18021. EXPECT_FALSE(ws.is_valid());
  18022. auto res = ws.connect();
  18023. EXPECT_FALSE(res);
  18024. EXPECT_EQ(Error::Connection, res.error());
  18025. EXPECT_EQ(-1, res.status());
  18026. }
  18027. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18028. // Grab a port that is free, then close it again so nothing listens there
  18029. Server svr;
  18030. auto port = svr.bind_to_any_port(HOST);
  18031. svr.stop();
  18032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18033. auto res = client.connect();
  18034. ASSERT_FALSE(res);
  18035. EXPECT_EQ(Error::Connection, res.error());
  18036. EXPECT_EQ(-1, res.status());
  18037. }
  18038. TEST(WebSocketTest, DefaultPort) {
  18039. ws::WebSocketClient ws1("ws://example.com/path");
  18040. EXPECT_TRUE(ws1.is_valid());
  18041. // ws:// defaults to port 80 (verified by successful parse)
  18042. #ifdef CPPHTTPLIB_SSL_ENABLED
  18043. ws::WebSocketClient ws2("wss://example.com/path");
  18044. EXPECT_TRUE(ws2.is_valid());
  18045. // wss:// defaults to port 443 (verified by successful parse)
  18046. #endif
  18047. }
  18048. TEST(WebSocketTest, IPv6LiteralAddress) {
  18049. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18050. EXPECT_TRUE(ws1.is_valid());
  18051. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18052. EXPECT_TRUE(ws2.is_valid());
  18053. }
  18054. TEST(WebSocketTest, ComplexPath) {
  18055. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18056. EXPECT_TRUE(ws1.is_valid());
  18057. ws::WebSocketClient ws2("ws://localhost:8080/");
  18058. EXPECT_TRUE(ws2.is_valid());
  18059. }
  18060. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18061. Server svr;
  18062. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18063. std::string msg;
  18064. while (ws.read(msg)) {}
  18065. });
  18066. auto port = svr.bind_to_any_port(HOST);
  18067. std::thread t([&]() { svr.listen_after_bind(); });
  18068. svr.wait_until_ready();
  18069. auto another_host = "example.com";
  18070. auto wrong_ip = "192.0.2.1";
  18071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18072. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18073. ASSERT_TRUE(client.connect());
  18074. EXPECT_TRUE(client.is_open());
  18075. client.close();
  18076. svr.stop();
  18077. t.join();
  18078. }
  18079. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18080. Server svr;
  18081. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18082. std::string msg;
  18083. while (ws.read(msg)) {}
  18084. });
  18085. auto port = svr.bind_to_any_port(HOST);
  18086. std::thread t([&]() { svr.listen_after_bind(); });
  18087. svr.wait_until_ready();
  18088. auto wrong_ip = "192.0.2.1";
  18089. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18090. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18091. client.set_connection_timeout(1);
  18092. client.set_read_timeout(1);
  18093. client.set_write_timeout(1);
  18094. EXPECT_FALSE(client.connect());
  18095. EXPECT_FALSE(client.is_open());
  18096. svr.stop();
  18097. t.join();
  18098. }
  18099. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18100. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18101. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18102. // (RFC 6761) is only a map key and the Host header value.
  18103. auto host = "target.invalid";
  18104. Server svr;
  18105. std::string received_host;
  18106. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18107. received_host = req.get_header_value("Host");
  18108. std::string msg;
  18109. while (ws.read(msg)) {}
  18110. });
  18111. auto port = svr.bind_to_any_port(HOST);
  18112. std::thread t([&]() { svr.listen_after_bind(); });
  18113. // ASSERT_* below returns from the test body, which would leave t joinable
  18114. // and make ~thread call std::terminate.
  18115. auto se = detail::scope_exit([&] {
  18116. svr.stop();
  18117. if (t.joinable()) { t.join(); }
  18118. });
  18119. svr.wait_until_ready();
  18120. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18121. std::to_string(port) + "/ws");
  18122. client.set_hostname_addr_map({{host, HOST}});
  18123. ASSERT_TRUE(client.connect());
  18124. EXPECT_TRUE(client.is_open());
  18125. client.close();
  18126. svr.stop();
  18127. t.join();
  18128. // The mapping only redirects the connection; the identity stays host_.
  18129. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18130. }
  18131. class WebSocketIntegrationTest : public ::testing::Test {
  18132. protected:
  18133. void SetUp() override {
  18134. server_ = httplib::detail::make_unique<Server>();
  18135. setup_server();
  18136. start_server();
  18137. }
  18138. void TearDown() override {
  18139. server_->stop();
  18140. if (server_thread_.joinable()) { server_thread_.join(); }
  18141. }
  18142. void setup_server() {
  18143. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18144. std::string msg;
  18145. ws::ReadResult ret;
  18146. while ((ret = ws.read(msg))) {
  18147. if (ret == ws::Binary) {
  18148. ws.send(msg.data(), msg.size());
  18149. } else {
  18150. ws.send(msg);
  18151. }
  18152. }
  18153. });
  18154. server_->WebSocket("/ws-echo-string",
  18155. [](const Request &, ws::WebSocket &ws) {
  18156. std::string msg;
  18157. while (ws.read(msg)) {
  18158. ws.send("echo: " + msg);
  18159. }
  18160. });
  18161. server_->WebSocket(
  18162. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18163. // Echo back request metadata
  18164. ws.send("path:" + req.path);
  18165. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18166. std::string msg;
  18167. while (ws.read(msg)) {}
  18168. });
  18169. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18170. std::string msg;
  18171. ws.read(msg); // wait for a message
  18172. ws.close();
  18173. });
  18174. server_->WebSocket("/ws-close-status",
  18175. [](const Request &, ws::WebSocket &ws) {
  18176. std::string msg;
  18177. ws.read(msg); // wait for a message
  18178. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18179. });
  18180. server_->WebSocket(
  18181. "/ws-subprotocol",
  18182. [](const Request &, ws::WebSocket &ws) {
  18183. std::string msg;
  18184. while (ws.read(msg)) {
  18185. ws.send(msg);
  18186. }
  18187. },
  18188. [](const std::vector<std::string> &protocols) -> std::string {
  18189. for (const auto &p : protocols) {
  18190. if (p == "graphql-ws") { return p; }
  18191. }
  18192. return "";
  18193. });
  18194. }
  18195. void start_server() {
  18196. port_ = server_->bind_to_any_port(HOST);
  18197. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18198. server_->wait_until_ready();
  18199. }
  18200. std::unique_ptr<Server> server_;
  18201. std::thread server_thread_;
  18202. int port_ = 0;
  18203. };
  18204. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18206. "/ws-echo");
  18207. ASSERT_TRUE(client.connect());
  18208. ASSERT_TRUE(client.is_open());
  18209. ASSERT_TRUE(client.send("Hello WebSocket"));
  18210. std::string msg;
  18211. EXPECT_EQ(ws::Text, client.read(msg));
  18212. EXPECT_EQ("Hello WebSocket", msg);
  18213. client.close();
  18214. }
  18215. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18216. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18217. "/ws-echo");
  18218. ASSERT_TRUE(client.connect());
  18219. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18220. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18221. std::string msg;
  18222. EXPECT_EQ(ws::Binary, client.read(msg));
  18223. EXPECT_EQ(binary_data, msg);
  18224. client.close();
  18225. }
  18226. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18228. "/ws-echo");
  18229. ASSERT_TRUE(client.connect());
  18230. for (int i = 0; i < 10; i++) {
  18231. auto text = "message " + std::to_string(i);
  18232. ASSERT_TRUE(client.send(text));
  18233. std::string msg;
  18234. ASSERT_TRUE(client.read(msg));
  18235. EXPECT_EQ(text, msg);
  18236. }
  18237. client.close();
  18238. }
  18239. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18240. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18241. "/ws-close");
  18242. ASSERT_TRUE(client.connect());
  18243. // Send a message to trigger the server to close
  18244. ASSERT_TRUE(client.send("trigger close"));
  18245. // The server will close, so read should return false
  18246. std::string msg;
  18247. EXPECT_FALSE(client.read(msg));
  18248. EXPECT_FALSE(client.is_open());
  18249. }
  18250. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18251. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18252. "/ws-echo");
  18253. ASSERT_TRUE(client.connect());
  18254. // 128KB message
  18255. std::string large_data(128 * 1024, 'X');
  18256. ASSERT_TRUE(client.send(large_data));
  18257. std::string msg;
  18258. ASSERT_TRUE(client.read(msg));
  18259. EXPECT_EQ(large_data, msg);
  18260. client.close();
  18261. }
  18262. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18263. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18264. "/ws-echo");
  18265. ASSERT_TRUE(client.connect());
  18266. const int num_threads = 4;
  18267. std::vector<std::thread> threads;
  18268. std::atomic<int> send_count{0};
  18269. for (int t = 0; t < num_threads; t++) {
  18270. threads.emplace_back([&client, &send_count, t]() {
  18271. for (int i = 0; i < 5; i++) {
  18272. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18273. if (client.send(text)) { send_count++; }
  18274. }
  18275. });
  18276. }
  18277. for (auto &th : threads) {
  18278. th.join();
  18279. }
  18280. int received = 0;
  18281. std::string msg;
  18282. while (received < send_count.load()) {
  18283. if (!client.read(msg)) { break; }
  18284. received++;
  18285. }
  18286. EXPECT_EQ(send_count.load(), received);
  18287. client.close();
  18288. }
  18289. TEST_F(WebSocketIntegrationTest, ReadString) {
  18290. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18291. "/ws-echo-string");
  18292. ASSERT_TRUE(client.connect());
  18293. ASSERT_TRUE(client.send("hello"));
  18294. std::string msg;
  18295. ASSERT_TRUE(client.read(msg));
  18296. EXPECT_EQ("echo: hello", msg);
  18297. ASSERT_TRUE(client.send("world"));
  18298. ASSERT_TRUE(client.read(msg));
  18299. EXPECT_EQ("echo: world", msg);
  18300. client.close();
  18301. }
  18302. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18303. Headers headers = {{"X-Test-Header", "test-value"}};
  18304. ws::WebSocketClient client(
  18305. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18306. ASSERT_TRUE(client.connect());
  18307. std::string msg;
  18308. ASSERT_TRUE(client.read(msg));
  18309. EXPECT_EQ("path:/ws-request-info", msg);
  18310. ASSERT_TRUE(client.read(msg));
  18311. EXPECT_EQ("header:test-value", msg);
  18312. client.close();
  18313. }
  18314. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18316. "/ws-echo");
  18317. client.set_read_timeout(1, 0); // 1 second
  18318. ASSERT_TRUE(client.connect());
  18319. // Don't send anything — server echo handler waits for a message,
  18320. // so read() should time out and return false.
  18321. std::string msg;
  18322. EXPECT_FALSE(client.read(msg));
  18323. }
  18324. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18326. "/ws-echo");
  18327. client.set_read_timeout(5, 0);
  18328. ASSERT_TRUE(client.connect());
  18329. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18330. // The server should reject it and close the connection.
  18331. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18332. client.send(oversized);
  18333. // The server's read() should have failed due to payload limit,
  18334. // so our read() should return false (connection closed).
  18335. std::string msg;
  18336. EXPECT_FALSE(client.read(msg));
  18337. }
  18338. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18339. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18340. "/ws-echo");
  18341. client.set_read_timeout(10, 0);
  18342. ASSERT_TRUE(client.connect());
  18343. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18344. // This should succeed.
  18345. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18346. ASSERT_TRUE(client.send(at_limit));
  18347. std::string msg;
  18348. ASSERT_TRUE(client.read(msg));
  18349. EXPECT_EQ(at_limit.size(), msg.size());
  18350. client.close();
  18351. }
  18352. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18354. "/nonexistent");
  18355. auto res = client.connect();
  18356. EXPECT_FALSE(res);
  18357. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18358. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18359. EXPECT_FALSE(client.is_open());
  18360. }
  18361. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18362. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18363. "/ws-echo");
  18364. ASSERT_TRUE(client.connect());
  18365. ASSERT_TRUE(client.send(""));
  18366. std::string msg;
  18367. EXPECT_EQ(ws::Text, client.read(msg));
  18368. EXPECT_EQ("", msg);
  18369. client.close();
  18370. }
  18371. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18372. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18373. "/ws-echo");
  18374. // First connection
  18375. ASSERT_TRUE(client.connect());
  18376. ASSERT_TRUE(client.send("first"));
  18377. std::string msg;
  18378. ASSERT_TRUE(client.read(msg));
  18379. EXPECT_EQ("first", msg);
  18380. client.close();
  18381. EXPECT_FALSE(client.is_open());
  18382. // Reconnect using the same client object
  18383. ASSERT_TRUE(client.connect());
  18384. ASSERT_TRUE(client.is_open());
  18385. ASSERT_TRUE(client.send("second"));
  18386. ASSERT_TRUE(client.read(msg));
  18387. EXPECT_EQ("second", msg);
  18388. client.close();
  18389. }
  18390. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18391. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18392. "/ws-close-status");
  18393. ASSERT_TRUE(client.connect());
  18394. // Trigger the server to close with GoingAway status
  18395. ASSERT_TRUE(client.send("trigger"));
  18396. // read() should return false after receiving the close frame
  18397. std::string msg;
  18398. EXPECT_FALSE(client.read(msg));
  18399. EXPECT_FALSE(client.is_open());
  18400. }
  18401. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18402. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18403. "/ws-echo");
  18404. ASSERT_TRUE(client.connect());
  18405. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18406. EXPECT_FALSE(client.is_open());
  18407. }
  18408. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18409. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18410. ws::WebSocketClient client(
  18411. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18412. ASSERT_TRUE(client.connect());
  18413. // Server should have selected graphql-ws
  18414. EXPECT_EQ("graphql-ws", client.subprotocol());
  18415. client.close();
  18416. }
  18417. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18418. Headers headers;
  18419. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18420. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18421. ws::WebSocketClient client(
  18422. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18423. ASSERT_TRUE(client.connect());
  18424. // The offer on the second field line counts too, so graphql-ws is selected
  18425. EXPECT_EQ("graphql-ws", client.subprotocol());
  18426. client.close();
  18427. }
  18428. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18429. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18430. ws::WebSocketClient client(
  18431. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18432. ASSERT_TRUE(client.connect());
  18433. // Server should not have selected any subprotocol
  18434. EXPECT_TRUE(client.subprotocol().empty());
  18435. client.close();
  18436. }
  18437. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18438. // Connect without requesting any subprotocol
  18439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18440. "/ws-subprotocol");
  18441. ASSERT_TRUE(client.connect());
  18442. EXPECT_TRUE(client.subprotocol().empty());
  18443. client.close();
  18444. }
  18445. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18446. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18447. "/ws-echo");
  18448. client.set_tcp_nodelay(true);
  18449. client.set_connection_timeout(3, 0);
  18450. bool socket_options_called = false;
  18451. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18452. ASSERT_TRUE(client.connect());
  18453. ASSERT_TRUE(client.is_open());
  18454. EXPECT_TRUE(socket_options_called);
  18455. ASSERT_TRUE(client.send("hello"));
  18456. std::string msg;
  18457. auto result = client.read(msg);
  18458. EXPECT_EQ(result, ws::ReadResult::Text);
  18459. EXPECT_EQ(msg, "hello");
  18460. client.close();
  18461. }
  18462. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18464. "/ws-echo");
  18465. client.set_connection_timeout(std::chrono::seconds(3));
  18466. client.set_write_timeout(std::chrono::seconds(3));
  18467. // A sub-second remainder exercises the seconds/microseconds split.
  18468. client.set_read_timeout(std::chrono::milliseconds(1500));
  18469. ASSERT_TRUE(client.connect());
  18470. auto start = std::chrono::steady_clock::now();
  18471. std::string msg;
  18472. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18473. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18474. std::chrono::steady_clock::now() - start)
  18475. .count();
  18476. // Above 1s so that dropping the microseconds half of the split fails here,
  18477. // and well under the 300s default so that ignoring the setter fails too.
  18478. EXPECT_GE(elapsed, 1400);
  18479. EXPECT_LT(elapsed, 30000);
  18480. }
  18481. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18482. Server svr;
  18483. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18484. if (!req.has_header("Authorization")) {
  18485. res.status = StatusCode::Unauthorized_401;
  18486. res.set_content("Unauthorized", "text/plain");
  18487. return Server::HandlerResponse::Handled;
  18488. }
  18489. return Server::HandlerResponse::Unhandled;
  18490. });
  18491. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18492. std::string msg;
  18493. while (ws.read(msg)) {
  18494. ws.send(msg);
  18495. }
  18496. });
  18497. auto port = svr.bind_to_any_port("localhost");
  18498. std::thread t([&]() { svr.listen_after_bind(); });
  18499. svr.wait_until_ready();
  18500. // Without Authorization header - should be rejected before upgrade
  18501. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18502. EXPECT_FALSE(client1.connect());
  18503. // With Authorization header - should succeed
  18504. Headers headers = {{"Authorization", "Bearer token123"}};
  18505. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18506. headers);
  18507. ASSERT_TRUE(client2.connect());
  18508. ASSERT_TRUE(client2.send("hello"));
  18509. std::string msg;
  18510. ASSERT_TRUE(client2.read(msg));
  18511. EXPECT_EQ("hello", msg);
  18512. client2.close();
  18513. svr.stop();
  18514. t.join();
  18515. }
  18516. TEST(WebSocketTest, QueryStringInHandshake) {
  18517. Server svr;
  18518. std::mutex mtx;
  18519. std::string received_target;
  18520. std::string received_token;
  18521. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18522. {
  18523. std::lock_guard<std::mutex> lock(mtx);
  18524. received_target = req.target;
  18525. if (req.has_param("token")) {
  18526. received_token = req.get_param_value("token");
  18527. }
  18528. }
  18529. std::string msg;
  18530. while (ws.read(msg)) {
  18531. ws.send(msg);
  18532. }
  18533. });
  18534. auto port = svr.bind_to_any_port("localhost");
  18535. std::thread t([&]() { svr.listen_after_bind(); });
  18536. svr.wait_until_ready();
  18537. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18538. "/ws?token=ABC&session=123");
  18539. ASSERT_TRUE(client.connect());
  18540. // Round-trip ensures the handler has run and captured the request.
  18541. ASSERT_TRUE(client.send("hello"));
  18542. std::string msg;
  18543. ASSERT_TRUE(client.read(msg));
  18544. EXPECT_EQ("hello", msg);
  18545. client.close();
  18546. {
  18547. std::lock_guard<std::mutex> lock(mtx);
  18548. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18549. EXPECT_EQ("ABC", received_token);
  18550. }
  18551. svr.stop();
  18552. t.join();
  18553. }
  18554. // Run a handshake against a throwaway server and hand the request the server
  18555. // received back to the caller, so tests can assert on the headers the client
  18556. // actually put on the wire.
  18557. static void capture_websocket_handshake_request(
  18558. const Headers &client_headers,
  18559. std::function<void(const Request &, int port)> verify) {
  18560. Server svr;
  18561. std::mutex mtx;
  18562. Request received;
  18563. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18564. {
  18565. std::lock_guard<std::mutex> lock(mtx);
  18566. received = req;
  18567. }
  18568. std::string msg;
  18569. while (ws.read(msg)) {
  18570. ws.send(msg);
  18571. }
  18572. });
  18573. auto port = svr.bind_to_any_port("localhost");
  18574. std::thread t([&]() { svr.listen_after_bind(); });
  18575. auto se = detail::scope_exit([&] {
  18576. svr.stop();
  18577. t.join();
  18578. });
  18579. svr.wait_until_ready();
  18580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18581. client_headers);
  18582. ASSERT_TRUE(client.connect());
  18583. ASSERT_TRUE(client.send("hello"));
  18584. std::string msg;
  18585. ASSERT_TRUE(client.read(msg));
  18586. client.close();
  18587. {
  18588. std::lock_guard<std::mutex> lock(mtx);
  18589. verify(received, port);
  18590. }
  18591. }
  18592. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18593. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18594. // Non-default port must be present in the Host header. Default ports
  18595. // (80/443) are omitted; that logic is covered by
  18596. // MakeHostAndPortStringTest.
  18597. EXPECT_EQ("localhost:" + std::to_string(port),
  18598. req.get_header_value("Host"));
  18599. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18600. req.get_header_value("User-Agent"));
  18601. EXPECT_FALSE(req.has_header("Accept"));
  18602. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18603. EXPECT_FALSE(req.has_header("Content-Length"));
  18604. });
  18605. }
  18606. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18607. capture_websocket_handshake_request(
  18608. {{"Host", "example.com"},
  18609. {"User-Agent", "custom-agent"},
  18610. {"X-Custom", "value"}},
  18611. [](const Request &req, int) {
  18612. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18613. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18614. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18615. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18616. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18617. });
  18618. }
  18619. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18620. capture_websocket_handshake_request(
  18621. {{"Upgrade", "bogus"},
  18622. {"Connection", "close"},
  18623. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18624. {"Sec-WebSocket-Version", "8"}},
  18625. [](const Request &req, int) {
  18626. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18627. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18628. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18629. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18630. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18631. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18632. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18633. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18634. req.get_header_value("Sec-WebSocket-Key"));
  18635. });
  18636. }
  18637. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18638. // A header the client refuses to send must abort the handshake before any
  18639. // part of it reaches the wire; a lone request line would otherwise sit in
  18640. // the peer's buffer as a truncated request.
  18641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18642. ASSERT_NE(INVALID_SOCKET, srv);
  18643. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18644. sockaddr_in addr{};
  18645. addr.sin_family = AF_INET;
  18646. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18647. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18648. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18649. ASSERT_EQ(0, ::listen(srv, 1));
  18650. sockaddr_in bound{};
  18651. socklen_t bound_len = sizeof(bound);
  18652. ASSERT_EQ(
  18653. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18654. auto port = ntohs(bound.sin_port);
  18655. ssize_t received = -1;
  18656. std::thread t([&] {
  18657. // Bound every blocking call so a regression fails the test with a bad
  18658. // value instead of hanging the suite.
  18659. fd_set rfds;
  18660. FD_ZERO(&rfds);
  18661. FD_SET(srv, &rfds);
  18662. timeval tv{5, 0};
  18663. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18664. 0) {
  18665. return;
  18666. }
  18667. sockaddr_in cli_addr{};
  18668. socklen_t cli_len = sizeof(cli_addr);
  18669. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18670. if (cli == INVALID_SOCKET) { return; }
  18671. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18672. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18673. char buf[4096];
  18674. received = ::recv(cli, buf, sizeof(buf), 0);
  18675. });
  18676. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18677. // connect() has already shut the socket down by the time it returns false,
  18678. // so the peer sees EOF without waiting for the client to be destroyed.
  18679. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18680. {{"X-Bad", "a\r\nInjected: 1"}});
  18681. EXPECT_FALSE(client.connect());
  18682. t.join();
  18683. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18684. EXPECT_EQ(0, received);
  18685. }
  18686. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18687. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18688. // contains "upgrade" as a substring is a different token and must not
  18689. // start a WebSocket handshake.
  18690. auto make_request = [](const std::vector<std::string> &connection_values) {
  18691. Request req;
  18692. req.method = "GET";
  18693. req.headers.emplace("Upgrade", "websocket");
  18694. for (const auto &value : connection_values) {
  18695. req.headers.emplace("Connection", value);
  18696. }
  18697. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18698. req.headers.emplace("Sec-WebSocket-Version", "13");
  18699. return req;
  18700. };
  18701. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18702. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18703. EXPECT_TRUE(
  18704. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18705. EXPECT_TRUE(
  18706. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18707. EXPECT_TRUE(
  18708. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18709. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18710. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18711. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18712. EXPECT_FALSE(
  18713. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18714. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18715. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18716. }
  18717. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18718. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18719. // asks recipients to match each protocol-name case-insensitively, and RFC
  18720. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18721. // client naming websocket alongside another protocol, or on a second field
  18722. // line, is offering websocket; a value that merely contains "websocket" as a
  18723. // substring is a different protocol name and is not.
  18724. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18725. Request req;
  18726. req.method = "GET";
  18727. for (const auto &value : upgrade_values) {
  18728. req.headers.emplace("Upgrade", value);
  18729. }
  18730. req.headers.emplace("Connection", "Upgrade");
  18731. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18732. req.headers.emplace("Sec-WebSocket-Version", "13");
  18733. return req;
  18734. };
  18735. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18736. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18737. EXPECT_TRUE(
  18738. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18739. EXPECT_TRUE(
  18740. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18741. EXPECT_TRUE(
  18742. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18743. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18744. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18745. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18746. EXPECT_FALSE(
  18747. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18748. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18749. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18750. }
  18751. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18752. Server svr;
  18753. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18754. auto port = svr.bind_to_any_port("localhost");
  18755. std::thread t([&]() { svr.listen_after_bind(); });
  18756. auto se = detail::scope_exit([&] {
  18757. svr.stop();
  18758. t.join();
  18759. });
  18760. svr.wait_until_ready();
  18761. Headers headers = {{"Upgrade", "websocket"},
  18762. {"Connection", "notupgrade"},
  18763. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18764. {"Sec-WebSocket-Version", "13"}};
  18765. Client cli("localhost", port);
  18766. auto res = cli.Get("/ws", headers);
  18767. // The route exists only as a WebSocket route, so a request that fails the
  18768. // handshake check falls through to ordinary routing.
  18769. ASSERT_TRUE(res);
  18770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18771. }
  18772. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18773. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18774. // Connection value is the only thing left for the client to reject.
  18775. Server svr;
  18776. svr.Get("/ws", [](const Request &req, Response &res) {
  18777. res.status = StatusCode::SwitchingProtocol_101;
  18778. res.set_header("Upgrade", "websocket");
  18779. res.set_header("Connection", "notupgrade");
  18780. res.set_header("Sec-WebSocket-Accept",
  18781. detail::websocket_accept_key(
  18782. req.get_header_value("Sec-WebSocket-Key")));
  18783. });
  18784. auto port = svr.bind_to_any_port("localhost");
  18785. std::thread t([&]() { svr.listen_after_bind(); });
  18786. auto se = detail::scope_exit([&] {
  18787. svr.stop();
  18788. t.join();
  18789. });
  18790. svr.wait_until_ready();
  18791. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18792. auto res = client.connect();
  18793. EXPECT_FALSE(res);
  18794. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18795. EXPECT_FALSE(client.is_open());
  18796. }
  18797. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18798. // The socket path doubles as the URL host, so it must not contain '/'.
  18799. const char *shard = getenv("GTEST_SHARD_INDEX");
  18800. const std::string sock_path =
  18801. shard ? std::string("httplib-ws-") + shard + ".sock"
  18802. : std::string("httplib-ws.sock");
  18803. std::remove(sock_path.c_str());
  18804. Server svr;
  18805. std::mutex mtx;
  18806. std::string received_host;
  18807. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18808. {
  18809. std::lock_guard<std::mutex> lock(mtx);
  18810. received_host = req.get_header_value("Host");
  18811. }
  18812. std::string msg;
  18813. while (ws.read(msg)) {
  18814. ws.send(msg);
  18815. }
  18816. });
  18817. svr.set_address_family(AF_UNIX);
  18818. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18819. auto se = detail::scope_exit([&] {
  18820. svr.stop();
  18821. t.join();
  18822. std::remove(sock_path.c_str());
  18823. });
  18824. svr.wait_until_ready();
  18825. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18826. client.set_address_family(AF_UNIX);
  18827. ASSERT_TRUE(client.connect());
  18828. ASSERT_TRUE(client.send("hello"));
  18829. std::string msg;
  18830. ASSERT_TRUE(client.read(msg));
  18831. client.close();
  18832. {
  18833. std::lock_guard<std::mutex> lock(mtx);
  18834. // There is no host:port for a Unix socket, so the same "localhost"
  18835. // placeholder the HTTP client uses is expected.
  18836. EXPECT_EQ("localhost", received_host);
  18837. }
  18838. }
  18839. // Two threads must never parse WebSocket frames from the same stream.
  18840. // close() used to read the peer's Close reply with its own frame read, so it
  18841. // raced a reader thread that was in the middle of a payload: the payload loop
  18842. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18843. // so bytes taken by close() were replaced with bytes from further along the
  18844. // stream. The message kept its length and silently changed content.
  18845. //
  18846. // The raw peer below sends a frame header plus part of the payload, waits for
  18847. // the handler to call close(), and only then sends the rest. Whichever thread
  18848. // would win the race for those bytes, the message must arrive intact, because
  18849. // close() must not touch the stream while read() owns it.
  18850. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18851. #ifndef _WIN32
  18852. signal(SIGPIPE, SIG_IGN);
  18853. #endif
  18854. const size_t payload_len = 120; // fits the 7-bit length field
  18855. const size_t prefix_len = 8;
  18856. const int attempts = 8;
  18857. std::string expected(payload_len, '\0');
  18858. for (size_t i = 0; i < payload_len; i++) {
  18859. expected[i] = static_cast<char>('a' + i % 26);
  18860. }
  18861. std::atomic<bool> peer_stalled{false};
  18862. std::atomic<bool> handler_done{false};
  18863. std::mutex received_mutex;
  18864. std::vector<std::string> received;
  18865. // Bound every wait, so a regression fails the test instead of hanging the
  18866. // suite.
  18867. auto wait_for = [](const std::atomic<bool> &flag) {
  18868. for (int i = 0; i < 500 && !flag; i++) {
  18869. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18870. }
  18871. };
  18872. Server svr;
  18873. svr.set_websocket_ping_interval(0);
  18874. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18875. std::thread reader([&]() {
  18876. std::string msg;
  18877. while (ws.read(msg)) {
  18878. std::lock_guard<std::mutex> guard(received_mutex);
  18879. received.push_back(msg);
  18880. }
  18881. });
  18882. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18883. // inside read_websocket_frame() when close() runs.
  18884. wait_for(peer_stalled);
  18885. ws.close();
  18886. reader.join();
  18887. handler_done = true;
  18888. });
  18889. auto port = svr.bind_to_any_port("127.0.0.1");
  18890. std::thread t([&]() { svr.listen_after_bind(); });
  18891. auto se = detail::scope_exit([&] {
  18892. svr.stop();
  18893. t.join();
  18894. });
  18895. svr.wait_until_ready();
  18896. auto send_bytes = [](socket_t s, const std::string &data) {
  18897. #ifdef _WIN32
  18898. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18899. #else
  18900. auto n = ::send(s, data.data(), data.size(), 0);
  18901. #endif
  18902. return n == static_cast<decltype(n)>(data.size());
  18903. };
  18904. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18905. // Every length used here fits the 7-bit length field.
  18906. auto masked_header = [](uint8_t first_byte, size_t len) {
  18907. std::string h;
  18908. h += static_cast<char>(first_byte);
  18909. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18910. h.append(4, '\0'); // mask key
  18911. return h;
  18912. };
  18913. for (int attempt = 0; attempt < attempts; attempt++) {
  18914. peer_stalled = false;
  18915. handler_done = false;
  18916. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18917. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18918. auto se_sock = detail::scope_exit([&] {
  18919. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18920. });
  18921. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18922. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18923. sockaddr_in addr{};
  18924. addr.sin_family = AF_INET;
  18925. addr.sin_port = htons(static_cast<uint16_t>(port));
  18926. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18927. ASSERT_EQ(
  18928. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18929. << "attempt " << attempt;
  18930. ASSERT_TRUE(send_bytes(sock,
  18931. "GET /ws HTTP/1.1\r\n"
  18932. "Host: 127.0.0.1\r\n"
  18933. "Upgrade: websocket\r\n"
  18934. "Connection: Upgrade\r\n"
  18935. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18936. "Sec-WebSocket-Version: 13\r\n"
  18937. "\r\n"))
  18938. << "attempt " << attempt;
  18939. std::string response;
  18940. while (response.find("\r\n\r\n") == std::string::npos) {
  18941. char buf[512];
  18942. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18943. if (n <= 0) { break; }
  18944. response.append(buf, static_cast<size_t>(n));
  18945. }
  18946. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18947. << "attempt " << attempt;
  18948. // Send the header of a Binary message but only the first prefix_len bytes
  18949. // of its payload, leaving the reader thread stalled inside the payload.
  18950. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18951. expected.substr(0, prefix_len)))
  18952. << "attempt " << attempt;
  18953. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18954. peer_stalled = true;
  18955. // Let close() send its Close frame and park in its own read before the
  18956. // rest of the payload arrives, so both threads are waiting for it.
  18957. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18958. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18959. close_frame += static_cast<char>(0x03); // status 1000
  18960. close_frame += static_cast<char>(0xE8);
  18961. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18962. << "attempt " << attempt;
  18963. // Closing the peer releases the reader thread even on the buggy path,
  18964. // where it waits for bytes another thread already consumed.
  18965. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18966. detail::close_socket(sock);
  18967. sock = INVALID_SOCKET;
  18968. wait_for(handler_done);
  18969. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18970. }
  18971. std::lock_guard<std::mutex> guard(received_mutex);
  18972. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18973. << "a message in flight when close() ran was dropped";
  18974. for (size_t i = 0; i < received.size(); i++) {
  18975. EXPECT_EQ(expected, received[i]) << "message " << i;
  18976. }
  18977. }
  18978. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18979. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18980. protected:
  18981. void SetUp() override {
  18982. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18983. SERVER_PRIVATE_KEY_FILE);
  18984. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18985. std::string msg;
  18986. ws::ReadResult ret;
  18987. while ((ret = ws.read(msg))) {
  18988. if (ret == ws::Binary) {
  18989. ws.send(msg.data(), msg.size());
  18990. } else {
  18991. ws.send(msg);
  18992. }
  18993. }
  18994. });
  18995. port_ = server_->bind_to_any_port(HOST);
  18996. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18997. server_->wait_until_ready();
  18998. }
  18999. void TearDown() override {
  19000. server_->stop();
  19001. if (server_thread_.joinable()) { server_thread_.join(); }
  19002. }
  19003. std::unique_ptr<SSLServer> server_;
  19004. std::thread server_thread_;
  19005. int port_ = 0;
  19006. };
  19007. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19008. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19009. "/ws-echo");
  19010. client.enable_server_certificate_verification(false);
  19011. ASSERT_TRUE(client.connect());
  19012. ASSERT_TRUE(client.is_open());
  19013. ASSERT_TRUE(client.send("Hello WSS"));
  19014. std::string msg;
  19015. EXPECT_EQ(ws::Text, client.read(msg));
  19016. EXPECT_EQ("Hello WSS", msg);
  19017. client.close();
  19018. }
  19019. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19020. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19021. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19022. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19023. // client (without calling close() first) is the only path that runs
  19024. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19025. // bug exactly.
  19026. //
  19027. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19028. // when linked against an instrumented libssl; run under Valgrind to catch it
  19029. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19030. // suite (the freed session otherwise stalls on the close handshake) — this test
  19031. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19032. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19033. {
  19034. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19035. "/ws-echo");
  19036. client.enable_server_certificate_verification(false);
  19037. client.set_read_timeout(2, 0);
  19038. client.set_write_timeout(2, 0);
  19039. ASSERT_TRUE(client.connect());
  19040. ASSERT_TRUE(client.is_open());
  19041. ASSERT_TRUE(client.send("still open"));
  19042. // Intentionally do NOT call client.close(): leaving scope runs
  19043. // shutdown_and_close() with the WebSocket still open, which must send the
  19044. // close frame while the TLS session is still alive.
  19045. }
  19046. }
  19047. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19048. // shutdown_and_close() at the start of connect(), reproducing the same
  19049. // use-after-free within the test body rather than at scope exit. The second
  19050. // connect must succeed and echo, proving the close handshake ran over a live
  19051. // session. See the note above about memory-tool requirements.
  19052. TEST_F(WebSocketSSLIntegrationTest,
  19053. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19054. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19055. "/ws-echo");
  19056. client.enable_server_certificate_verification(false);
  19057. client.set_read_timeout(2, 0);
  19058. client.set_write_timeout(2, 0);
  19059. ASSERT_TRUE(client.connect());
  19060. ASSERT_TRUE(client.is_open());
  19061. ASSERT_TRUE(client.send("still open"));
  19062. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19063. // the still-open connection, which must not touch a freed TLS session.
  19064. ASSERT_TRUE(client.connect());
  19065. ASSERT_TRUE(client.is_open());
  19066. ASSERT_TRUE(client.send("after reconnect"));
  19067. std::string msg;
  19068. EXPECT_EQ(ws::Text, client.read(msg));
  19069. EXPECT_EQ("after reconnect", msg);
  19070. client.close();
  19071. }
  19072. #endif
  19073. #ifdef CPPHTTPLIB_SSL_ENABLED
  19074. class WebSocketSSLCATest : public ::testing::Test {
  19075. protected:
  19076. void SetUp() override {
  19077. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19078. SERVER_PRIVATE_KEY_FILE);
  19079. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19080. std::string msg;
  19081. while (ws.read(msg)) {
  19082. ws.send(msg);
  19083. }
  19084. });
  19085. port_ = server_->bind_to_any_port("127.0.0.1");
  19086. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19087. server_->wait_until_ready();
  19088. }
  19089. void TearDown() override {
  19090. server_->stop();
  19091. if (server_thread_.joinable()) { server_thread_.join(); }
  19092. }
  19093. std::string url() const {
  19094. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19095. }
  19096. std::unique_ptr<SSLServer> server_;
  19097. std::thread server_thread_;
  19098. int port_ = 0;
  19099. };
  19100. // A custom CA loaded as PEM verifies the server with full certificate
  19101. // verification enabled
  19102. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19103. ws::WebSocketClient client(url());
  19104. std::string cert;
  19105. read_file(SERVER_CERT2_FILE, cert);
  19106. client.load_ca_cert_store(cert.c_str(), cert.size());
  19107. ASSERT_TRUE(client.connect());
  19108. ASSERT_TRUE(client.send("hello"));
  19109. std::string msg;
  19110. EXPECT_EQ(ws::Text, client.read(msg));
  19111. EXPECT_EQ("hello", msg);
  19112. client.close();
  19113. }
  19114. // A custom CA that does not cover the server must fail verification (the
  19115. // custom CA is exclusive; system certs are not loaded alongside it)
  19116. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19117. ws::WebSocketClient client(url());
  19118. std::string cert;
  19119. read_file(CLIENT_CA_CERT_FILE, cert);
  19120. client.load_ca_cert_store(cert.c_str(), cert.size());
  19121. auto res = client.connect();
  19122. ASSERT_FALSE(res);
  19123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19124. EXPECT_EQ(-1, res.status());
  19125. EXPECT_NE(0u, res.ssl_backend_error());
  19126. }
  19127. // The same CA as a file path rather than PEM in memory
  19128. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19129. ws::WebSocketClient client(url());
  19130. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19131. ASSERT_TRUE(client.connect());
  19132. ASSERT_TRUE(client.send("hello"));
  19133. std::string msg;
  19134. EXPECT_EQ(ws::Text, client.read(msg));
  19135. EXPECT_EQ("hello", msg);
  19136. client.close();
  19137. }
  19138. // ...and a CA file that does not cover the server still fails, so it is the
  19139. // path above that decides the outcome
  19140. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19141. ws::WebSocketClient client(url());
  19142. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19143. ASSERT_FALSE(client.connect());
  19144. }
  19145. // Regression test: reconnecting with a native custom CA store used to reuse
  19146. // a store handle the previous TLS context had already freed (use-after-free
  19147. // under the OpenSSL backend). The context now lives as long as the client.
  19148. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19149. ws::WebSocketClient client(url());
  19150. std::string cert;
  19151. read_file(SERVER_CERT2_FILE, cert);
  19152. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19153. ASSERT_TRUE(client.connect());
  19154. client.close();
  19155. ASSERT_TRUE(client.connect());
  19156. ASSERT_TRUE(client.send("again"));
  19157. std::string msg;
  19158. EXPECT_EQ(ws::Text, client.read(msg));
  19159. EXPECT_EQ("again", msg);
  19160. client.close();
  19161. }
  19162. // Regression test: a certificate with a trusted chain but no identity match
  19163. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19164. // verification entirely for IP hosts, so this connection succeeded there.
  19165. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19166. // chain verification while the identity check must still fail.
  19167. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19169. ASSERT_TRUE(svr.is_valid());
  19170. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19171. std::string msg;
  19172. while (ws.read(msg)) {
  19173. ws.send(msg);
  19174. }
  19175. });
  19176. auto port = svr.bind_to_any_port("127.0.0.1");
  19177. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19178. auto se = detail::scope_exit([&] {
  19179. svr.stop();
  19180. t.join();
  19181. });
  19182. svr.wait_until_ready();
  19183. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19184. "/echo");
  19185. std::string cert;
  19186. read_file(SERVER_CERT_FILE, cert);
  19187. client.load_ca_cert_store(cert.c_str(), cert.size());
  19188. ASSERT_FALSE(client.connect());
  19189. }
  19190. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19191. // SNI, so nothing binds the host name to the TLS session. These bind the
  19192. // server to "localhost" instead, the only shape that exercises the SNI and
  19193. // hostname-verification path with certificate verification left enabled.
  19194. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19195. protected:
  19196. void Start(const char *cert_file) {
  19197. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19198. SERVER_PRIVATE_KEY_FILE);
  19199. ASSERT_TRUE(server_->is_valid());
  19200. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19201. std::string msg;
  19202. while (ws.read(msg)) {
  19203. ws.send(msg);
  19204. }
  19205. });
  19206. port_ = server_->bind_to_any_port("localhost");
  19207. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19208. server_->wait_until_ready();
  19209. }
  19210. void TearDown() override {
  19211. if (server_) { server_->stop(); }
  19212. if (server_thread_.joinable()) { server_thread_.join(); }
  19213. }
  19214. std::string url() const {
  19215. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19216. }
  19217. std::unique_ptr<SSLServer> server_;
  19218. std::thread server_thread_;
  19219. int port_ = 0;
  19220. };
  19221. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19222. // out and the connection is usable
  19223. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19224. Start(SERVER_CERT2_FILE);
  19225. ws::WebSocketClient client(url());
  19226. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19227. ASSERT_TRUE(client.connect());
  19228. ASSERT_TRUE(client.send("hello"));
  19229. std::string msg;
  19230. EXPECT_EQ(ws::Text, client.read(msg));
  19231. EXPECT_EQ("hello", msg);
  19232. client.close();
  19233. }
  19234. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19235. // while the identity check must still reject "localhost"
  19236. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19237. Start(SERVER_CERT_FILE);
  19238. ws::WebSocketClient client(url());
  19239. client.set_ca_cert_path(SERVER_CERT_FILE);
  19240. auto res = client.connect();
  19241. ASSERT_FALSE(res);
  19242. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19243. EXPECT_EQ(-1, res.status());
  19244. }
  19245. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19246. // disabled: the chain is still checked, only the identity check is skipped
  19247. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19248. Start(SERVER_CERT_FILE);
  19249. ws::WebSocketClient client(url());
  19250. client.set_ca_cert_path(SERVER_CERT_FILE);
  19251. client.enable_server_hostname_verification(false);
  19252. ASSERT_TRUE(client.connect());
  19253. ASSERT_TRUE(client.send("hello"));
  19254. std::string msg;
  19255. EXPECT_EQ(ws::Text, client.read(msg));
  19256. EXPECT_EQ("hello", msg);
  19257. client.close();
  19258. }
  19259. // A CA that did not sign the server certificate fails the chain, even though
  19260. // the name would match
  19261. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19262. Start(SERVER_CERT2_FILE);
  19263. ws::WebSocketClient client(url());
  19264. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19265. ASSERT_FALSE(client.connect());
  19266. }
  19267. // With verification disabled, neither the chain nor the name is checked
  19268. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19269. Start(SERVER_CERT_FILE);
  19270. ws::WebSocketClient client(url());
  19271. client.enable_server_certificate_verification(false);
  19272. ASSERT_TRUE(client.connect());
  19273. ASSERT_TRUE(client.send("hello"));
  19274. std::string msg;
  19275. EXPECT_EQ(ws::Text, client.read(msg));
  19276. EXPECT_EQ("hello", msg);
  19277. client.close();
  19278. }
  19279. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19280. protected:
  19281. void SetUp() override {
  19282. server_ = httplib::detail::make_unique<SSLServer>(
  19283. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19284. ASSERT_TRUE(server_->is_valid());
  19285. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19286. std::string msg;
  19287. while (ws.read(msg)) {
  19288. ws.send(msg);
  19289. }
  19290. });
  19291. port_ = server_->bind_to_any_port("localhost");
  19292. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19293. server_->wait_until_ready();
  19294. }
  19295. void TearDown() override {
  19296. server_->stop();
  19297. if (server_thread_.joinable()) { server_thread_.join(); }
  19298. }
  19299. std::string url() const {
  19300. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19301. }
  19302. void ConnectWithClientCert(const std::string &client_cert_file,
  19303. const std::string &client_private_key_file,
  19304. const char *private_key_password) {
  19305. std::string cert_pem, key_pem;
  19306. read_file(client_cert_file, cert_pem);
  19307. read_file(client_private_key_file, key_pem);
  19308. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19309. key_pem.c_str(), key_pem.size(),
  19310. private_key_password};
  19311. ws::WebSocketClient client(url(), pem);
  19312. ASSERT_TRUE(client.is_valid());
  19313. client.enable_server_certificate_verification(false);
  19314. ASSERT_TRUE(client.connect());
  19315. ASSERT_TRUE(client.send("hello"));
  19316. std::string msg;
  19317. EXPECT_EQ(ws::Text, client.read(msg));
  19318. EXPECT_EQ("hello", msg);
  19319. client.close();
  19320. }
  19321. std::unique_ptr<SSLServer> server_;
  19322. std::thread server_thread_;
  19323. int port_ = 0;
  19324. };
  19325. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19326. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19327. }
  19328. // Control for the tests above: the fixture's server really does require a
  19329. // client certificate, so it is the PEM the constructor installed that decides
  19330. // the outcome.
  19331. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19332. ws::WebSocketClient client(url());
  19333. ASSERT_TRUE(client.is_valid());
  19334. client.enable_server_certificate_verification(false);
  19335. EXPECT_FALSE(client.connect());
  19336. }
  19337. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19338. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19339. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19340. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19341. }
  19342. #endif
  19343. #if !defined(_WIN32)
  19344. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19345. auto secret_dir = std::string("./symlink_test_secret");
  19346. auto served_dir = std::string("./symlink_test_served");
  19347. auto secret_file = secret_dir + "/secret.txt";
  19348. auto symlink_path = served_dir + "/escape";
  19349. // Setup: create directories and files
  19350. mkdir(secret_dir.c_str(), 0755);
  19351. mkdir(served_dir.c_str(), 0755);
  19352. {
  19353. std::ofstream ofs(secret_file);
  19354. ofs << "SECRET_DATA";
  19355. }
  19356. // Create symlink using absolute path so it resolves correctly
  19357. #ifdef PATH_MAX
  19358. char abs_secret[PATH_MAX];
  19359. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19360. #else
  19361. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19362. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19363. ASSERT_NE(nullptr, abs_secret);
  19364. #endif
  19365. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19366. auto se = detail::scope_exit([&] {
  19367. unlink(symlink_path.c_str());
  19368. unlink(secret_file.c_str());
  19369. rmdir(served_dir.c_str());
  19370. rmdir(secret_dir.c_str());
  19371. });
  19372. Server svr;
  19373. svr.set_mount_point("/", served_dir);
  19374. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19375. auto se2 = detail::scope_exit([&] {
  19376. svr.stop();
  19377. listen_thread.join();
  19378. });
  19379. svr.wait_until_ready();
  19380. Client cli("localhost", PORT);
  19381. // Symlink pointing outside base dir should be blocked
  19382. auto res = cli.Get("/escape/secret.txt");
  19383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19384. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19385. }
  19386. #endif
  19387. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19388. // A GET request with Content-Length to a static file handler must have its
  19389. // body drained before the keep-alive connection is reused. Otherwise the
  19390. // unread body bytes are interpreted as the next HTTP request.
  19391. //
  19392. // The body is sent AFTER receiving the first response (as in the original
  19393. // PoC) so that the stream_line_reader cannot buffer it together with the
  19394. // headers of the first request.
  19395. Server svr;
  19396. svr.set_mount_point("/", "./www");
  19397. std::atomic<int> smuggled_count(0);
  19398. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19399. smuggled_count++;
  19400. res.set_content("oops", "text/plain");
  19401. });
  19402. auto port = svr.bind_to_any_port("localhost");
  19403. thread t = thread([&] { svr.listen_after_bind(); });
  19404. auto se = detail::scope_exit([&] {
  19405. svr.stop();
  19406. t.join();
  19407. });
  19408. svr.wait_until_ready();
  19409. auto error = Error::Success;
  19410. auto sock = detail::create_client_socket(
  19411. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19412. /*connection_timeout_sec=*/2, 0,
  19413. /*read_timeout_sec=*/2, 0,
  19414. /*write_timeout_sec=*/2, 0, std::string(), error);
  19415. ASSERT_NE(INVALID_SOCKET, sock);
  19416. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19417. // The "smuggled" request will be sent as the body of the outer GET
  19418. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19419. "Host: localhost\r\n"
  19420. "Connection: close\r\n"
  19421. "\r\n";
  19422. // Step 1: Send only the outer request headers (no body yet)
  19423. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19424. "Host: localhost\r\n"
  19425. "Content-Length: " +
  19426. std::to_string(smuggled.size()) +
  19427. "\r\n"
  19428. "\r\n";
  19429. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19430. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19431. // Step 2: Read the first response (server serves file without reading body)
  19432. std::string first_response;
  19433. char buf[4096];
  19434. for (;;) {
  19435. auto n = recv(sock, buf, sizeof(buf), 0);
  19436. if (n <= 0) break;
  19437. first_response.append(buf, static_cast<size_t>(n));
  19438. // Stop once we have a complete response (headers + body)
  19439. auto hdr_end = first_response.find("\r\n\r\n");
  19440. if (hdr_end != std::string::npos) {
  19441. // Check for Content-Length to know when the body is complete
  19442. auto cl_pos = first_response.find("Content-Length:");
  19443. if (cl_pos != std::string::npos) {
  19444. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19445. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19446. auto cl = std::stoul(
  19447. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19448. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19449. } else {
  19450. break; // No Content-Length, assume headers-only response
  19451. }
  19452. }
  19453. }
  19454. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19455. // Step 3: Now send the body, which looks like a new HTTP request.
  19456. // On a vulnerable server the keep-alive loop reads this as a second request.
  19457. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19458. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19459. // Step 4: Try to read a second response (should NOT exist after fix)
  19460. std::string second_response;
  19461. for (;;) {
  19462. auto n = recv(sock, buf, sizeof(buf), 0);
  19463. if (n <= 0) break;
  19464. second_response.append(buf, static_cast<size_t>(n));
  19465. }
  19466. // The smuggled request must NOT have been processed
  19467. EXPECT_EQ(0, smuggled_count.load());
  19468. }
  19469. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19470. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19471. // must be rejected with 400 Bad Request.
  19472. Server svr;
  19473. svr.Post("/test", [&](const Request &, Response &res) {
  19474. res.set_content("ok", "text/plain");
  19475. });
  19476. thread t = thread([&] { svr.listen(HOST, PORT); });
  19477. auto se = detail::scope_exit([&] {
  19478. svr.stop();
  19479. t.join();
  19480. ASSERT_FALSE(svr.is_running());
  19481. });
  19482. svr.wait_until_ready();
  19483. // Exact "chunked"
  19484. {
  19485. auto req = "POST /test HTTP/1.1\r\n"
  19486. "Host: localhost\r\n"
  19487. "Content-Length: 5\r\n"
  19488. "Transfer-Encoding: chunked\r\n"
  19489. "Connection: close\r\n"
  19490. "\r\n"
  19491. "hello";
  19492. std::string response;
  19493. ASSERT_TRUE(send_request(1, req, &response));
  19494. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19495. response.substr(0, response.find("\r\n")));
  19496. }
  19497. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19498. {
  19499. auto req = "POST /test HTTP/1.1\r\n"
  19500. "Host: localhost\r\n"
  19501. "Content-Length: 5\r\n"
  19502. "Transfer-Encoding: gzip, chunked\r\n"
  19503. "Connection: close\r\n"
  19504. "\r\n"
  19505. "hello";
  19506. std::string response;
  19507. ASSERT_TRUE(send_request(1, req, &response));
  19508. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19509. response.substr(0, response.find("\r\n")));
  19510. }
  19511. }
  19512. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19513. Server svr;
  19514. svr.Post("/test", [&](const Request &, Response &res) {
  19515. res.set_content("ok", "text/plain");
  19516. });
  19517. thread t = thread([&] { svr.listen(HOST, PORT); });
  19518. auto se = detail::scope_exit([&] {
  19519. svr.stop();
  19520. t.join();
  19521. ASSERT_FALSE(svr.is_running());
  19522. });
  19523. svr.wait_until_ready();
  19524. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19525. // length cannot be determined, so the server must answer 400 and close
  19526. // rather than treat the request as bodyless and leave the body in the
  19527. // socket for the next request to pick up.
  19528. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19529. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19530. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19531. std::string response;
  19532. ASSERT_TRUE(send_request(1, req, &response));
  19533. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19534. response.substr(0, response.find("\r\n")))
  19535. << transfer_encoding;
  19536. }
  19537. // RFC 9110 5.3: the codings may also be split across several
  19538. // Transfer-Encoding lines, which combine in the order they were received.
  19539. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19540. // just like the single-line "chunked, gzip" above.
  19541. {
  19542. auto req = "POST /test HTTP/1.1\r\n"
  19543. "Host: localhost\r\n"
  19544. "Transfer-Encoding: chunked\r\n"
  19545. "Transfer-Encoding: gzip\r\n"
  19546. "\r\n"
  19547. "0\r\n\r\n";
  19548. std::string response;
  19549. ASSERT_TRUE(send_request(1, req, &response));
  19550. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19551. response.substr(0, response.find("\r\n")));
  19552. }
  19553. // A sequence ending in chunked stays valid.
  19554. auto req = "POST /test HTTP/1.1\r\n"
  19555. "Host: localhost\r\n"
  19556. "Transfer-Encoding: gzip, chunked\r\n"
  19557. "Connection: close\r\n"
  19558. "\r\n"
  19559. "0\r\n\r\n";
  19560. std::string response;
  19561. ASSERT_TRUE(send_request(1, req, &response));
  19562. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19563. // ...including when it is spread over several lines.
  19564. auto split_req = "POST /test HTTP/1.1\r\n"
  19565. "Host: localhost\r\n"
  19566. "Transfer-Encoding: gzip\r\n"
  19567. "Transfer-Encoding: chunked\r\n"
  19568. "Connection: close\r\n"
  19569. "\r\n"
  19570. "0\r\n\r\n";
  19571. std::string split_response;
  19572. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19573. EXPECT_EQ("HTTP/1.1 200 OK",
  19574. split_response.substr(0, split_response.find("\r\n")));
  19575. }
  19576. // Regression for issue #2450: a DELETE without Content-Length on a
  19577. // keep-alive connection must not let the post-response drain consume the
  19578. // next request's bytes.
  19579. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19580. Server svr;
  19581. std::atomic<int> delete_count(0);
  19582. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19583. delete_count++;
  19584. res.status = StatusCode::NoContent_204;
  19585. });
  19586. auto port = svr.bind_to_any_port(HOST);
  19587. thread t = thread([&] { svr.listen_after_bind(); });
  19588. auto se = detail::scope_exit([&] {
  19589. svr.stop();
  19590. t.join();
  19591. });
  19592. svr.wait_until_ready();
  19593. auto error = Error::Success;
  19594. auto sock = detail::create_client_socket(
  19595. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19596. /*connection_timeout_sec=*/2, 0,
  19597. /*read_timeout_sec=*/2, 0,
  19598. /*write_timeout_sec=*/2, 0, std::string(), error);
  19599. ASSERT_NE(INVALID_SOCKET, sock);
  19600. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19601. auto send_request_and_read_response = [&](const std::string &req,
  19602. std::string &out) -> bool {
  19603. auto sent = send(sock, req.data(), req.size(), 0);
  19604. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19605. char buf[4096];
  19606. for (;;) {
  19607. auto n = recv(sock, buf, sizeof(buf), 0);
  19608. if (n <= 0) { return !out.empty(); }
  19609. out.append(buf, static_cast<size_t>(n));
  19610. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19611. }
  19612. };
  19613. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19614. "Host: localhost\r\n"
  19615. "\r\n";
  19616. std::string resp1;
  19617. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19618. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19619. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19620. "Host: localhost\r\n"
  19621. "Connection: close\r\n"
  19622. "\r\n";
  19623. std::string resp2;
  19624. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19625. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19626. EXPECT_EQ(2, delete_count.load());
  19627. }
  19628. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19629. Server svr;
  19630. svr.Post("/ingest", [&](const Request &, Response &res,
  19631. const ContentReader &content_reader) {
  19632. auto consumed = content_reader([](const char *, size_t) { return false; });
  19633. EXPECT_FALSE(consumed);
  19634. res.status = StatusCode::Conflict_409;
  19635. res.set_header("Connection", "close");
  19636. });
  19637. auto port = svr.bind_to_any_port(HOST);
  19638. thread t = thread([&] { svr.listen_after_bind(); });
  19639. auto se = detail::scope_exit([&] {
  19640. svr.stop();
  19641. t.join();
  19642. });
  19643. svr.wait_until_ready();
  19644. auto error = Error::Success;
  19645. auto sock = detail::create_client_socket(
  19646. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19647. /*connection_timeout_sec=*/2, 0,
  19648. /*read_timeout_sec=*/1, 0,
  19649. /*write_timeout_sec=*/2, 0, std::string(), error);
  19650. ASSERT_NE(INVALID_SOCKET, sock);
  19651. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19652. std::string request = "POST /ingest HTTP/1.1\r\n"
  19653. "Host: localhost\r\n"
  19654. "Transfer-Encoding: chunked\r\n"
  19655. "\r\n"
  19656. "4\r\n"
  19657. "data\r\n";
  19658. auto sent = send(sock, request.data(), request.size(), 0);
  19659. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19660. std::string response;
  19661. ssize_t received = 0;
  19662. do {
  19663. char buf[4096];
  19664. received = recv(sock, buf, sizeof(buf), 0);
  19665. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19666. } while (received > 0);
  19667. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19668. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19669. EXPECT_EQ(0, received);
  19670. }
  19671. namespace no_proxy_test {
  19672. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19673. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19674. // calling listen().
  19675. class ScopedServer {
  19676. public:
  19677. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19678. ~ScopedServer() {
  19679. svr_.stop();
  19680. if (th_.joinable()) { th_.join(); }
  19681. }
  19682. Server &svr() { return svr_; }
  19683. int port() const { return port_; }
  19684. void listen() {
  19685. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19686. svr_.wait_until_ready();
  19687. }
  19688. private:
  19689. Server svr_;
  19690. std::thread th_;
  19691. int port_ = 0;
  19692. };
  19693. class ProxyAndTargetServers {
  19694. public:
  19695. ProxyAndTargetServers() {
  19696. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19697. proxy_hits_++;
  19698. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19699. res.set_content("via-proxy", "text/plain");
  19700. });
  19701. target_.Get(".*", [this](const Request &req, Response &res) {
  19702. target_hits_++;
  19703. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19704. res.set_content("direct", "text/plain");
  19705. });
  19706. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19707. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19708. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19709. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19710. proxy_mock_.wait_until_ready();
  19711. target_.wait_until_ready();
  19712. }
  19713. ~ProxyAndTargetServers() {
  19714. proxy_mock_.stop();
  19715. target_.stop();
  19716. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19717. if (target_thread_.joinable()) { target_thread_.join(); }
  19718. }
  19719. Server &proxy_mock() { return proxy_mock_; }
  19720. Server &target() { return target_; }
  19721. int proxy_port() const { return proxy_port_; }
  19722. int target_port() const { return target_port_; }
  19723. int proxy_hits() const { return proxy_hits_.load(); }
  19724. int target_hits() const { return target_hits_.load(); }
  19725. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19726. void reset_counters() {
  19727. proxy_hits_ = 0;
  19728. target_hits_ = 0;
  19729. last_had_proxy_authz_ = false;
  19730. }
  19731. private:
  19732. Server proxy_mock_;
  19733. Server target_;
  19734. std::thread proxy_thread_;
  19735. std::thread target_thread_;
  19736. int proxy_port_ = 0;
  19737. int target_port_ = 0;
  19738. std::atomic<int> proxy_hits_{0};
  19739. std::atomic<int> target_hits_{0};
  19740. std::atomic<bool> last_had_proxy_authz_{false};
  19741. };
  19742. inline std::unique_ptr<Client> make_client(const std::string &host,
  19743. ProxyAndTargetServers &s) {
  19744. auto cli = detail::make_unique<Client>(host, s.target_port());
  19745. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19746. cli->set_proxy("127.0.0.1", s.proxy_port());
  19747. return cli;
  19748. }
  19749. } // namespace no_proxy_test
  19750. using no_proxy_test::make_client;
  19751. using no_proxy_test::ProxyAndTargetServers;
  19752. TEST(NoProxyTest, ExactHostnameBypasses) {
  19753. ProxyAndTargetServers s;
  19754. auto cli = make_client("example.com", s);
  19755. cli->set_no_proxy({"example.com"});
  19756. auto res = cli->Get("/");
  19757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19758. EXPECT_EQ(0, s.proxy_hits());
  19759. EXPECT_EQ(1, s.target_hits());
  19760. }
  19761. TEST(NoProxyTest, SubdomainBypasses) {
  19762. ProxyAndTargetServers s;
  19763. auto cli = make_client("foo.example.com", s);
  19764. cli->set_no_proxy({"example.com"});
  19765. auto res = cli->Get("/");
  19766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19767. EXPECT_EQ(0, s.proxy_hits());
  19768. EXPECT_EQ(1, s.target_hits());
  19769. }
  19770. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19771. // Regression guard: "evilexample.com" must not be considered a subdomain
  19772. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19773. // check would let traffic bypass the proxy and leak credentials direct
  19774. // to the attacker host.
  19775. ProxyAndTargetServers s;
  19776. auto cli = make_client("evilexample.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_GE(s.proxy_hits(), 1);
  19781. EXPECT_EQ(0, s.target_hits());
  19782. }
  19783. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19784. ProxyAndTargetServers s;
  19785. auto cli = make_client("example.com.evil.com", s);
  19786. cli->set_no_proxy({"example.com"});
  19787. auto res = cli->Get("/");
  19788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19789. EXPECT_GE(s.proxy_hits(), 1);
  19790. EXPECT_EQ(0, s.target_hits());
  19791. }
  19792. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19793. ProxyAndTargetServers s;
  19794. auto cli = make_client("example.com", s);
  19795. cli->set_no_proxy({".example.com"});
  19796. auto res = cli->Get("/");
  19797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19798. EXPECT_EQ(0, s.proxy_hits());
  19799. EXPECT_EQ(1, s.target_hits());
  19800. }
  19801. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19802. ProxyAndTargetServers s;
  19803. auto cli = make_client("Example.COM", s);
  19804. cli->set_no_proxy({"EXAMPLE.com"});
  19805. auto res = cli->Get("/");
  19806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19807. EXPECT_EQ(0, s.proxy_hits());
  19808. EXPECT_EQ(1, s.target_hits());
  19809. }
  19810. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19811. ProxyAndTargetServers s;
  19812. auto cli = make_client("example.com.", s);
  19813. cli->set_no_proxy({"example.com"});
  19814. auto res = cli->Get("/");
  19815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19816. EXPECT_EQ(0, s.proxy_hits());
  19817. EXPECT_EQ(1, s.target_hits());
  19818. }
  19819. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19820. // Trailing dots must be normalized on BOTH sides — host and entry.
  19821. // An implementation that only strips the host-side trailing dot would
  19822. // fail to match host "example.com" against entry "example.com." because
  19823. // a literal substring search would compare 11 chars against 12.
  19824. ProxyAndTargetServers s;
  19825. auto cli = make_client("example.com", s);
  19826. cli->set_no_proxy({"example.com."});
  19827. auto res = cli->Get("/");
  19828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19829. EXPECT_EQ(0, s.proxy_hits());
  19830. EXPECT_EQ(1, s.target_hits());
  19831. }
  19832. TEST(NoProxyTest, WildcardBypassesEverything) {
  19833. ProxyAndTargetServers s;
  19834. auto cli = make_client("anything.invalid.test", s);
  19835. cli->set_no_proxy({"*"});
  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, IPv4LiteralExactMatch) {
  19842. ProxyAndTargetServers s;
  19843. Client cli("127.0.0.1", s.target_port());
  19844. cli.set_proxy("127.0.0.1", s.proxy_port());
  19845. cli.set_no_proxy({"127.0.0.1"});
  19846. auto res = cli.Get("/");
  19847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19848. EXPECT_EQ(0, s.proxy_hits());
  19849. EXPECT_EQ(1, s.target_hits());
  19850. }
  19851. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19852. ProxyAndTargetServers s;
  19853. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19854. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19855. cli.set_proxy("127.0.0.1", s.proxy_port());
  19856. cli.set_no_proxy({"::1"});
  19857. auto res = cli.Get("/");
  19858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19859. EXPECT_EQ(0, s.proxy_hits());
  19860. EXPECT_EQ(1, s.target_hits());
  19861. }
  19862. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19863. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19864. // must still be recognized as IPv6 for CIDR matching. Implementations
  19865. // that detect IPv6 only when the host begins with '[' would parse the
  19866. // host as a hostname and miss the match.
  19867. ProxyAndTargetServers s;
  19868. Client cli("fe80::1", s.target_port());
  19869. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19870. cli.set_proxy("127.0.0.1", s.proxy_port());
  19871. cli.set_no_proxy({"fe80::/10"});
  19872. auto res = cli.Get("/");
  19873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19874. EXPECT_EQ(0, s.proxy_hits());
  19875. EXPECT_EQ(1, s.target_hits());
  19876. }
  19877. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19878. ProxyAndTargetServers s;
  19879. Client cli("::1", s.target_port());
  19880. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19881. cli.set_proxy("127.0.0.1", s.proxy_port());
  19882. cli.set_no_proxy({"[::1]"});
  19883. auto res = cli.Get("/");
  19884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19885. EXPECT_EQ(0, s.proxy_hits());
  19886. EXPECT_EQ(1, s.target_hits());
  19887. }
  19888. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19889. ProxyAndTargetServers s;
  19890. Client cli("fe80::1", s.target_port());
  19891. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19892. cli.set_proxy("127.0.0.1", s.proxy_port());
  19893. cli.set_no_proxy({"[fe80::]/10"});
  19894. auto res = cli.Get("/");
  19895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19896. EXPECT_EQ(0, s.proxy_hits());
  19897. EXPECT_EQ(1, s.target_hits());
  19898. }
  19899. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19900. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19901. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19902. // tricks via address-family conversion.
  19903. ProxyAndTargetServers s;
  19904. Client cli("::ffff:127.0.0.1", s.target_port());
  19905. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19906. cli.set_proxy("127.0.0.1", s.proxy_port());
  19907. cli.set_no_proxy({"127.0.0.1"});
  19908. auto res = cli.Get("/");
  19909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19910. EXPECT_GE(s.proxy_hits(), 1);
  19911. EXPECT_EQ(0, s.target_hits());
  19912. }
  19913. TEST(NoProxyTest, IPv4CidrMatch) {
  19914. ProxyAndTargetServers s;
  19915. Client cli("127.0.0.1", s.target_port());
  19916. cli.set_proxy("127.0.0.1", s.proxy_port());
  19917. cli.set_no_proxy({"127.0.0.0/8"});
  19918. auto res = cli.Get("/");
  19919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19920. EXPECT_EQ(0, s.proxy_hits());
  19921. EXPECT_EQ(1, s.target_hits());
  19922. }
  19923. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19924. ProxyAndTargetServers s;
  19925. Client cli("127.0.0.1", s.target_port());
  19926. cli.set_proxy("127.0.0.1", s.proxy_port());
  19927. cli.set_no_proxy({"10.0.0.0/8"});
  19928. auto res = cli.Get("/");
  19929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19930. EXPECT_GE(s.proxy_hits(), 1);
  19931. EXPECT_EQ(0, s.target_hits());
  19932. }
  19933. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19934. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19935. // IPv4 target matches.
  19936. ProxyAndTargetServers s;
  19937. Client cli("127.0.0.1", s.target_port());
  19938. cli.set_proxy("127.0.0.1", s.proxy_port());
  19939. cli.set_no_proxy({"0.0.0.0/0"});
  19940. auto res = cli.Get("/");
  19941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19942. EXPECT_EQ(0, s.proxy_hits());
  19943. EXPECT_EQ(1, s.target_hits());
  19944. }
  19945. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19946. ProxyAndTargetServers s;
  19947. Client cli("127.0.0.1", s.target_port());
  19948. cli.set_proxy("127.0.0.1", s.proxy_port());
  19949. cli.set_no_proxy({"127.0.0.1"});
  19950. auto res = cli.Get("/");
  19951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19952. EXPECT_EQ(0, s.proxy_hits());
  19953. EXPECT_EQ(1, s.target_hits());
  19954. }
  19955. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19956. ProxyAndTargetServers s;
  19957. Client cli("127.0.0.1", s.target_port());
  19958. cli.set_proxy("127.0.0.1", s.proxy_port());
  19959. cli.set_no_proxy({"127.0.0.0/33"});
  19960. auto res = cli.Get("/");
  19961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19962. EXPECT_GE(s.proxy_hits(), 1);
  19963. EXPECT_EQ(0, s.target_hits());
  19964. }
  19965. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19966. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19967. ProxyAndTargetServers s;
  19968. Client cli("127.0.0.1", s.target_port());
  19969. cli.set_proxy("127.0.0.1", s.proxy_port());
  19970. cli.set_no_proxy({"127.0.0.1/"});
  19971. auto res = cli.Get("/");
  19972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19973. EXPECT_GE(s.proxy_hits(), 1);
  19974. EXPECT_EQ(0, s.target_hits());
  19975. }
  19976. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19977. ProxyAndTargetServers s;
  19978. auto cli = make_client("internal.corp", s);
  19979. cli->set_proxy_basic_auth("u", "p");
  19980. cli->set_no_proxy({"internal.corp"});
  19981. auto res = cli->Get("/");
  19982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19983. EXPECT_EQ(1, s.target_hits());
  19984. EXPECT_EQ(0, s.proxy_hits());
  19985. EXPECT_FALSE(s.last_had_proxy_authz())
  19986. << "Proxy-Authorization must not be sent direct to the target";
  19987. }
  19988. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19989. ProxyAndTargetServers s;
  19990. auto cli = make_client("public.example", s);
  19991. cli->set_proxy_basic_auth("u", "p");
  19992. cli->set_no_proxy({"internal.corp"}); // does not match
  19993. auto res = cli->Get("/");
  19994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19995. EXPECT_GE(s.proxy_hits(), 1);
  19996. EXPECT_TRUE(s.last_had_proxy_authz());
  19997. }
  19998. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19999. ProxyAndTargetServers s;
  20000. auto cli = make_client("anything.test", s);
  20001. auto res = cli->Get("/");
  20002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20003. EXPECT_GE(s.proxy_hits(), 1);
  20004. EXPECT_EQ(0, s.target_hits());
  20005. }
  20006. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20007. ProxyAndTargetServers s;
  20008. auto cli = make_client("example.com", s);
  20009. cli->set_no_proxy({"example.com:8080"});
  20010. auto res = cli->Get("/");
  20011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20012. EXPECT_GE(s.proxy_hits(), 1);
  20013. EXPECT_EQ(0, s.target_hits());
  20014. }
  20015. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20016. ProxyAndTargetServers s;
  20017. auto cli = make_client("anything.test", s);
  20018. cli->set_no_proxy({"", " ", "\t"});
  20019. auto res = cli->Get("/");
  20020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20021. EXPECT_GE(s.proxy_hits(), 1);
  20022. EXPECT_EQ(0, s.target_hits());
  20023. }
  20024. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20025. // An entry with leading/trailing whitespace must still match — env-style
  20026. // values are commonly pasted with stray spaces and an implementation
  20027. // that feeds the raw token directly to inet_pton would fail to match
  20028. // valid CIDRs because of the spaces.
  20029. ProxyAndTargetServers s;
  20030. Client cli("127.0.0.1", s.target_port());
  20031. cli.set_proxy("127.0.0.1", s.proxy_port());
  20032. cli.set_no_proxy({" 127.0.0.0/8 "});
  20033. auto res = cli.Get("/");
  20034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20035. EXPECT_EQ(0, s.proxy_hits());
  20036. EXPECT_EQ(1, s.target_hits());
  20037. }
  20038. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20039. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20040. // go direct and must NOT carry Proxy-Authorization.
  20041. std::atomic<int> proxy_hits{0};
  20042. std::atomic<int> target_hits{0};
  20043. std::atomic<bool> target_saw_authz{false};
  20044. no_proxy_test::ScopedServer proxy_mock, target;
  20045. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20046. proxy_hits++;
  20047. res.status = 302;
  20048. res.set_header("Location", "http://127.0.0.1:" +
  20049. std::to_string(target.port()) + "/landed");
  20050. });
  20051. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20052. target_hits++;
  20053. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20054. res.set_content("direct", "text/plain");
  20055. });
  20056. proxy_mock.listen();
  20057. target.listen();
  20058. Client cli("public.example", target.port());
  20059. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20060. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20061. cli.set_proxy_basic_auth("u", "p");
  20062. cli.set_no_proxy({"127.0.0.1"});
  20063. cli.set_follow_location(true);
  20064. auto res = cli.Get("/redir");
  20065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20066. EXPECT_GE(proxy_hits.load(), 1);
  20067. EXPECT_GE(target_hits.load(), 1);
  20068. EXPECT_FALSE(target_saw_authz.load());
  20069. }
  20070. #ifdef CPPHTTPLIB_SSL_ENABLED
  20071. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20072. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20073. // proxy creds would be sent to the (possibly hostile) origin.
  20074. std::atomic<int> target_hits{0};
  20075. std::atomic<bool> target_saw_proxy_authz{false};
  20076. no_proxy_test::ScopedServer target;
  20077. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20078. target_hits++;
  20079. if (req.has_header("Proxy-Authorization")) {
  20080. target_saw_proxy_authz = true;
  20081. }
  20082. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20083. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20084. "nonce=\"abc\", algorithm=MD5");
  20085. });
  20086. target.listen();
  20087. // The proxy address is set to the target's port: the bypass MUST kick in;
  20088. // if it doesn't, the test still routes "via proxy" to the same server and
  20089. // the Proxy-Authorization assertion below catches the leak.
  20090. Client cli("evil.example", target.port());
  20091. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20092. cli.set_proxy("127.0.0.1", target.port());
  20093. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20094. cli.set_no_proxy({"evil.example"});
  20095. auto res = cli.Get("/x");
  20096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20097. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20098. EXPECT_EQ(1, target_hits.load());
  20099. EXPECT_FALSE(target_saw_proxy_authz.load());
  20100. }
  20101. #endif
  20102. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20103. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20104. std::atomic<int> proxy_hits{0};
  20105. std::atomic<int> bypass_hits{0};
  20106. std::atomic<bool> proxy_saw_c_url{false};
  20107. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20108. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20109. proxy_hits++;
  20110. if (req.path.find("/start") != std::string::npos) {
  20111. res.status = 302;
  20112. res.set_header("Location", "http://127.0.0.1:" +
  20113. std::to_string(bypass_server.port()) +
  20114. "/middle");
  20115. return;
  20116. }
  20117. if (req.path.find("/end") != std::string::npos) {
  20118. proxy_saw_c_url = true;
  20119. res.set_content("c-via-proxy", "text/plain");
  20120. return;
  20121. }
  20122. res.set_content("unexpected", "text/plain");
  20123. });
  20124. // public.example's "advertised" port is arbitrary (the request never lands
  20125. // there — it goes through the proxy), but use a dynamic value to stay
  20126. // friendly with sharded parallel runs.
  20127. int public_port = bypass_server.port();
  20128. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20129. bypass_hits++;
  20130. res.status = 302;
  20131. res.set_header("Location", "http://public.example:" +
  20132. std::to_string(public_port) + "/end");
  20133. });
  20134. proxy_mock.listen();
  20135. bypass_server.listen();
  20136. Client cli("public.example", public_port);
  20137. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20138. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20139. cli.set_no_proxy({"127.0.0.1"});
  20140. cli.set_follow_location(true);
  20141. auto res = cli.Get("/start");
  20142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20143. EXPECT_EQ(StatusCode::OK_200, res->status);
  20144. EXPECT_EQ("c-via-proxy", res->body);
  20145. EXPECT_GE(proxy_hits.load(), 2);
  20146. EXPECT_GE(bypass_hits.load(), 1);
  20147. EXPECT_TRUE(proxy_saw_c_url.load());
  20148. }
  20149. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20150. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20151. // request reconnects to the correct endpoint.
  20152. std::atomic<int> proxy_hits{0};
  20153. std::atomic<int> target_hits{0};
  20154. no_proxy_test::ScopedServer proxy_mock, target;
  20155. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20156. proxy_hits++;
  20157. res.set_content("via-proxy", "text/plain");
  20158. });
  20159. target.svr().Get(".*", [&](const Request &, Response &res) {
  20160. target_hits++;
  20161. res.set_content("direct", "text/plain");
  20162. });
  20163. proxy_mock.listen();
  20164. target.listen();
  20165. Client cli("public.example", target.port());
  20166. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20167. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20168. cli.set_keep_alive(true);
  20169. auto res1 = cli.Get("/a");
  20170. ASSERT_TRUE(res1);
  20171. EXPECT_EQ("via-proxy", res1->body);
  20172. EXPECT_EQ(1, proxy_hits.load());
  20173. EXPECT_EQ(0, target_hits.load());
  20174. cli.set_no_proxy({"public.example"});
  20175. auto res2 = cli.Get("/b");
  20176. ASSERT_TRUE(res2);
  20177. EXPECT_EQ("direct", res2->body);
  20178. EXPECT_EQ(1, proxy_hits.load());
  20179. EXPECT_EQ(1, target_hits.load());
  20180. }
  20181. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20182. namespace proxy_tunnel_test {
  20183. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20184. class ScopedSSLServer {
  20185. public:
  20186. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20187. port_ = svr_.bind_to_any_port("127.0.0.1");
  20188. }
  20189. ~ScopedSSLServer() {
  20190. svr_.stop();
  20191. if (th_.joinable()) { th_.join(); }
  20192. }
  20193. SSLServer &svr() { return svr_; }
  20194. int port() const { return port_; }
  20195. void listen() {
  20196. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20197. svr_.wait_until_ready();
  20198. }
  20199. private:
  20200. SSLServer svr_;
  20201. std::thread th_;
  20202. int port_ = 0;
  20203. };
  20204. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20205. class ScopedConnectProxy {
  20206. public:
  20207. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20208. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20209. if (listen_fd_ < 0) { return; }
  20210. int yes = 1;
  20211. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20212. sockaddr_in a{};
  20213. a.sin_family = AF_INET;
  20214. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20215. a.sin_port = 0;
  20216. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20217. return;
  20218. }
  20219. socklen_t alen = sizeof(a);
  20220. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20221. 0) {
  20222. return;
  20223. }
  20224. port_ = ntohs(a.sin_port);
  20225. if (::listen(listen_fd_, 1) != 0) { return; }
  20226. th_ = std::thread([this] { run(); });
  20227. }
  20228. ~ScopedConnectProxy() {
  20229. stop_ = true;
  20230. if (listen_fd_ >= 0) {
  20231. ::shutdown(listen_fd_, SHUT_RDWR);
  20232. ::close(listen_fd_);
  20233. }
  20234. if (th_.joinable()) { th_.join(); }
  20235. }
  20236. int port() const { return port_; }
  20237. int connect_hits() const { return connect_hits_.load(); }
  20238. private:
  20239. void run() {
  20240. while (!stop_.load()) {
  20241. fd_set rfds;
  20242. FD_ZERO(&rfds);
  20243. FD_SET(listen_fd_, &rfds);
  20244. timeval tv{0, 100 * 1000};
  20245. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20246. if (sel <= 0) { continue; }
  20247. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20248. if (client_fd < 0) { continue; }
  20249. std::string req;
  20250. char buf[2048];
  20251. while (req.find("\r\n\r\n") == std::string::npos) {
  20252. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20253. if (n <= 0) { break; }
  20254. req.append(buf, static_cast<size_t>(n));
  20255. }
  20256. if (req.compare(0, 7, "CONNECT") != 0) {
  20257. ::close(client_fd);
  20258. continue;
  20259. }
  20260. connect_hits_++;
  20261. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20262. ::send(client_fd, ok, std::strlen(ok), 0);
  20263. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20264. sockaddr_in o{};
  20265. o.sin_family = AF_INET;
  20266. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20267. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20268. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20269. 0) {
  20270. ::close(client_fd);
  20271. ::close(origin_fd);
  20272. continue;
  20273. }
  20274. auto forward = [](int from, int to) {
  20275. char b[8192];
  20276. for (;;) {
  20277. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20278. if (n <= 0) { break; }
  20279. ssize_t off = 0;
  20280. while (off < n) {
  20281. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20282. if (s <= 0) {
  20283. off = n;
  20284. break;
  20285. }
  20286. off += s;
  20287. }
  20288. }
  20289. ::shutdown(to, SHUT_WR);
  20290. };
  20291. std::thread t1([&] { forward(client_fd, origin_fd); });
  20292. std::thread t2([&] { forward(origin_fd, client_fd); });
  20293. t1.join();
  20294. t2.join();
  20295. ::close(client_fd);
  20296. ::close(origin_fd);
  20297. }
  20298. }
  20299. int forward_port_ = -1;
  20300. int listen_fd_ = -1;
  20301. int port_ = 0;
  20302. std::thread th_;
  20303. std::atomic<bool> stop_{false};
  20304. std::atomic<int> connect_hits_{0};
  20305. };
  20306. } // namespace proxy_tunnel_test
  20307. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20308. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20309. // retry; otherwise proxy creds would be sent to the origin.
  20310. std::atomic<int> origin_hits{0};
  20311. std::atomic<bool> origin_saw_proxy_authz{false};
  20312. proxy_tunnel_test::ScopedSSLServer origin;
  20313. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20314. origin_hits++;
  20315. if (req.has_header("Proxy-Authorization")) {
  20316. origin_saw_proxy_authz = true;
  20317. }
  20318. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20319. res.set_header("Proxy-Authenticate",
  20320. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20321. "algorithm=MD5");
  20322. });
  20323. origin.listen();
  20324. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20325. ASSERT_NE(0, proxy.port());
  20326. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20327. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20328. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20329. // and answer with its own status, making this test flaky.
  20330. SSLClient cli("127.0.0.1", origin.port());
  20331. cli.enable_server_certificate_verification(false);
  20332. cli.set_proxy("127.0.0.1", proxy.port());
  20333. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20334. auto res = cli.Get("/x");
  20335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20336. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20337. EXPECT_EQ(1, origin_hits.load());
  20338. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20339. EXPECT_EQ(1, proxy.connect_hits());
  20340. }
  20341. #endif