1
0

test.cc 740 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138
  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(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1358. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1359. // to depend on the standard library (libstdc++ handed back duplicates in
  1360. // reverse insertion order, libc++ in insertion order).
  1361. Request req;
  1362. req.set_header("Accept-Encoding", "gzip");
  1363. req.set_header("Accept-Encoding", "deflate");
  1364. req.set_header("Accept-Encoding", "br");
  1365. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1366. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1367. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1368. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1369. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1370. }
  1371. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1372. Request req;
  1373. req.set_header("X-Test", "only");
  1374. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1375. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1376. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1377. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1378. }
  1379. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1380. Headers headers;
  1381. headers.emplace("Host", "example.com");
  1382. headers.emplace("Accept-Encoding", "gzip");
  1383. headers.emplace("User-Agent", "test");
  1384. headers.emplace("Accept-Encoding", "deflate");
  1385. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1386. "Accept-Encoding=deflate ",
  1387. entries_to_string(headers));
  1388. }
  1389. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1390. Headers headers = {{"Content-Type", "text/html"},
  1391. {"CONTENT-TYPE", "text/xml"}};
  1392. EXPECT_EQ(2U, headers.count("content-type"));
  1393. auto it = headers.find("content-type");
  1394. ASSERT_TRUE(it != headers.end());
  1395. EXPECT_EQ("text/html", it->second);
  1396. }
  1397. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1398. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1399. // drop only those fields and leave everything positioned between them.
  1400. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1401. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1402. auto rng = headers.equal_range("a");
  1403. headers.erase(rng.first, rng.second);
  1404. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1405. }
  1406. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1407. Headers headers = {
  1408. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1409. EXPECT_EQ(3U, headers.erase("A"));
  1410. EXPECT_EQ(0U, headers.count("A"));
  1411. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1412. }
  1413. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1414. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1415. headers.emplace_front("Host", "example.com");
  1416. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1417. entries_to_string(headers));
  1418. }
  1419. TEST(ParseHeaderValueTest, Range) {
  1420. {
  1421. Ranges ranges;
  1422. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1423. EXPECT_TRUE(ret);
  1424. EXPECT_EQ(1u, ranges.size());
  1425. EXPECT_EQ(1u, ranges[0].first);
  1426. EXPECT_EQ(-1, ranges[0].second);
  1427. }
  1428. {
  1429. Ranges ranges;
  1430. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1431. EXPECT_TRUE(ret);
  1432. EXPECT_EQ(1u, ranges.size());
  1433. EXPECT_EQ(-1, ranges[0].first);
  1434. EXPECT_EQ(1u, ranges[0].second);
  1435. }
  1436. {
  1437. Ranges ranges;
  1438. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1439. EXPECT_TRUE(ret);
  1440. EXPECT_EQ(1u, ranges.size());
  1441. EXPECT_EQ(1u, ranges[0].first);
  1442. EXPECT_EQ(10u, ranges[0].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1447. EXPECT_FALSE(ret);
  1448. }
  1449. {
  1450. Ranges ranges;
  1451. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1452. EXPECT_TRUE(ret);
  1453. EXPECT_EQ(2u, ranges.size());
  1454. EXPECT_EQ(1u, ranges[0].first);
  1455. EXPECT_EQ(10u, ranges[0].second);
  1456. EXPECT_EQ(100u, ranges[1].first);
  1457. EXPECT_EQ(-1, ranges[1].second);
  1458. }
  1459. {
  1460. Ranges ranges;
  1461. auto ret =
  1462. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1463. EXPECT_TRUE(ret);
  1464. EXPECT_EQ(3u, ranges.size());
  1465. EXPECT_EQ(1u, ranges[0].first);
  1466. EXPECT_EQ(10u, ranges[0].second);
  1467. EXPECT_EQ(100u, ranges[1].first);
  1468. EXPECT_EQ(200u, ranges[1].second);
  1469. EXPECT_EQ(300u, ranges[2].first);
  1470. EXPECT_EQ(400u, ranges[2].second);
  1471. }
  1472. {
  1473. Ranges ranges;
  1474. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1475. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1476. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1477. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1478. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1479. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1480. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1481. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1482. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1483. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1484. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1485. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1486. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1487. EXPECT_TRUE(ranges.empty());
  1488. }
  1489. }
  1490. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1491. Request req;
  1492. req.set_header("Accept-Encoding", "gzip");
  1493. Response res;
  1494. res.set_header("Content-Type", "text/plain");
  1495. auto ret = detail::encoding_type(req, res);
  1496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1497. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1498. #else
  1499. EXPECT_TRUE(ret == detail::EncodingType::None);
  1500. #endif
  1501. }
  1502. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1503. Request req;
  1504. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1505. Response res;
  1506. res.set_header("Content-Type", "text/plain");
  1507. auto ret = detail::encoding_type(req, res);
  1508. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1509. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1510. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1512. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1514. #else
  1515. EXPECT_TRUE(ret == detail::EncodingType::None);
  1516. #endif
  1517. }
  1518. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1519. Request req;
  1520. req.set_header("Accept-Encoding",
  1521. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1522. Response res;
  1523. res.set_header("Content-Type", "text/plain");
  1524. auto ret = detail::encoding_type(req, res);
  1525. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1526. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1527. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1528. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1529. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1530. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1531. #else
  1532. EXPECT_TRUE(ret == detail::EncodingType::None);
  1533. #endif
  1534. }
  1535. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1536. // All supported encodings rejected with q=0 should return None
  1537. Request req;
  1538. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1539. Response res;
  1540. res.set_header("Content-Type", "text/plain");
  1541. auto ret = detail::encoding_type(req, res);
  1542. EXPECT_TRUE(ret == detail::EncodingType::None);
  1543. }
  1544. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1545. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1546. Request req;
  1547. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1548. Response res;
  1549. res.set_header("Content-Type", "text/plain");
  1550. auto ret = detail::encoding_type(req, res);
  1551. EXPECT_TRUE(ret == detail::EncodingType::None);
  1552. }
  1553. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1554. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1563. // RFC 7231: Accept-Encoding values are case-insensitive
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1570. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1571. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1572. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1573. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1575. #else
  1576. EXPECT_TRUE(ret == detail::EncodingType::None);
  1577. #endif
  1578. }
  1579. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1580. // q value should determine priority, not hardcoded order
  1581. Request req;
  1582. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1583. Response res;
  1584. res.set_header("Content-Type", "text/plain");
  1585. auto ret = detail::encoding_type(req, res);
  1586. // gzip has highest q=1.0, so it should be selected even though
  1587. // br and zstd are also supported
  1588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1589. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1590. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1591. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1592. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1593. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1594. #else
  1595. EXPECT_TRUE(ret == detail::EncodingType::None);
  1596. #endif
  1597. }
  1598. TEST(BufferStreamTest, read) {
  1599. detail::BufferStream strm1;
  1600. Stream &strm = strm1;
  1601. EXPECT_EQ(5, strm.write("hello"));
  1602. char buf[512];
  1603. EXPECT_EQ(2, strm.read(buf, 2));
  1604. EXPECT_EQ('h', buf[0]);
  1605. EXPECT_EQ('e', buf[1]);
  1606. EXPECT_EQ(2, strm.read(buf, 2));
  1607. EXPECT_EQ('l', buf[0]);
  1608. EXPECT_EQ('l', buf[1]);
  1609. EXPECT_EQ(1, strm.read(buf, 1));
  1610. EXPECT_EQ('o', buf[0]);
  1611. EXPECT_EQ(0, strm.read(buf, 1));
  1612. }
  1613. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1614. auto host = "www.httpwatch.com";
  1615. auto ip = hosted_at(host);
  1616. EXPECT_EQ("23.96.13.243", ip);
  1617. std::vector<std::string> addrs;
  1618. hosted_at(host, addrs);
  1619. EXPECT_EQ(1u, addrs.size());
  1620. }
  1621. #if 0 // It depends on each test environment...
  1622. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1623. auto host = "www.youtube.com";
  1624. std::vector<std::string> addrs;
  1625. hosted_at(host, addrs);
  1626. EXPECT_EQ(20u, addrs.size());
  1627. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1628. EXPECT_TRUE(it != addrs.end());
  1629. }
  1630. #endif
  1631. class ChunkedEncodingTest : public ::testing::Test {
  1632. protected:
  1633. ChunkedEncodingTest()
  1634. : cli_(HOST, PORT)
  1635. #ifdef CPPHTTPLIB_SSL_ENABLED
  1636. ,
  1637. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1638. #endif
  1639. {
  1640. cli_.set_connection_timeout(2);
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. cli_.enable_server_certificate_verification(false);
  1643. #endif
  1644. }
  1645. virtual void SetUp() {
  1646. read_file("./image.jpg", image_data_);
  1647. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1648. res.set_content("Hello World!", "text/plain");
  1649. });
  1650. svr_.Get(
  1651. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1652. res.set_chunked_content_provider(
  1653. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1654. size_t remaining = image_data_.size() - offset;
  1655. if (remaining == 0) {
  1656. sink.done();
  1657. } else {
  1658. constexpr size_t CHUNK_SIZE = 1024;
  1659. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1660. sink.write(&image_data_[offset], send_size);
  1661. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1662. }
  1663. return true;
  1664. });
  1665. });
  1666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1667. svr_.wait_until_ready();
  1668. }
  1669. virtual void TearDown() {
  1670. svr_.stop();
  1671. if (!request_threads_.empty()) {
  1672. std::this_thread::sleep_for(std::chrono::seconds(1));
  1673. for (auto &t : request_threads_) {
  1674. t.join();
  1675. }
  1676. }
  1677. t_.join();
  1678. }
  1679. #ifdef CPPHTTPLIB_SSL_ENABLED
  1680. SSLClient cli_;
  1681. SSLServer svr_;
  1682. #else
  1683. Client cli_;
  1684. Server svr_;
  1685. #endif
  1686. thread t_;
  1687. std::vector<thread> request_threads_;
  1688. std::string image_data_;
  1689. };
  1690. TEST_F(ChunkedEncodingTest, NormalGet) {
  1691. auto res = cli_.Get("/chunked");
  1692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1693. std::string out;
  1694. read_file("./image.jpg", out);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. EXPECT_EQ(out, res->body);
  1697. }
  1698. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1699. std::string body;
  1700. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1701. body.append(data, data_length);
  1702. return true;
  1703. });
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. std::string out;
  1706. read_file("./image.jpg", out);
  1707. EXPECT_EQ(StatusCode::OK_200, res->status);
  1708. EXPECT_EQ(out, body);
  1709. }
  1710. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1711. std::string body;
  1712. auto res = cli_.Get(
  1713. "/chunked",
  1714. [&](const Response &response) {
  1715. EXPECT_EQ(StatusCode::OK_200, response.status);
  1716. return true;
  1717. },
  1718. [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST(RangeTest, FromHTTPBin_Online) {
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/range/32"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. cli.set_connection_timeout(5);
  1739. {
  1740. auto res = cli.Get(path);
  1741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1742. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. }
  1745. {
  1746. Headers headers = {make_range_header({{1, -1}})};
  1747. auto res = cli.Get(path, headers);
  1748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1749. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}})};
  1754. auto res = cli.Get(path, headers);
  1755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1756. EXPECT_EQ("bcdefghijk", res->body);
  1757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1758. }
  1759. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1760. // entire resource, while the original httpbin returned 200. Both are
  1761. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1762. {
  1763. Headers headers = {make_range_header({{0, 31}})};
  1764. auto res = cli.Get(path, headers);
  1765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1766. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1767. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1768. res->status == StatusCode::PartialContent_206);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{0, -1}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1775. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1776. res->status == StatusCode::PartialContent_206);
  1777. }
  1778. // go-httpbin returns 206 with clamped range for over-range requests,
  1779. // while the original httpbin returned 416. Both behaviors are observed
  1780. // in real servers, so we only verify the request succeeds.
  1781. {
  1782. Headers headers = {make_range_header({{0, 32}})};
  1783. auto res = cli.Get(path, headers);
  1784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1785. }
  1786. }
  1787. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1788. auto host = "unresolvableaddress.local";
  1789. auto path = std::string{"/"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. auto port = 443;
  1792. SSLClient cli(host, port);
  1793. #else
  1794. auto port = 80;
  1795. Client cli(host, port);
  1796. #endif
  1797. cli.set_connection_timeout(1);
  1798. {
  1799. auto res = cli.Get(path);
  1800. ASSERT_FALSE(res);
  1801. }
  1802. std::this_thread::sleep_for(std::chrono::seconds(8));
  1803. }
  1804. #if defined(__linux__) && defined(__GLIBC__) && \
  1805. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1806. // Forward declaration: in split builds split.py strips `inline` and moves the
  1807. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1808. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1809. // against the symbol in both header-only and split builds.
  1810. namespace httplib {
  1811. namespace detail {
  1812. int getaddrinfo_with_timeout(const char *node, const char *service,
  1813. const struct addrinfo *hints,
  1814. struct addrinfo **res, time_t timeout_sec);
  1815. } // namespace detail
  1816. } // namespace httplib
  1817. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1818. //
  1819. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1820. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1821. // gai_suspend() call hits the connection timeout the function calls
  1822. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1823. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1824. // still alive and still references the now-destroyed stack frame.
  1825. //
  1826. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1827. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1828. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1829. // and runs them in a container.
  1830. namespace {
  1831. bool should_run_issue_2431_tests() {
  1832. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1833. return v && *v && std::string(v) != "0";
  1834. }
  1835. std::string unique_unresolvable_host(int n) {
  1836. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1837. // glibc still asks the configured nameserver — which is exactly the path
  1838. // we want to exercise. A unique label per call avoids the resolver cache.
  1839. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1840. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1841. std::to_string(n) + ".invalid";
  1842. }
  1843. } // namespace
  1844. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1845. if (!should_run_issue_2431_tests()) {
  1846. GTEST_SKIP()
  1847. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1848. }
  1849. for (int i = 0; i < 8; ++i) {
  1850. struct addrinfo hints;
  1851. memset(&hints, 0, sizeof(hints));
  1852. hints.ai_family = AF_UNSPEC;
  1853. hints.ai_socktype = SOCK_STREAM;
  1854. auto host = unique_unresolvable_host(i);
  1855. struct addrinfo *result = nullptr;
  1856. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1857. &result, /*timeout_sec=*/1);
  1858. if (rc == 0 && result) { freeaddrinfo(result); }
  1859. }
  1860. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1861. // stack region they still believe holds their gaicb.
  1862. std::this_thread::sleep_for(std::chrono::seconds(3));
  1863. }
  1864. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1865. if (!should_run_issue_2431_tests()) {
  1866. GTEST_SKIP()
  1867. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1868. }
  1869. std::atomic<bool> stop{false};
  1870. std::vector<std::thread> threads;
  1871. for (int t = 0; t < 8; ++t) {
  1872. threads.emplace_back([t, &stop] {
  1873. int i = 0;
  1874. while (!stop.load(std::memory_order_relaxed)) {
  1875. struct addrinfo hints;
  1876. memset(&hints, 0, sizeof(hints));
  1877. hints.ai_family = AF_UNSPEC;
  1878. hints.ai_socktype = SOCK_STREAM;
  1879. auto host = unique_unresolvable_host(t * 100000 + i++);
  1880. struct addrinfo *result = nullptr;
  1881. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1882. &result, /*timeout_sec=*/1);
  1883. if (rc == 0 && result) { freeaddrinfo(result); }
  1884. }
  1885. });
  1886. }
  1887. std::this_thread::sleep_for(std::chrono::seconds(8));
  1888. stop.store(true, std::memory_order_relaxed);
  1889. for (auto &th : threads) {
  1890. th.join();
  1891. }
  1892. std::this_thread::sleep_for(std::chrono::seconds(3));
  1893. }
  1894. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1895. if (!should_run_issue_2431_tests()) {
  1896. GTEST_SKIP()
  1897. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1898. }
  1899. std::atomic<bool> stop{false};
  1900. std::vector<std::thread> threads;
  1901. for (int t = 0; t < 8; ++t) {
  1902. threads.emplace_back([t, &stop] {
  1903. int i = 0;
  1904. while (!stop.load(std::memory_order_relaxed)) {
  1905. auto host = unique_unresolvable_host(t * 100000 + i++);
  1906. Client cli(host, 80);
  1907. cli.set_connection_timeout(1, 0);
  1908. cli.set_read_timeout(1, 0);
  1909. cli.set_write_timeout(1, 0);
  1910. (void)cli.Get("/");
  1911. }
  1912. });
  1913. }
  1914. std::this_thread::sleep_for(std::chrono::seconds(8));
  1915. stop.store(true, std::memory_order_relaxed);
  1916. for (auto &th : threads) {
  1917. th.join();
  1918. }
  1919. std::this_thread::sleep_for(std::chrono::seconds(3));
  1920. }
  1921. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1922. TEST(ConnectionErrorTest, InvalidHost) {
  1923. auto host = "-abcde.com";
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. auto port = 443;
  1926. SSLClient cli(host, port);
  1927. #else
  1928. auto port = 80;
  1929. Client cli(host, port);
  1930. #endif
  1931. cli.set_connection_timeout(std::chrono::seconds(2));
  1932. auto res = cli.Get("/");
  1933. ASSERT_TRUE(!res);
  1934. EXPECT_EQ(Error::Connection, res.error());
  1935. }
  1936. TEST(ConnectionErrorTest, InvalidHost2) {
  1937. auto host = "httpcan.org/";
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. SSLClient cli(host);
  1940. #else
  1941. Client cli(host);
  1942. #endif
  1943. cli.set_connection_timeout(std::chrono::seconds(2));
  1944. auto res = cli.Get("/");
  1945. ASSERT_TRUE(!res);
  1946. EXPECT_EQ(Error::Connection, res.error());
  1947. }
  1948. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1949. auto host = "httpcan.org/";
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. stringstream s;
  1959. s << "error code: " << res.error();
  1960. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1961. }
  1962. TEST(ConnectionErrorTest, InvalidPort) {
  1963. auto host = "localhost";
  1964. auto port = 44380;
  1965. #ifdef CPPHTTPLIB_SSL_ENABLED
  1966. SSLClient cli(host, port);
  1967. #else
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(!res);
  1973. EXPECT_TRUE(Error::Connection == res.error() ||
  1974. Error::ConnectionTimeout == res.error());
  1975. }
  1976. TEST(ConnectionErrorTest, Timeout_Online) {
  1977. auto host = "google.com";
  1978. #ifdef CPPHTTPLIB_SSL_ENABLED
  1979. auto port = 44380;
  1980. SSLClient cli(host, port);
  1981. #else
  1982. auto port = 8080;
  1983. Client cli(host, port);
  1984. #endif
  1985. cli.set_connection_timeout(std::chrono::seconds(2));
  1986. // only probe one address type so that the error reason
  1987. // correlates to the timed-out IPv4, not the unsupported
  1988. // IPv6 connection attempt
  1989. cli.set_address_family(AF_INET);
  1990. auto res = cli.Get("/");
  1991. ASSERT_TRUE(!res);
  1992. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1993. }
  1994. TEST(CancelTest, NoCancel_Online) {
  1995. auto host = "httpbingo.org";
  1996. auto path = std::string{"/range/32"};
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. auto port = 443;
  1999. SSLClient cli(host, port);
  2000. #else
  2001. auto port = 80;
  2002. Client cli(host, port);
  2003. #endif
  2004. cli.set_connection_timeout(std::chrono::seconds(5));
  2005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2008. EXPECT_EQ(StatusCode::OK_200, res->status);
  2009. }
  2010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2011. // Use /bytes with a large payload so that the DownloadProgress callback
  2012. // (which only fires for Content-Length responses) is invoked before the
  2013. // entire body is received, giving cancellation a chance to fire.
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2024. cli.set_connection_timeout(std::chrono::seconds(5));
  2025. ASSERT_TRUE(!res);
  2026. EXPECT_EQ(Error::Canceled, res.error());
  2027. }
  2028. TEST(CancelTest, WithCancelLargePayload_Online) {
  2029. auto host = "httpbingo.org";
  2030. auto path = std::string{"/bytes/524288"};
  2031. #ifdef CPPHTTPLIB_SSL_ENABLED
  2032. auto port = 443;
  2033. SSLClient cli(host, port);
  2034. #else
  2035. auto port = 80;
  2036. Client cli(host, port);
  2037. #endif
  2038. cli.set_connection_timeout(std::chrono::seconds(5));
  2039. uint32_t count = 0;
  2040. auto res =
  2041. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Canceled, res.error());
  2044. }
  2045. TEST(CancelTest, NoCancelPost) {
  2046. Server svr;
  2047. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2048. res.set_content("Hello World!", "text/plain");
  2049. });
  2050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2051. auto se = detail::scope_exit([&] {
  2052. svr.stop();
  2053. thread.join();
  2054. ASSERT_FALSE(svr.is_running());
  2055. });
  2056. svr.wait_until_ready();
  2057. Client cli(HOST, PORT);
  2058. cli.set_connection_timeout(std::chrono::seconds(5));
  2059. auto res =
  2060. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2061. "application/json", [](uint64_t, uint64_t) { return true; });
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("Hello World!", res->body);
  2064. EXPECT_EQ(StatusCode::OK_200, res->status);
  2065. }
  2066. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2067. Server svr;
  2068. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2069. res.set_content("Hello World!", "text/plain");
  2070. });
  2071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2072. auto se = detail::scope_exit([&] {
  2073. svr.stop();
  2074. thread.join();
  2075. ASSERT_FALSE(svr.is_running());
  2076. });
  2077. svr.wait_until_ready();
  2078. Client cli(HOST, PORT);
  2079. cli.set_connection_timeout(std::chrono::seconds(5));
  2080. auto res =
  2081. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2082. "application/json", [](uint64_t, uint64_t) { return false; });
  2083. ASSERT_TRUE(!res);
  2084. EXPECT_EQ(Error::Canceled, res.error());
  2085. }
  2086. TEST(CancelTest, WithCancelLargePayloadPost) {
  2087. Server svr;
  2088. svr.set_payload_max_length(200 * 1024 * 1024);
  2089. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2090. res.set_content(LARGE_DATA, "text/plain");
  2091. });
  2092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2093. auto se = detail::scope_exit([&] {
  2094. svr.stop();
  2095. thread.join();
  2096. ASSERT_FALSE(svr.is_running());
  2097. });
  2098. svr.wait_until_ready();
  2099. Client cli(HOST, PORT);
  2100. cli.set_payload_max_length(200 * 1024 * 1024);
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res =
  2103. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2104. "application/json", [](uint64_t, uint64_t) { return false; });
  2105. ASSERT_TRUE(!res);
  2106. EXPECT_EQ(Error::Canceled, res.error());
  2107. }
  2108. TEST(CancelTest, NoCancelPut) {
  2109. Server svr;
  2110. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2111. res.set_content("Hello World!", "text/plain");
  2112. });
  2113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2114. auto se = detail::scope_exit([&] {
  2115. svr.stop();
  2116. thread.join();
  2117. ASSERT_FALSE(svr.is_running());
  2118. });
  2119. svr.wait_until_ready();
  2120. Client cli(HOST, PORT);
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. auto res =
  2123. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2124. "application/json", [](uint64_t, uint64_t) { return true; });
  2125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. }
  2129. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2130. Server svr;
  2131. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2132. res.set_content("Hello World!", "text/plain");
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. Client cli(HOST, PORT);
  2142. cli.set_connection_timeout(std::chrono::seconds(5));
  2143. auto res =
  2144. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2145. "application/json", [](uint64_t, uint64_t) { return false; });
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Canceled, res.error());
  2148. }
  2149. TEST(CancelTest, WithCancelLargePayloadPut) {
  2150. Server svr;
  2151. svr.set_payload_max_length(200 * 1024 * 1024);
  2152. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content(LARGE_DATA, "text/plain");
  2154. });
  2155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2156. auto se = detail::scope_exit([&] {
  2157. svr.stop();
  2158. thread.join();
  2159. ASSERT_FALSE(svr.is_running());
  2160. });
  2161. svr.wait_until_ready();
  2162. Client cli(HOST, PORT);
  2163. cli.set_payload_max_length(200 * 1024 * 1024);
  2164. cli.set_connection_timeout(std::chrono::seconds(5));
  2165. auto res =
  2166. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2167. "application/json", [](uint64_t, uint64_t) { return false; });
  2168. ASSERT_TRUE(!res);
  2169. EXPECT_EQ(Error::Canceled, res.error());
  2170. }
  2171. TEST(CancelTest, NoCancelPatch) {
  2172. Server svr;
  2173. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2174. res.set_content("Hello World!", "text/plain");
  2175. });
  2176. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2177. auto se = detail::scope_exit([&] {
  2178. svr.stop();
  2179. thread.join();
  2180. ASSERT_FALSE(svr.is_running());
  2181. });
  2182. svr.wait_until_ready();
  2183. Client cli(HOST, PORT);
  2184. cli.set_connection_timeout(std::chrono::seconds(5));
  2185. auto res =
  2186. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2187. "application/json", [](uint64_t, uint64_t) { return true; });
  2188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. EXPECT_EQ(StatusCode::OK_200, res->status);
  2191. }
  2192. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2193. Server svr;
  2194. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2195. res.set_content("Hello World!", "text/plain");
  2196. });
  2197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. thread.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. Client cli(HOST, PORT);
  2205. cli.set_connection_timeout(std::chrono::seconds(5));
  2206. auto res =
  2207. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2208. "application/json", [](uint64_t, uint64_t) { return false; });
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Canceled, res.error());
  2211. }
  2212. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2213. Server svr;
  2214. svr.set_payload_max_length(200 * 1024 * 1024);
  2215. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2216. res.set_content(LARGE_DATA, "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. Client cli(HOST, PORT);
  2226. cli.set_payload_max_length(200 * 1024 * 1024);
  2227. cli.set_connection_timeout(std::chrono::seconds(5));
  2228. auto res =
  2229. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2230. "application/json", [](uint64_t, uint64_t) { return false; });
  2231. ASSERT_TRUE(!res);
  2232. EXPECT_EQ(Error::Canceled, res.error());
  2233. }
  2234. TEST(CancelTest, NoCancelDelete) {
  2235. Server svr;
  2236. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2237. res.set_content("Hello World!", "text/plain");
  2238. });
  2239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2240. auto se = detail::scope_exit([&] {
  2241. svr.stop();
  2242. thread.join();
  2243. ASSERT_FALSE(svr.is_running());
  2244. });
  2245. svr.wait_until_ready();
  2246. Client cli(HOST, PORT);
  2247. cli.set_connection_timeout(std::chrono::seconds(5));
  2248. auto res =
  2249. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2250. "application/json", [](uint64_t, uint64_t) { return true; });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. EXPECT_EQ("Hello World!", res->body);
  2253. EXPECT_EQ(StatusCode::OK_200, res->status);
  2254. }
  2255. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2256. Server svr;
  2257. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2258. res.set_content("Hello World!", "text/plain");
  2259. });
  2260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli(HOST, PORT);
  2268. cli.set_connection_timeout(std::chrono::seconds(5));
  2269. auto res =
  2270. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2271. "application/json", [](uint64_t, uint64_t) { return false; });
  2272. ASSERT_TRUE(!res);
  2273. EXPECT_EQ(Error::Canceled, res.error());
  2274. }
  2275. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2276. Server svr;
  2277. svr.set_payload_max_length(200 * 1024 * 1024);
  2278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2279. res.set_content(LARGE_DATA, "text/plain");
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. Client cli(HOST, PORT);
  2289. cli.set_payload_max_length(200 * 1024 * 1024);
  2290. cli.set_connection_timeout(std::chrono::seconds(5));
  2291. auto res =
  2292. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2293. "application/json", [](uint64_t, uint64_t) { return false; });
  2294. ASSERT_TRUE(!res);
  2295. EXPECT_EQ(Error::Canceled, res.error());
  2296. }
  2297. static std::string remove_whitespace(const std::string &input) {
  2298. std::string output;
  2299. output.reserve(input.size());
  2300. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2301. [](unsigned char c) { return !std::isspace(c); });
  2302. return output;
  2303. }
  2304. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2305. auto host = "httpbingo.org";
  2306. auto path = std::string{"/basic-auth/hello/world"};
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. auto port = 443;
  2309. SSLClient cli(host, port);
  2310. #else
  2311. auto port = 80;
  2312. Client cli(host, port);
  2313. #endif
  2314. {
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2318. }
  2319. {
  2320. auto res = cli.Get(
  2321. path, Headers{make_basic_authentication_header("hello", "world")});
  2322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2323. auto body = remove_whitespace(res->body);
  2324. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2325. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2326. EXPECT_EQ(StatusCode::OK_200, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("hello", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. auto body = remove_whitespace(res->body);
  2333. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2334. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2335. EXPECT_EQ(StatusCode::OK_200, res->status);
  2336. }
  2337. {
  2338. cli.set_basic_auth("hello", "bad");
  2339. auto res = cli.Get(path);
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2342. }
  2343. {
  2344. cli.set_basic_auth("bad", "world");
  2345. auto res = cli.Get(path);
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2348. }
  2349. }
  2350. #ifdef CPPHTTPLIB_SSL_ENABLED
  2351. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2352. auto host = "httpbingo.org";
  2353. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2354. auto paths = std::vector<std::string>{
  2355. "/digest-auth/auth/hello/world/MD5",
  2356. "/digest-auth/auth/hello/world/SHA-256",
  2357. };
  2358. auto port = 443;
  2359. SSLClient cli(host, port);
  2360. {
  2361. auto res = cli.Get(unauth_path);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2364. }
  2365. {
  2366. cli.set_digest_auth("hello", "world");
  2367. for (const auto &path : paths) {
  2368. auto res = cli.Get(path.c_str());
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. auto body = remove_whitespace(res->body);
  2371. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2372. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. cli.set_digest_auth("hello", "bad");
  2376. for (const auto &path : paths) {
  2377. auto res = cli.Get(path.c_str());
  2378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2379. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2380. }
  2381. }
  2382. }
  2383. #endif
  2384. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2385. auto host = "google.com";
  2386. auto another_host = "example.com";
  2387. auto wrong_ip = "0.0.0.0";
  2388. #ifdef CPPHTTPLIB_SSL_ENABLED
  2389. SSLClient cli(host);
  2390. #else
  2391. Client cli(host);
  2392. #endif
  2393. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2394. auto res = cli.Get("/");
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2397. }
  2398. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2399. auto host = "google.com";
  2400. auto wrong_ip = "0.0.0.0";
  2401. #ifdef CPPHTTPLIB_SSL_ENABLED
  2402. SSLClient cli(host);
  2403. #else
  2404. Client cli(host);
  2405. #endif
  2406. cli.set_hostname_addr_map({{host, wrong_ip}});
  2407. auto res = cli.Get("/");
  2408. ASSERT_TRUE(!res);
  2409. EXPECT_EQ(Error::Connection, res.error());
  2410. }
  2411. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2412. // A mapped value that is not an IP literal must be resolved. "localhost"
  2413. // resolves from the hosts file, so this test needs no external DNS.
  2414. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2415. auto host = "target.invalid";
  2416. Server svr;
  2417. std::string received_host;
  2418. svr.Get("/hi", [&](const Request &req, Response &res) {
  2419. received_host = req.get_header_value("Host");
  2420. res.set_content("Hello World!", "text/plain");
  2421. });
  2422. auto port = svr.bind_to_any_port(HOST);
  2423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. Client cli(host, port);
  2431. cli.set_hostname_addr_map({{host, HOST}});
  2432. auto res = cli.Get("/hi");
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. // The mapping only redirects the connection; the identity stays host_.
  2436. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2437. }
  2438. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2439. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2440. auto host = "target.invalid";
  2441. Server svr;
  2442. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2443. res.set_content("Hello World!", "text/plain");
  2444. });
  2445. auto port = svr.bind_to_any_port("127.0.0.1");
  2446. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. Client cli(host, port);
  2454. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2455. auto res = cli.Get("/hi");
  2456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. }
  2459. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2460. // An empty mapped value must leave host_ as the connection target. Without
  2461. // that guard the empty value would become the host argument, getaddrinfo
  2462. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2463. // loopback - silently connecting somewhere the caller never asked for.
  2464. // The server listens on loopback, so such a fallback would succeed and is
  2465. // therefore observable as a failure of this test.
  2466. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2467. Server svr;
  2468. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2469. res.set_content("Hello World!", "text/plain");
  2470. });
  2471. auto port = svr.bind_to_any_port(HOST);
  2472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. thread.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. svr.wait_until_ready();
  2479. Client cli(blackhole, port);
  2480. cli.set_hostname_addr_map({{blackhole, ""}});
  2481. cli.set_connection_timeout(1);
  2482. auto res = cli.Get("/hi");
  2483. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2484. }
  2485. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2486. auto host = "httpbingo.org";
  2487. auto path = std::string{"/absolute-redirect/3"};
  2488. #ifdef CPPHTTPLIB_SSL_ENABLED
  2489. SSLClient cli(host);
  2490. #else
  2491. Client cli(host);
  2492. #endif
  2493. cli.set_follow_location(true);
  2494. auto res = cli.Get(path);
  2495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. }
  2498. TEST(RedirectTest, Redirect_Online) {
  2499. auto host = "httpbingo.org";
  2500. auto path = std::string{"/redirect/3"};
  2501. #ifdef CPPHTTPLIB_SSL_ENABLED
  2502. SSLClient cli(host);
  2503. #else
  2504. Client cli(host);
  2505. #endif
  2506. cli.set_follow_location(true);
  2507. auto res = cli.Get(path);
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. }
  2511. TEST(RelativeRedirectTest, Redirect_Online) {
  2512. auto host = "httpbingo.org";
  2513. auto path = std::string{"/relative-redirect/3"};
  2514. #ifdef CPPHTTPLIB_SSL_ENABLED
  2515. SSLClient cli(host);
  2516. #else
  2517. Client cli(host);
  2518. #endif
  2519. cli.set_follow_location(true);
  2520. auto res = cli.Get(path);
  2521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2522. EXPECT_EQ(StatusCode::OK_200, res->status);
  2523. }
  2524. TEST(TooManyRedirectTest, Redirect_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/redirect/21"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. SSLClient cli(host);
  2529. #else
  2530. Client cli(host);
  2531. #endif
  2532. cli.set_follow_location(true);
  2533. auto res = cli.Get(path);
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2536. }
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. TEST(YahooRedirectTest, Redirect_Online) {
  2539. Client cli("yahoo.com");
  2540. auto res = cli.Get("/");
  2541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2542. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2543. cli.set_follow_location(true);
  2544. res = cli.Get("/");
  2545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2546. EXPECT_EQ(StatusCode::OK_200, res->status);
  2547. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2548. }
  2549. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2550. #define REDIR_HOST "httpbingo.org"
  2551. #define REDIR_PATH "/redirect-to"
  2552. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2553. SSLClient cli(REDIR_HOST);
  2554. cli.set_follow_location(true);
  2555. auto res =
  2556. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2558. EXPECT_EQ(StatusCode::OK_200, res->status);
  2559. }
  2560. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2561. SSLClient cli(REDIR_HOST);
  2562. cli.set_follow_location(true);
  2563. Params params;
  2564. params.emplace("url", "http://example.com");
  2565. params.emplace("status_code", "302");
  2566. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::OK_200, res->status);
  2569. }
  2570. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2571. SSLClient cli(REDIR_HOST);
  2572. cli.set_follow_location(true);
  2573. Params params;
  2574. params.emplace("url", "http://example.com");
  2575. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. }
  2579. TEST(UrlWithSpace, Redirect_Online) {
  2580. SSLClient cli("edge.forgecdn.net");
  2581. cli.set_follow_location(true);
  2582. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2586. }
  2587. #endif
  2588. #if !defined(_WIN32) && !defined(_WIN64)
  2589. TEST(ReceiveSignals, Signal) {
  2590. auto setupSignalHandlers = []() {
  2591. struct sigaction act;
  2592. sigemptyset(&act.sa_mask);
  2593. act.sa_flags = SA_SIGINFO;
  2594. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2595. switch (sig) {
  2596. case SIGINT:
  2597. default: break;
  2598. }
  2599. };
  2600. ::sigaction(SIGINT, &act, nullptr);
  2601. };
  2602. Server svr;
  2603. int port = 0;
  2604. auto thread = std::thread([&]() {
  2605. setupSignalHandlers();
  2606. port = svr.bind_to_any_port(HOST);
  2607. svr.listen_after_bind();
  2608. });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. ASSERT_TRUE(svr.is_running());
  2616. pthread_kill(thread.native_handle(), SIGINT);
  2617. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2618. ASSERT_TRUE(svr.is_running());
  2619. }
  2620. #endif
  2621. TEST(RedirectToDifferentPort, Redirect) {
  2622. Server svr1;
  2623. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content("Hello World!", "text/plain");
  2625. });
  2626. int svr1_port = 0;
  2627. auto thread1 = std::thread([&]() {
  2628. svr1_port = svr1.bind_to_any_port(HOST);
  2629. svr1.listen_after_bind();
  2630. });
  2631. Server svr2;
  2632. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2633. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2634. });
  2635. int svr2_port = 0;
  2636. auto thread2 = std::thread([&]() {
  2637. svr2_port = svr2.bind_to_any_port(HOST);
  2638. svr2.listen_after_bind();
  2639. });
  2640. auto se = detail::scope_exit([&] {
  2641. svr2.stop();
  2642. thread2.join();
  2643. svr1.stop();
  2644. thread1.join();
  2645. ASSERT_FALSE(svr2.is_running());
  2646. ASSERT_FALSE(svr1.is_running());
  2647. });
  2648. svr1.wait_until_ready();
  2649. svr2.wait_until_ready();
  2650. Client cli("localhost", svr2_port);
  2651. cli.set_follow_location(true);
  2652. auto res = cli.Get("/2");
  2653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2654. EXPECT_EQ(StatusCode::OK_200, res->status);
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. }
  2657. static void
  2658. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2659. Server svr1;
  2660. std::string captured_authorization;
  2661. svr1.Get("/target", [&](const Request &req, Response &res) {
  2662. captured_authorization = req.get_header_value("Authorization");
  2663. res.set_content("OK", "text/plain");
  2664. });
  2665. int svr1_port = 0;
  2666. auto thread1 = std::thread([&]() {
  2667. svr1_port = svr1.bind_to_any_port(HOST);
  2668. svr1.listen_after_bind();
  2669. });
  2670. Server svr2;
  2671. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2672. res.set_redirect(
  2673. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2674. });
  2675. int svr2_port = 0;
  2676. auto thread2 = std::thread([&]() {
  2677. svr2_port = svr2.bind_to_any_port(HOST);
  2678. svr2.listen_after_bind();
  2679. });
  2680. auto se = detail::scope_exit([&] {
  2681. svr2.stop();
  2682. thread2.join();
  2683. svr1.stop();
  2684. thread1.join();
  2685. ASSERT_FALSE(svr2.is_running());
  2686. ASSERT_FALSE(svr1.is_running());
  2687. });
  2688. svr1.wait_until_ready();
  2689. svr2.wait_until_ready();
  2690. Client cli("localhost", svr2_port);
  2691. cli.set_follow_location(true);
  2692. set_auth(cli);
  2693. auto res = cli.Get("/redir");
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ(StatusCode::OK_200, res->status);
  2696. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2697. EXPECT_TRUE(captured_authorization.empty());
  2698. }
  2699. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2700. TestDoNotForwardCredentialsOnRedirect(
  2701. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2702. }
  2703. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2704. TestDoNotForwardCredentialsOnRedirect(
  2705. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2706. }
  2707. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2708. Server svr1;
  2709. std::string captured_cookie;
  2710. bool target_hit = false;
  2711. svr1.Get("/target", [&](const Request &req, Response &res) {
  2712. captured_cookie = req.get_header_value("Cookie");
  2713. target_hit = true;
  2714. res.set_content("OK", "text/plain");
  2715. });
  2716. int svr1_port = 0;
  2717. auto thread1 = std::thread([&]() {
  2718. svr1_port = svr1.bind_to_any_port(HOST);
  2719. svr1.listen_after_bind();
  2720. });
  2721. Server svr2;
  2722. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2723. res.set_redirect(
  2724. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2725. });
  2726. int svr2_port = 0;
  2727. auto thread2 = std::thread([&]() {
  2728. svr2_port = svr2.bind_to_any_port(HOST);
  2729. svr2.listen_after_bind();
  2730. });
  2731. auto se = detail::scope_exit([&] {
  2732. svr2.stop();
  2733. thread2.join();
  2734. svr1.stop();
  2735. thread1.join();
  2736. ASSERT_FALSE(svr2.is_running());
  2737. ASSERT_FALSE(svr1.is_running());
  2738. });
  2739. svr1.wait_until_ready();
  2740. svr2.wait_until_ready();
  2741. Client cli("localhost", svr2_port);
  2742. cli.set_follow_location(true);
  2743. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2744. auto res = cli.Get("/redir", headers);
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. EXPECT_TRUE(target_hit);
  2748. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2749. EXPECT_TRUE(captured_cookie.empty());
  2750. }
  2751. TEST(RedirectToSamePort, ForwardCookie) {
  2752. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2753. // header so that ordinary session flows keep working.
  2754. Server svr;
  2755. std::string captured_cookie;
  2756. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2757. res.set_redirect("/target", 302);
  2758. });
  2759. svr.Get("/target", [&](const Request &req, Response &res) {
  2760. captured_cookie = req.get_header_value("Cookie");
  2761. res.set_content("OK", "text/plain");
  2762. });
  2763. auto port = svr.bind_to_any_port(HOST);
  2764. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2765. auto se = detail::scope_exit([&] {
  2766. svr.stop();
  2767. thread.join();
  2768. ASSERT_FALSE(svr.is_running());
  2769. });
  2770. svr.wait_until_ready();
  2771. Client cli(HOST, port);
  2772. cli.set_follow_location(true);
  2773. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2774. auto res = cli.Get("/redir", headers);
  2775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2776. EXPECT_EQ(StatusCode::OK_200, res->status);
  2777. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2778. }
  2779. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2780. Server svr;
  2781. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2782. // Port number that overflows int — should not crash
  2783. res.set_redirect("http://localhost:99999999999999999999/target");
  2784. });
  2785. auto port = svr.bind_to_any_port(HOST);
  2786. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. Client cli(HOST, port);
  2794. cli.set_follow_location(true);
  2795. auto res = cli.Get("/redir");
  2796. // Should fail gracefully, not crash (no valid response due to bad port)
  2797. EXPECT_FALSE(res);
  2798. }
  2799. TEST(RedirectFromPageWithContent, Redirect) {
  2800. Server svr;
  2801. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("___", "text/plain");
  2803. res.set_redirect("/2");
  2804. });
  2805. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2809. auto se = detail::scope_exit([&] {
  2810. svr.stop();
  2811. th.join();
  2812. ASSERT_FALSE(svr.is_running());
  2813. });
  2814. svr.wait_until_ready();
  2815. {
  2816. Client cli("localhost", PORT);
  2817. cli.set_follow_location(true);
  2818. std::string body;
  2819. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2820. body.append(data, data_length);
  2821. return true;
  2822. });
  2823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2824. EXPECT_EQ(StatusCode::OK_200, res->status);
  2825. EXPECT_EQ("Hello World!", body);
  2826. }
  2827. {
  2828. Client cli("localhost", PORT);
  2829. std::string body;
  2830. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2831. body.append(data, data_length);
  2832. return true;
  2833. });
  2834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2835. EXPECT_EQ(StatusCode::Found_302, res->status);
  2836. EXPECT_EQ("___", body);
  2837. }
  2838. }
  2839. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2840. Server svr;
  2841. auto port_str = std::to_string(PORT);
  2842. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2843. auto expected_host = "[::1]:" + port_str;
  2844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2845. res.set_content("___", "text/plain");
  2846. // res.set_redirect("/2");
  2847. res.set_redirect(redirect_url);
  2848. });
  2849. svr.Get("/2", [&](const Request &req, Response &res) {
  2850. auto host_header = req.headers.find("Host");
  2851. ASSERT_TRUE(host_header != req.headers.end());
  2852. EXPECT_EQ(expected_host, host_header->second);
  2853. res.set_content("Hello World!", "text/plain");
  2854. });
  2855. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. th.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2862. // actually starts anything, so the condition !svr.is_running() will
  2863. // always remain true, and the loop never stops.
  2864. // This basically counts how many milliseconds have passed since the
  2865. // call to svr.listen(), and if after 5 seconds nothing started yet
  2866. // aborts the test.
  2867. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2868. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2869. ASSERT_LT(milliseconds, 5000U);
  2870. }
  2871. {
  2872. Client cli("::1", PORT);
  2873. cli.set_follow_location(true);
  2874. std::string body;
  2875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2876. body.append(data, data_length);
  2877. return true;
  2878. });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. EXPECT_EQ("Hello World!", body);
  2882. }
  2883. {
  2884. Client cli("::1", PORT);
  2885. std::string body;
  2886. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2887. body.append(data, data_length);
  2888. return true;
  2889. });
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Found_302, res->status);
  2892. EXPECT_EQ("___", body);
  2893. }
  2894. }
  2895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2896. Server svr;
  2897. svr.Get("/foo", [](const Request &req, Response &res) {
  2898. auto a = req.params.find("a");
  2899. if (a != req.params.end()) {
  2900. res.set_content((*a).second, "text/plain");
  2901. res.status = StatusCode::OK_200;
  2902. } else {
  2903. res.status = StatusCode::BadRequest_400;
  2904. }
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. {
  2914. Client cli(HOST, PORT);
  2915. cli.set_path_encode(false);
  2916. auto res = cli.Get("/foo?a=explicitly+encoded");
  2917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. // This expects it back with a space, as the `+` won't have been
  2920. // url-encoded, and server-side the params get decoded turning `+`
  2921. // into spaces.
  2922. EXPECT_EQ("explicitly encoded", res->body);
  2923. }
  2924. }
  2925. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2926. // When path encoding is disabled the client must transmit the supplied
  2927. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2928. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2929. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2930. // than a space (0x20). Assert on the raw wire target to catch this.
  2931. Server svr;
  2932. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2933. svr.Get("/foo", [&](const Request &req, Response &res) {
  2934. EXPECT_EQ(expected_target, req.target);
  2935. res.status = StatusCode::OK_200;
  2936. });
  2937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2938. auto se = detail::scope_exit([&] {
  2939. svr.stop();
  2940. thread.join();
  2941. ASSERT_FALSE(svr.is_running());
  2942. });
  2943. svr.wait_until_ready();
  2944. {
  2945. Client cli(HOST, PORT);
  2946. cli.set_path_encode(false);
  2947. auto res = cli.Get(expected_target.c_str());
  2948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. }
  2951. }
  2952. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2953. // `open_stream()` used to skip the path encoding that the buffered send
  2954. // path applies, so the same `path` produced different bytes in the request
  2955. // line depending on which API was used. Assert the two agree.
  2956. Server svr;
  2957. std::string target;
  2958. svr.Get(".*", [&](const Request &req, Response &res) {
  2959. target = req.target;
  2960. res.status = StatusCode::OK_200;
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. thread.join();
  2967. ASSERT_FALSE(svr.is_running());
  2968. });
  2969. svr.wait_until_ready();
  2970. struct {
  2971. const char *path;
  2972. const char *expected;
  2973. } cases[] = {
  2974. {"/a b?x=1", "/a%20b?x=1"},
  2975. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2976. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2977. };
  2978. for (const auto &c : cases) {
  2979. Client cli(HOST, port);
  2980. target.clear();
  2981. auto res = cli.Get(c.path);
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2984. auto buffered_target = target;
  2985. target.clear();
  2986. auto handle = cli.open_stream("GET", c.path);
  2987. EXPECT_TRUE(handle.is_valid())
  2988. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2989. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2990. }
  2991. }
  2992. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2993. // The `set_path_encode(false)` contract — transmit the supplied target
  2994. // verbatim — must hold for the streaming API too.
  2995. Server svr;
  2996. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2997. std::string target;
  2998. svr.Get("/foo", [&](const Request &req, Response &res) {
  2999. target = req.target;
  3000. res.status = StatusCode::OK_200;
  3001. });
  3002. auto port = svr.bind_to_any_port(HOST);
  3003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. {
  3011. Client cli(HOST, port);
  3012. cli.set_path_encode(false);
  3013. auto handle = cli.open_stream("GET", expected_target);
  3014. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3015. EXPECT_EQ(expected_target, target);
  3016. }
  3017. }
  3018. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3019. // With path encoding enabled a CR/LF in the target is percent-encoded
  3020. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3021. // write_request_line still backstops `set_path_encode(false)`, which is
  3022. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3023. Server svr;
  3024. // Captured before routing: the decoded path contains a newline, which a
  3025. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3026. std::string target;
  3027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3028. target = req.target;
  3029. res.status = StatusCode::OK_200;
  3030. return Server::HandlerResponse::Handled;
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. {
  3041. Client cli(HOST, port);
  3042. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3043. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3044. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3045. }
  3046. }
  3047. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3048. // Nothing may reach the wire: a raw CR/LF target would split the request
  3049. // line and inject headers.
  3050. Server svr;
  3051. // Pre-routing so that "not called" means nothing reached the server at all,
  3052. // rather than merely failing to match a handler pattern.
  3053. auto handler_called = false;
  3054. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3055. handler_called = true;
  3056. res.status = StatusCode::OK_200;
  3057. return Server::HandlerResponse::Handled;
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. thread.join();
  3064. ASSERT_FALSE(svr.is_running());
  3065. });
  3066. svr.wait_until_ready();
  3067. {
  3068. Client cli(HOST, port);
  3069. cli.set_path_encode(false);
  3070. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3071. EXPECT_FALSE(handle.is_valid());
  3072. EXPECT_EQ(Error::Write, handle.error);
  3073. EXPECT_FALSE(handler_called);
  3074. }
  3075. }
  3076. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3077. // Which of the two branches runs is decided by whether the query component
  3078. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3079. // an empty query and must still fall back to building one from
  3080. // `req.params`, while a non-empty query must win over `req.params`.
  3081. Server svr;
  3082. std::string target;
  3083. svr.Get("/foo", [&](const Request &req, Response &res) {
  3084. target = req.target;
  3085. res.status = StatusCode::OK_200;
  3086. });
  3087. auto port = svr.bind_to_any_port(HOST);
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. {
  3096. // Trailing `?` -> empty query component -> `req.params` is used.
  3097. Client cli(HOST, port);
  3098. Request req;
  3099. req.method = "GET";
  3100. req.path = "/foo?";
  3101. req.params.emplace("a", "1");
  3102. target.clear();
  3103. auto res = cli.send(req);
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ("/foo?a=1", target);
  3106. }
  3107. {
  3108. // Non-empty query in `req.path` -> `req.params` is not appended.
  3109. Client cli(HOST, port);
  3110. Request req;
  3111. req.method = "GET";
  3112. req.path = "/foo?b=2";
  3113. req.params.emplace("a", "1");
  3114. target.clear();
  3115. auto res = cli.send(req);
  3116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3117. EXPECT_EQ("/foo?b=2", target);
  3118. }
  3119. }
  3120. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3121. Server svr;
  3122. svr.Get("/", [](const Request &req, Response &) {
  3123. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3124. });
  3125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3126. auto se = detail::scope_exit([&] {
  3127. svr.stop();
  3128. thread.join();
  3129. ASSERT_FALSE(svr.is_running());
  3130. });
  3131. svr.wait_until_ready();
  3132. {
  3133. Client cli(HOST, PORT);
  3134. cli.set_path_encode(false);
  3135. auto res = cli.Get("/?something=%0A");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::OK_200, res->status);
  3138. }
  3139. }
  3140. TEST(BindServerTest, BindDualStack) {
  3141. Server svr;
  3142. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3143. res.set_content("Hello World!", "text/plain");
  3144. });
  3145. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. {
  3153. Client cli("127.0.0.1", PORT);
  3154. auto res = cli.Get("/1");
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::OK_200, res->status);
  3157. EXPECT_EQ("Hello World!", res->body);
  3158. }
  3159. {
  3160. Client cli("::1", PORT);
  3161. auto res = cli.Get("/1");
  3162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3163. EXPECT_EQ(StatusCode::OK_200, res->status);
  3164. EXPECT_EQ("Hello World!", res->body);
  3165. }
  3166. }
  3167. TEST(BindServerTest, BindAndListenSeparately) {
  3168. Server svr;
  3169. int port = svr.bind_to_any_port("0.0.0.0");
  3170. ASSERT_TRUE(svr.is_valid());
  3171. ASSERT_TRUE(port > 0);
  3172. svr.stop();
  3173. }
  3174. // Reports whether anything is still listening on a loopback port. A plain
  3175. // connect() is used instead of a Client request because a socket left bound by
  3176. // mistake accepts the connection into its backlog and never answers, which
  3177. // would hang the test instead of failing it.
  3178. static bool is_loopback_port_accepting(int port) {
  3179. sockaddr_in addr{};
  3180. addr.sin_family = AF_INET;
  3181. addr.sin_port = htons(static_cast<uint16_t>(port));
  3182. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3183. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3184. EXPECT_NE(sock, INVALID_SOCKET);
  3185. if (sock == INVALID_SOCKET) { return false; }
  3186. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3187. static_cast<socklen_t>(sizeof(addr)));
  3188. detail::close_socket(sock);
  3189. return ret == 0;
  3190. }
  3191. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3192. Server svr;
  3193. auto port = svr.bind_to_any_port("127.0.0.1");
  3194. ASSERT_TRUE(port > 0);
  3195. svr.stop();
  3196. // bind_to_any_port() already called listen(2), so until stop() closed the
  3197. // descriptor the port kept accepting connections into the backlog. ASSERT
  3198. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3199. // below blocks forever in the accept loop.
  3200. ASSERT_FALSE(is_loopback_port_accepting(port));
  3201. // Nothing is left to accept on, so listen_after_bind() must report failure
  3202. // instead of returning success without ever serving.
  3203. EXPECT_FALSE(svr.listen_after_bind());
  3204. // The failed listen marks the server decommissioned, so a waiter returns
  3205. // instead of spinning forever.
  3206. svr.wait_until_ready();
  3207. }
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3211. CLIENT_CA_CERT_DIR);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. svr.stop();
  3216. }
  3217. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3218. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3219. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3220. int port = svr.bind_to_any_port("0.0.0.0");
  3221. ASSERT_TRUE(svr.is_valid());
  3222. ASSERT_TRUE(port > 0);
  3223. svr.stop();
  3224. }
  3225. TEST(BindServerTest, UpdateCertsPem) {
  3226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3227. int port = svr.bind_to_any_port("0.0.0.0");
  3228. ASSERT_TRUE(svr.is_valid());
  3229. ASSERT_TRUE(port > 0);
  3230. // Read PEM files
  3231. std::string cert_pem, key_pem, ca_pem;
  3232. read_file(SERVER_CERT_FILE, cert_pem);
  3233. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3234. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3235. // Update server certificates using PEM API
  3236. ASSERT_TRUE(
  3237. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3238. ASSERT_TRUE(svr.is_valid());
  3239. svr.stop();
  3240. }
  3241. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3242. // Start server with client CA (enables client auth)
  3243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3244. ASSERT_TRUE(svr.is_valid());
  3245. bool handler_called = false;
  3246. svr.Get("/test", [&](const Request &req, Response &res) {
  3247. handler_called = true;
  3248. // Verify client certificate is present
  3249. auto cert = req.peer_cert();
  3250. EXPECT_TRUE(static_cast<bool>(cert));
  3251. res.set_content("ok", "text/plain");
  3252. });
  3253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. t.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. svr.wait_until_ready();
  3260. // Read PEM files
  3261. std::string cert_pem, key_pem, ca_pem;
  3262. read_file(SERVER_CERT_FILE, cert_pem);
  3263. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3264. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3265. // Update server certificates and client CA using PEM API while server running
  3266. ASSERT_TRUE(
  3267. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3268. // Connect with client certificate
  3269. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3270. cli.enable_server_certificate_verification(false);
  3271. cli.set_connection_timeout(30);
  3272. auto res = cli.Get("/test");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_TRUE(handler_called);
  3276. EXPECT_EQ("ok", res->body);
  3277. }
  3278. #endif
  3279. TEST(ErrorHandlerTest, ContentLength) {
  3280. Server svr;
  3281. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3282. res.status = StatusCode::OK_200;
  3283. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3284. "text/html"); // <= Content-Length still 13
  3285. });
  3286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3287. res.set_content("Hello World!\n", "text/plain");
  3288. res.status = 524;
  3289. });
  3290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3291. auto se = detail::scope_exit([&] {
  3292. svr.stop();
  3293. thread.join();
  3294. ASSERT_FALSE(svr.is_running());
  3295. });
  3296. svr.wait_until_ready();
  3297. {
  3298. Client cli(HOST, PORT);
  3299. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3305. }
  3306. }
  3307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3308. TEST(ExceptionTest, WithoutExceptionHandler) {
  3309. Server svr;
  3310. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3311. throw std::runtime_error("exception...");
  3312. });
  3313. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3314. throw std::runtime_error("exception\r\n...");
  3315. });
  3316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3317. auto se = detail::scope_exit([&] {
  3318. svr.stop();
  3319. listen_thread.join();
  3320. ASSERT_FALSE(svr.is_running());
  3321. });
  3322. svr.wait_until_ready();
  3323. Client cli("localhost", PORT);
  3324. {
  3325. auto res = cli.Get("/exception");
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3328. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3329. }
  3330. {
  3331. auto res = cli.Get("/unknown");
  3332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3333. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3334. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3335. }
  3336. }
  3337. TEST(ExceptionTest, WithExceptionHandler) {
  3338. Server svr;
  3339. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3340. std::exception_ptr ep) {
  3341. EXPECT_FALSE(ep == nullptr);
  3342. try {
  3343. std::rethrow_exception(ep);
  3344. } catch (std::exception &e) {
  3345. EXPECT_EQ("abc", std::string(e.what()));
  3346. } catch (...) {}
  3347. res.status = StatusCode::InternalServerError_500;
  3348. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3349. "text/html"); // <= Content-Length still 13 at this point
  3350. });
  3351. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3352. res.set_content("Hello World!\n", "text/plain");
  3353. throw std::runtime_error("abc");
  3354. });
  3355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3356. auto se = detail::scope_exit([&] {
  3357. svr.stop();
  3358. thread.join();
  3359. ASSERT_FALSE(svr.is_running());
  3360. });
  3361. svr.wait_until_ready();
  3362. for (size_t i = 0; i < 10; i++) {
  3363. Client cli(HOST, PORT);
  3364. for (size_t j = 0; j < 100; j++) {
  3365. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3367. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3371. }
  3372. cli.set_keep_alive(true);
  3373. for (size_t j = 0; j < 100; j++) {
  3374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3376. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3380. }
  3381. }
  3382. }
  3383. TEST(ExceptionTest, AndErrorHandler) {
  3384. Server svr;
  3385. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3386. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3387. });
  3388. svr.set_exception_handler(
  3389. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3390. EXPECT_FALSE(ep == nullptr);
  3391. try {
  3392. std::rethrow_exception(ep);
  3393. } catch (std::exception &e) {
  3394. res.set_content(e.what(), "text/html");
  3395. } catch (...) {}
  3396. res.status = StatusCode::InternalServerError_500;
  3397. });
  3398. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3399. throw std::runtime_error("EXCEPTION");
  3400. });
  3401. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3402. res.set_content("ERROR", "text/html");
  3403. res.status = StatusCode::InternalServerError_500;
  3404. });
  3405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3406. auto se = detail::scope_exit([&] {
  3407. svr.stop();
  3408. thread.join();
  3409. ASSERT_FALSE(svr.is_running());
  3410. });
  3411. svr.wait_until_ready();
  3412. Client cli(HOST, PORT);
  3413. {
  3414. auto res = cli.Get("/exception");
  3415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3416. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3417. EXPECT_EQ("EXCEPTION", res->body);
  3418. }
  3419. {
  3420. auto res = cli.Get("/error");
  3421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3422. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3423. EXPECT_EQ("ERROR", res->body);
  3424. }
  3425. {
  3426. auto res = cli.Get("/invalid");
  3427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3428. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3429. EXPECT_EQ("NOT_FOUND", res->body);
  3430. }
  3431. }
  3432. #endif
  3433. TEST(NoContentTest, ContentLength) {
  3434. Server svr;
  3435. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3436. res.status = StatusCode::NoContent_204;
  3437. });
  3438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. {
  3446. Client cli(HOST, PORT);
  3447. auto res = cli.Get("/hi");
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3451. }
  3452. }
  3453. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3454. #ifdef CPPHTTPLIB_SSL_ENABLED
  3455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3456. ASSERT_TRUE(svr.is_valid());
  3457. #else
  3458. Server svr;
  3459. #endif
  3460. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3461. if (req.path == "/routing_handler") {
  3462. res.set_header("PRE_ROUTING", "on");
  3463. res.set_content("Routing Handler", "text/plain");
  3464. return httplib::Server::HandlerResponse::Handled;
  3465. }
  3466. return httplib::Server::HandlerResponse::Unhandled;
  3467. });
  3468. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3469. res.set_content("Error", "text/html");
  3470. });
  3471. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3472. if (req.path == "/routing_handler") {
  3473. res.set_header("POST_ROUTING", "on");
  3474. }
  3475. });
  3476. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3477. res.set_content("Hello World!\n", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. {
  3487. #ifdef CPPHTTPLIB_SSL_ENABLED
  3488. SSLClient cli(HOST, PORT);
  3489. cli.enable_server_certificate_verification(false);
  3490. #else
  3491. Client cli(HOST, PORT);
  3492. #endif
  3493. auto res = cli.Get("/routing_handler");
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Routing Handler", res->body);
  3497. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3498. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3499. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3500. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3501. }
  3502. {
  3503. #ifdef CPPHTTPLIB_SSL_ENABLED
  3504. SSLClient cli(HOST, PORT);
  3505. cli.enable_server_certificate_verification(false);
  3506. #else
  3507. Client cli(HOST, PORT);
  3508. #endif
  3509. auto res = cli.Get("/hi");
  3510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("Hello World!\n", res->body);
  3513. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3514. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3515. }
  3516. {
  3517. #ifdef CPPHTTPLIB_SSL_ENABLED
  3518. SSLClient cli(HOST, PORT);
  3519. cli.enable_server_certificate_verification(false);
  3520. #else
  3521. Client cli(HOST, PORT);
  3522. #endif
  3523. auto res = cli.Get("/aaa");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3526. EXPECT_EQ("Error", res->body);
  3527. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3528. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3529. }
  3530. }
  3531. TEST(RequestHandlerTest, PreRequestHandler) {
  3532. auto route_path = "/user/:user";
  3533. Server svr;
  3534. svr.Get("/hi", [](const Request &, Response &res) {
  3535. res.set_content("hi", "text/plain");
  3536. });
  3537. svr.Get(route_path, [](const Request &req, Response &res) {
  3538. res.set_content(req.path_params.at("user"), "text/plain");
  3539. });
  3540. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3541. if (req.matched_route == route_path) {
  3542. auto user = req.path_params.at("user");
  3543. if (user != "john") {
  3544. res.status = StatusCode::Forbidden_403;
  3545. res.set_content("error", "text/html");
  3546. return Server::HandlerResponse::Handled;
  3547. }
  3548. }
  3549. return Server::HandlerResponse::Unhandled;
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, PORT);
  3559. {
  3560. auto res = cli.Get("/hi");
  3561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3562. EXPECT_EQ(StatusCode::OK_200, res->status);
  3563. EXPECT_EQ("hi", res->body);
  3564. }
  3565. {
  3566. auto res = cli.Get("/user/john");
  3567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("john", res->body);
  3570. }
  3571. {
  3572. auto res = cli.Get("/user/invalid-user");
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3575. EXPECT_EQ("error", res->body);
  3576. }
  3577. }
  3578. // The pre-request handler must run before the request body is read, so a
  3579. // rejected request never forces the server to buffer a (potentially large)
  3580. // body. Here the posted body is larger than the payload limit: if the body
  3581. // were read first the server would answer 413, but because the pre-request
  3582. // handler runs first it answers 403 and the body is never read.
  3583. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3584. Server svr;
  3585. svr.set_payload_max_length(8);
  3586. auto handler_ran = false;
  3587. svr.Post("/reject", [&](const Request &req, Response &res) {
  3588. handler_ran = true;
  3589. res.set_content(req.body, "text/plain");
  3590. });
  3591. svr.Post("/accept", [](const Request &req, Response &res) {
  3592. res.set_content(req.body, "text/plain");
  3593. });
  3594. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3595. if (req.matched_route == "/reject") {
  3596. res.status = StatusCode::Forbidden_403;
  3597. res.set_content("denied", "text/plain");
  3598. return Server::HandlerResponse::Handled;
  3599. }
  3600. return Server::HandlerResponse::Unhandled;
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. Client cli(HOST, PORT);
  3610. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3611. // rejects with 403 before the body is read, so 413 is never reached.
  3612. {
  3613. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3616. EXPECT_EQ("denied", res->body);
  3617. EXPECT_FALSE(handler_ran);
  3618. }
  3619. // An approved route still reads the body and enforces the payload limit.
  3620. {
  3621. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3624. }
  3625. }
  3626. TEST(UserDataTest, BasicOperations) {
  3627. httplib::UserData ud;
  3628. // Initially empty
  3629. EXPECT_FALSE(ud.has("key"));
  3630. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3631. // set and get
  3632. ud.set("key", 42);
  3633. EXPECT_TRUE(ud.has("key"));
  3634. auto *p = ud.get<int>("key");
  3635. ASSERT_NE(nullptr, p);
  3636. EXPECT_EQ(42, *p);
  3637. // Type mismatch → nullptr
  3638. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3639. // Overwrite with different type
  3640. ud.set("key", std::string("hello"));
  3641. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3642. auto *s = ud.get<std::string>("key");
  3643. ASSERT_NE(nullptr, s);
  3644. EXPECT_EQ("hello", *s);
  3645. // erase
  3646. ud.erase("key");
  3647. EXPECT_FALSE(ud.has("key"));
  3648. // clear
  3649. ud.set("a", 1);
  3650. ud.set("b", 2);
  3651. ud.clear();
  3652. EXPECT_FALSE(ud.has("a"));
  3653. EXPECT_FALSE(ud.has("b"));
  3654. }
  3655. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3656. struct AuthCtx {
  3657. std::string user_id;
  3658. };
  3659. Server svr;
  3660. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3661. res.user_data.set("auth", AuthCtx{"alice"});
  3662. return Server::HandlerResponse::Unhandled;
  3663. });
  3664. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3665. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3666. ASSERT_NE(nullptr, ctx);
  3667. res.set_content("Hello " + ctx->user_id, "text/plain");
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. Client cli(HOST, PORT);
  3677. auto res = cli.Get("/me");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("Hello alice", res->body);
  3681. }
  3682. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3683. struct RoleCtx {
  3684. std::string role;
  3685. };
  3686. Server svr;
  3687. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3688. res.user_data.set("role", RoleCtx{"admin"});
  3689. return Server::HandlerResponse::Unhandled;
  3690. });
  3691. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3692. auto *ctx = res.user_data.get<RoleCtx>("role");
  3693. ASSERT_NE(nullptr, ctx);
  3694. res.set_content(ctx->role, "text/plain");
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. Client cli(HOST, PORT);
  3704. auto res = cli.Get("/role");
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("admin", res->body);
  3708. }
  3709. TEST(InvalidFormatTest, StatusCode) {
  3710. Server svr;
  3711. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3712. res.set_content("Hello World!\n", "text/plain");
  3713. res.status = 9999; // Status should be a three-digit code...
  3714. });
  3715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3716. auto se = detail::scope_exit([&] {
  3717. svr.stop();
  3718. thread.join();
  3719. ASSERT_FALSE(svr.is_running());
  3720. });
  3721. svr.wait_until_ready();
  3722. {
  3723. Client cli(HOST, PORT);
  3724. auto res = cli.Get("/hi");
  3725. ASSERT_FALSE(res);
  3726. }
  3727. }
  3728. TEST(URLFragmentTest, WithFragment) {
  3729. Server svr;
  3730. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3731. EXPECT_TRUE(req.target == "/hi");
  3732. });
  3733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. thread.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. svr.wait_until_ready();
  3740. {
  3741. Client cli(HOST, PORT);
  3742. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3743. EXPECT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. res = cli.Get("/hi%23key1=val1=key2=val2");
  3746. EXPECT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. }
  3750. TEST(HeaderWriter, SetHeaderWriter) {
  3751. Server svr;
  3752. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3753. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3754. return detail::write_headers(strm, hdrs);
  3755. });
  3756. svr.Get("/hi", [](const Request &req, Response &res) {
  3757. auto it = req.headers.find("CustomClientHeader");
  3758. EXPECT_TRUE(it != req.headers.end());
  3759. EXPECT_EQ(it->second, "CustomClientValue");
  3760. res.set_content("Hello World!\n", "text/plain");
  3761. });
  3762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3763. auto se = detail::scope_exit([&] {
  3764. svr.stop();
  3765. thread.join();
  3766. ASSERT_FALSE(svr.is_running());
  3767. });
  3768. svr.wait_until_ready();
  3769. {
  3770. Client cli(HOST, PORT);
  3771. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3772. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3773. return detail::write_headers(strm, hdrs);
  3774. });
  3775. auto res = cli.Get("/hi");
  3776. EXPECT_TRUE(res);
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. auto it = res->headers.find("CustomServerHeader");
  3779. EXPECT_TRUE(it != res->headers.end());
  3780. EXPECT_EQ(it->second, "CustomServerValue");
  3781. }
  3782. }
  3783. class ServerTest : public ::testing::Test {
  3784. protected:
  3785. ServerTest()
  3786. : cli_(HOST, PORT)
  3787. #ifdef CPPHTTPLIB_SSL_ENABLED
  3788. ,
  3789. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3790. #endif
  3791. {
  3792. #ifdef CPPHTTPLIB_SSL_ENABLED
  3793. cli_.enable_server_certificate_verification(false);
  3794. #endif
  3795. // Allow LARGE_DATA (100MB) responses
  3796. cli_.set_payload_max_length(200 * 1024 * 1024);
  3797. }
  3798. virtual void SetUp() {
  3799. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3800. svr_.set_payload_max_length(200 * 1024 * 1024);
  3801. svr_.set_mount_point("/", "./www");
  3802. svr_.set_mount_point("/mount", "./www2");
  3803. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3804. svr_.Get("/hi",
  3805. [&](const Request & /*req*/, Response &res) {
  3806. res.set_content("Hello World!", "text/plain");
  3807. })
  3808. .Get("/file_content",
  3809. [&](const Request & /*req*/, Response &res) {
  3810. res.set_file_content("./www/dir/test.html");
  3811. })
  3812. .Get("/file_content_with_content_type",
  3813. [&](const Request & /*req*/, Response &res) {
  3814. res.set_file_content("./www/file", "text/plain");
  3815. })
  3816. .Get("/invalid_file_content",
  3817. [&](const Request & /*req*/, Response &res) {
  3818. res.set_file_content("./www/dir/invalid_file_path");
  3819. })
  3820. .Get("/http_response_splitting",
  3821. [&](const Request & /*req*/, Response &res) {
  3822. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_header("a", "1\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("a"));
  3828. res.set_header("a", "1\rSet-Cookie: a=1");
  3829. EXPECT_EQ(0U, res.headers.size());
  3830. EXPECT_FALSE(res.has_header("a"));
  3831. res.set_header("a\r\nb", "0");
  3832. EXPECT_EQ(0U, res.headers.size());
  3833. EXPECT_FALSE(res.has_header("a"));
  3834. res.set_header("a\rb", "0");
  3835. EXPECT_EQ(0U, res.headers.size());
  3836. EXPECT_FALSE(res.has_header("a"));
  3837. res.set_header("a\nb", "0");
  3838. EXPECT_EQ(0U, res.headers.size());
  3839. EXPECT_FALSE(res.has_header("a"));
  3840. res.set_redirect("1\r\nSet-Cookie: a=1");
  3841. EXPECT_EQ(0U, res.headers.size());
  3842. EXPECT_FALSE(res.has_header("Location"));
  3843. })
  3844. .Get("/slow",
  3845. [&](const Request & /*req*/, Response &res) {
  3846. std::this_thread::sleep_for(std::chrono::seconds(4));
  3847. res.set_content("slow", "text/plain");
  3848. })
  3849. #if 0
  3850. .Post("/slowpost",
  3851. [&](const Request & /*req*/, Response &res) {
  3852. std::this_thread::sleep_for(std::chrono::seconds(2));
  3853. res.set_content("slow", "text/plain");
  3854. })
  3855. #endif
  3856. .Get("/remote_addr",
  3857. [&](const Request &req, Response &res) {
  3858. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3859. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3860. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3861. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3862. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3863. #endif
  3864. res.set_content(req.remote_addr, "text/plain");
  3865. })
  3866. .Get("/local_addr",
  3867. [&](const Request &req, Response &res) {
  3868. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3869. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3871. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3872. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3873. #endif
  3874. auto local_addr = req.local_addr;
  3875. auto local_port = std::to_string(req.local_port);
  3876. res.set_content(local_addr.append(":").append(local_port),
  3877. "text/plain");
  3878. })
  3879. .Get("/endwith%",
  3880. [&](const Request & /*req*/, Response &res) {
  3881. res.set_content("Hello World!", "text/plain");
  3882. })
  3883. .Get("/a\\+\\+b",
  3884. [&](const Request &req, Response &res) {
  3885. ASSERT_TRUE(req.has_param("a +b"));
  3886. auto val = req.get_param_value("a +b");
  3887. res.set_content(val, "text/plain");
  3888. })
  3889. .Get("/", [&](const Request & /*req*/,
  3890. Response &res) { res.set_redirect("/hi"); })
  3891. .Post("/1",
  3892. [](const Request & /*req*/, Response &res) {
  3893. res.set_redirect("/2", StatusCode::SeeOther_303);
  3894. })
  3895. .Get("/2",
  3896. [](const Request & /*req*/, Response &res) {
  3897. res.set_content("redirected.", "text/plain");
  3898. res.status = StatusCode::OK_200;
  3899. })
  3900. .Post("/person",
  3901. [&](const Request &req, Response &res) {
  3902. if (req.has_param("name") && req.has_param("note")) {
  3903. persons_[req.get_param_value("name")] =
  3904. req.get_param_value("note");
  3905. } else {
  3906. res.status = StatusCode::BadRequest_400;
  3907. }
  3908. })
  3909. .Put("/person",
  3910. [&](const Request &req, Response &res) {
  3911. if (req.has_param("name") && req.has_param("note")) {
  3912. persons_[req.get_param_value("name")] =
  3913. req.get_param_value("note");
  3914. } else {
  3915. res.status = StatusCode::BadRequest_400;
  3916. }
  3917. })
  3918. .Get("/person/(.*)",
  3919. [&](const Request &req, Response &res) {
  3920. string name = req.matches[1];
  3921. if (persons_.find(name) != persons_.end()) {
  3922. auto note = persons_[name];
  3923. res.set_content(note, "text/plain");
  3924. } else {
  3925. res.status = StatusCode::NotFound_404;
  3926. }
  3927. })
  3928. .Delete("/person",
  3929. [&](const Request &req, Response &res) {
  3930. if (req.has_param("name")) {
  3931. string name = req.get_param_value("name");
  3932. if (persons_.find(name) != persons_.end()) {
  3933. persons_.erase(name);
  3934. res.set_content("DELETED", "text/plain");
  3935. } else {
  3936. res.status = StatusCode::NotFound_404;
  3937. }
  3938. } else {
  3939. res.status = StatusCode::BadRequest_400;
  3940. }
  3941. })
  3942. .Post("/x-www-form-urlencoded-json",
  3943. [&](const Request &req, Response &res) {
  3944. auto json = req.get_param_value("json");
  3945. ASSERT_EQ(JSON_DATA, json);
  3946. res.set_content(json, "appliation/json");
  3947. res.status = StatusCode::OK_200;
  3948. })
  3949. .Get("/streamed-chunked",
  3950. [&](const Request & /*req*/, Response &res) {
  3951. res.set_chunked_content_provider(
  3952. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3953. sink.os << "123";
  3954. sink.os << "456";
  3955. sink.os << "789";
  3956. sink.done();
  3957. return true;
  3958. });
  3959. })
  3960. .Get("/streamed-chunked-with-prohibited-trailer",
  3961. [&](const Request & /*req*/, Response &res) {
  3962. auto i = new int(0);
  3963. // Declare both a prohibited trailer (Content-Length) and an
  3964. // allowed one
  3965. res.set_header("Trailer", "Content-Length, X-Allowed");
  3966. res.set_chunked_content_provider(
  3967. "text/plain",
  3968. [i](size_t /*offset*/, DataSink &sink) {
  3969. switch (*i) {
  3970. case 0: sink.os << "123"; break;
  3971. case 1: sink.os << "456"; break;
  3972. case 2: sink.os << "789"; break;
  3973. case 3: {
  3974. sink.done_with_trailer(
  3975. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3976. } break;
  3977. }
  3978. (*i)++;
  3979. return true;
  3980. },
  3981. [i](bool success) {
  3982. EXPECT_TRUE(success);
  3983. delete i;
  3984. });
  3985. })
  3986. .Get("/streamed-chunked2",
  3987. [&](const Request & /*req*/, Response &res) {
  3988. auto i = new int(0);
  3989. res.set_chunked_content_provider(
  3990. "text/plain",
  3991. [i](size_t /*offset*/, DataSink &sink) {
  3992. switch (*i) {
  3993. case 0: sink.os << "123"; break;
  3994. case 1: sink.os << "456"; break;
  3995. case 2: sink.os << "789"; break;
  3996. case 3: sink.done(); break;
  3997. }
  3998. (*i)++;
  3999. return true;
  4000. },
  4001. [i](bool success) {
  4002. EXPECT_TRUE(success);
  4003. delete i;
  4004. });
  4005. })
  4006. .Get("/streamed-chunked-with-trailer",
  4007. [&](const Request & /*req*/, Response &res) {
  4008. auto i = new int(0);
  4009. res.set_header("Trailer", "Dummy1, Dummy2");
  4010. res.set_chunked_content_provider(
  4011. "text/plain",
  4012. [i](size_t /*offset*/, DataSink &sink) {
  4013. switch (*i) {
  4014. case 0: sink.os << "123"; break;
  4015. case 1: sink.os << "456"; break;
  4016. case 2: sink.os << "789"; break;
  4017. case 3: {
  4018. sink.done_with_trailer(
  4019. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4020. } break;
  4021. }
  4022. (*i)++;
  4023. return true;
  4024. },
  4025. [i](bool success) {
  4026. EXPECT_TRUE(success);
  4027. delete i;
  4028. });
  4029. })
  4030. .Get("/streamed",
  4031. [&](const Request & /*req*/, Response &res) {
  4032. res.set_content_provider(
  4033. 6, "text/plain",
  4034. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4035. sink.os << (offset < 3 ? "a" : "b");
  4036. return true;
  4037. });
  4038. })
  4039. .Get("/streamed-without-length",
  4040. [&](const Request & /*req*/, Response &res) {
  4041. auto data = new std::string("abcdefg");
  4042. res.set_content_provider(
  4043. "text/plain",
  4044. [data](size_t offset, DataSink &sink) {
  4045. if (offset < data->size()) {
  4046. sink.os << data->substr(offset);
  4047. }
  4048. sink.done();
  4049. return true;
  4050. },
  4051. [data](bool success) {
  4052. EXPECT_TRUE(success);
  4053. delete data;
  4054. });
  4055. })
  4056. .Get("/streamed-with-range",
  4057. [&](const Request &req, Response &res) {
  4058. auto data = new std::string("abcdefg");
  4059. // An explicit status keeps the server from picking the 206 it
  4060. // would otherwise choose for a ranged request, so the response
  4061. // is not a partial representation.
  4062. auto status = req.get_param_value("status");
  4063. if (status == "200") {
  4064. res.status = StatusCode::OK_200;
  4065. } else if (status == "403") {
  4066. res.status = StatusCode::Forbidden_403;
  4067. }
  4068. res.set_content_provider(
  4069. data->size(), "text/plain",
  4070. [data](size_t offset, size_t length, DataSink &sink) {
  4071. size_t DATA_CHUNK_SIZE = 4;
  4072. const auto &d = *data;
  4073. auto out_len =
  4074. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4075. auto ret =
  4076. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4077. EXPECT_TRUE(ret);
  4078. return true;
  4079. },
  4080. [data, &req](bool success) {
  4081. EXPECT_EQ(success, !req.has_param("error"));
  4082. delete data;
  4083. });
  4084. })
  4085. .Get("/streamed-cancel",
  4086. [&](const Request & /*req*/, Response &res) {
  4087. res.set_content_provider(
  4088. size_t(-1), "text/plain",
  4089. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4090. sink.os << "data_chunk";
  4091. return true;
  4092. });
  4093. })
  4094. .Get("/regex-with-delimiter",
  4095. [&](const Request &req, Response & /*res*/) {
  4096. ASSERT_TRUE(req.has_param("key"));
  4097. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4098. })
  4099. .Get("/with-range",
  4100. [&](const Request & /*req*/, Response &res) {
  4101. res.set_content("abcdefg", "text/plain");
  4102. })
  4103. .Get("/test-start-time",
  4104. [&](const Request &req, Response & /*res*/) {
  4105. EXPECT_NE(req.start_time_,
  4106. std::chrono::steady_clock::time_point::min());
  4107. })
  4108. .Get("/with-range-customized-response",
  4109. [&](const Request & /*req*/, Response &res) {
  4110. res.status = StatusCode::BadRequest_400;
  4111. res.set_content(JSON_DATA, "application/json");
  4112. })
  4113. .Post("/chunked",
  4114. [&](const Request &req, Response & /*res*/) {
  4115. EXPECT_EQ(req.body, "dechunked post body");
  4116. })
  4117. .Post("/large-chunked",
  4118. [&](const Request &req, Response & /*res*/) {
  4119. std::string expected(6 * 30 * 1024u, 'a');
  4120. EXPECT_EQ(req.body, expected);
  4121. })
  4122. .Post("/multipart",
  4123. [&](const Request &req, Response & /*res*/) {
  4124. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4125. req.form.get_field_count("text2") +
  4126. req.form.get_field_count("file3") +
  4127. req.form.get_field_count("file4"));
  4128. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4129. req.form.get_file_count("file2"));
  4130. ASSERT_TRUE(!req.form.has_file("???"));
  4131. ASSERT_TRUE(!req.form.has_field("???"));
  4132. ASSERT_TRUE(req.body.empty());
  4133. {
  4134. const auto &text = req.form.get_field("text1");
  4135. EXPECT_EQ("text default", text);
  4136. }
  4137. {
  4138. const auto &text = req.form.get_field("text2");
  4139. EXPECT_EQ("aωb", text);
  4140. }
  4141. {
  4142. const auto &file = req.form.get_file("file1");
  4143. EXPECT_EQ("hello.txt", file.filename);
  4144. EXPECT_EQ("text/plain", file.content_type);
  4145. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4146. }
  4147. {
  4148. const auto &file = req.form.get_file("file2");
  4149. EXPECT_EQ("world.json", file.filename);
  4150. EXPECT_EQ("application/json", file.content_type);
  4151. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4152. }
  4153. {
  4154. const auto &text = req.form.get_field("file3");
  4155. EXPECT_EQ(0u, text.size());
  4156. }
  4157. {
  4158. const auto &text = req.form.get_field("file4");
  4159. EXPECT_EQ(0u, text.size());
  4160. }
  4161. })
  4162. .Post("/multipart/multi_file_values",
  4163. [&](const Request &req, Response & /*res*/) {
  4164. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4165. req.form.get_field_count("multi_text1"));
  4166. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4167. ASSERT_TRUE(!req.form.has_file("???"));
  4168. ASSERT_TRUE(!req.form.has_field("???"));
  4169. ASSERT_TRUE(req.body.empty());
  4170. {
  4171. const auto &text = req.form.get_field("text");
  4172. EXPECT_EQ("default text", text);
  4173. }
  4174. {
  4175. const auto &text1_values = req.form.get_fields("multi_text1");
  4176. EXPECT_EQ(2u, text1_values.size());
  4177. EXPECT_EQ("aaaaa", text1_values[0]);
  4178. EXPECT_EQ("bbbbb", text1_values[1]);
  4179. }
  4180. {
  4181. const auto &file1_values = req.form.get_files("multi_file1");
  4182. EXPECT_EQ(2u, file1_values.size());
  4183. auto file1 = file1_values[0];
  4184. EXPECT_EQ(file1.filename, "hello.txt");
  4185. EXPECT_EQ(file1.content_type, "text/plain");
  4186. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4187. auto file2 = file1_values[1];
  4188. EXPECT_EQ(file2.filename, "world.json");
  4189. EXPECT_EQ(file2.content_type, "application/json");
  4190. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4191. }
  4192. })
  4193. .Post("/empty",
  4194. [&](const Request &req, Response &res) {
  4195. EXPECT_EQ(req.body, "");
  4196. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4198. res.set_content("empty", "text/plain");
  4199. })
  4200. .Post("/empty-no-content-type",
  4201. [&](const Request &req, Response &res) {
  4202. EXPECT_EQ(req.body, "");
  4203. EXPECT_FALSE(req.has_header("Content-Type"));
  4204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4205. res.set_content("empty-no-content-type", "text/plain");
  4206. })
  4207. .Post("/path-only",
  4208. [&](const Request &req, Response &res) {
  4209. EXPECT_EQ(req.body, "");
  4210. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4212. res.set_content("path-only", "text/plain");
  4213. })
  4214. .Post("/path-headers-only",
  4215. [&](const Request &req, Response &res) {
  4216. EXPECT_EQ(req.body, "");
  4217. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4218. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4219. EXPECT_EQ("world", req.get_header_value("hello"));
  4220. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4221. res.set_content("path-headers-only", "text/plain");
  4222. })
  4223. .Post("/post-large",
  4224. [&](const Request &req, Response &res) {
  4225. EXPECT_EQ(req.body, LARGE_DATA);
  4226. res.set_content(req.body, "text/plain");
  4227. })
  4228. .Post("/post-loopback",
  4229. [&](const Request &, Response &res,
  4230. ContentReader const &content_reader) {
  4231. std::string body;
  4232. content_reader([&](const char *data, size_t data_length) {
  4233. body.append(data, data_length);
  4234. return true;
  4235. });
  4236. res.set_content(body, "text/plain");
  4237. })
  4238. .Put("/put-loopback",
  4239. [&](const Request &, Response &res,
  4240. ContentReader const &content_reader) {
  4241. std::string body;
  4242. content_reader([&](const char *data, size_t data_length) {
  4243. body.append(data, data_length);
  4244. return true;
  4245. });
  4246. res.set_content(body, "text/plain");
  4247. })
  4248. .Patch("/patch-loopback",
  4249. [&](const Request &, Response &res,
  4250. ContentReader const &content_reader) {
  4251. std::string body;
  4252. content_reader([&](const char *data, size_t data_length) {
  4253. body.append(data, data_length);
  4254. return true;
  4255. });
  4256. res.set_content(body, "text/plain");
  4257. })
  4258. .Put("/empty-no-content-type",
  4259. [&](const Request &req, Response &res) {
  4260. EXPECT_EQ(req.body, "");
  4261. EXPECT_FALSE(req.has_header("Content-Type"));
  4262. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4263. res.set_content("empty-no-content-type", "text/plain");
  4264. })
  4265. .Put("/put",
  4266. [&](const Request &req, Response &res) {
  4267. EXPECT_EQ(req.body, "PUT");
  4268. res.set_content(req.body, "text/plain");
  4269. })
  4270. .Put("/put-large",
  4271. [&](const Request &req, Response &res) {
  4272. EXPECT_EQ(req.body, LARGE_DATA);
  4273. res.set_content(req.body, "text/plain");
  4274. })
  4275. .Patch("/patch",
  4276. [&](const Request &req, Response &res) {
  4277. EXPECT_EQ(req.body, "PATCH");
  4278. res.set_content(req.body, "text/plain");
  4279. })
  4280. .Delete("/delete",
  4281. [&](const Request & /*req*/, Response &res) {
  4282. res.set_content("DELETE", "text/plain");
  4283. })
  4284. .Delete("/delete-body",
  4285. [&](const Request &req, Response &res) {
  4286. EXPECT_EQ(req.body, "content");
  4287. res.set_content(req.body, "text/plain");
  4288. })
  4289. .Options(R"(\*)",
  4290. [&](const Request & /*req*/, Response &res) {
  4291. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4292. })
  4293. .Get("/request-target",
  4294. [&](const Request &req, Response & /*res*/) {
  4295. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4296. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4297. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4298. })
  4299. .Get("/long-query-value",
  4300. [&](const Request &req, Response & /*res*/) {
  4301. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4302. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4303. })
  4304. .Get("/too-long-query-value",
  4305. [&](const Request &req, Response & /*res*/) {
  4306. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4307. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4308. })
  4309. .Get("/array-param",
  4310. [&](const Request &req, Response & /*res*/) {
  4311. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4312. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4313. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4314. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4315. })
  4316. .Get("/array-param-values",
  4317. [&](const Request &req, Response & /*res*/) {
  4318. auto values = req.get_param_values("array");
  4319. EXPECT_EQ(3u, values.size());
  4320. EXPECT_EQ("value1", values[0]);
  4321. EXPECT_EQ("value2", values[1]);
  4322. EXPECT_EQ("value3", values[2]);
  4323. auto empty = req.get_param_values("nonexistent");
  4324. EXPECT_TRUE(empty.empty());
  4325. })
  4326. .Post("/validate-no-multiple-headers",
  4327. [&](const Request &req, Response & /*res*/) {
  4328. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4329. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4330. })
  4331. .Post("/content_receiver",
  4332. [&](const Request &req, Response &res,
  4333. const ContentReader &content_reader) {
  4334. if (req.is_multipart_form_data()) {
  4335. std::vector<FormData> items;
  4336. content_reader(
  4337. [&](const FormData &file) {
  4338. items.push_back(file);
  4339. return true;
  4340. },
  4341. [&](const char *data, size_t data_length) {
  4342. items.back().content.append(data, data_length);
  4343. return true;
  4344. });
  4345. EXPECT_EQ(5u, items.size());
  4346. {
  4347. const auto &file = get_file_value(items, "text1");
  4348. EXPECT_TRUE(file.filename.empty());
  4349. EXPECT_EQ("text default", file.content);
  4350. }
  4351. {
  4352. const auto &file = get_file_value(items, "text2");
  4353. EXPECT_TRUE(file.filename.empty());
  4354. EXPECT_EQ("aωb", file.content);
  4355. }
  4356. {
  4357. const auto &file = get_file_value(items, "file1");
  4358. EXPECT_EQ("hello.txt", file.filename);
  4359. EXPECT_EQ("text/plain", file.content_type);
  4360. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4361. }
  4362. {
  4363. const auto &file = get_file_value(items, "file2");
  4364. EXPECT_EQ("world.json", file.filename);
  4365. EXPECT_EQ("application/json", file.content_type);
  4366. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4367. }
  4368. {
  4369. const auto &file = get_file_value(items, "file3");
  4370. EXPECT_TRUE(file.filename.empty());
  4371. EXPECT_EQ("application/octet-stream", file.content_type);
  4372. EXPECT_EQ(0u, file.content.size());
  4373. }
  4374. } else {
  4375. std::string body;
  4376. content_reader([&](const char *data, size_t data_length) {
  4377. EXPECT_EQ(7U, data_length);
  4378. body.append(data, data_length);
  4379. return true;
  4380. });
  4381. EXPECT_EQ(body, "content");
  4382. res.set_content(body, "text/plain");
  4383. }
  4384. })
  4385. .Put("/content_receiver",
  4386. [&](const Request & /*req*/, Response &res,
  4387. const ContentReader &content_reader) {
  4388. std::string body;
  4389. content_reader([&](const char *data, size_t data_length) {
  4390. body.append(data, data_length);
  4391. return true;
  4392. });
  4393. EXPECT_EQ(body, "content");
  4394. res.set_content(body, "text/plain");
  4395. })
  4396. .Patch("/content_receiver",
  4397. [&](const Request & /*req*/, Response &res,
  4398. const ContentReader &content_reader) {
  4399. std::string body;
  4400. content_reader([&](const char *data, size_t data_length) {
  4401. body.append(data, data_length);
  4402. return true;
  4403. });
  4404. EXPECT_EQ(body, "content");
  4405. res.set_content(body, "text/plain");
  4406. })
  4407. .Post("/query-string-and-body",
  4408. [&](const Request &req, Response & /*res*/) {
  4409. ASSERT_TRUE(req.has_param("key"));
  4410. EXPECT_EQ(req.get_param_value("key"), "value");
  4411. EXPECT_EQ(req.body, "content");
  4412. })
  4413. .Get("/last-request",
  4414. [&](const Request &req, Response & /*res*/) {
  4415. EXPECT_EQ("close", req.get_header_value("Connection"));
  4416. })
  4417. .Get(R"(/redirect/(\d+))",
  4418. [&](const Request &req, Response &res) {
  4419. auto num = std::stoi(req.matches[1]) + 1;
  4420. std::string url = "/redirect/" + std::to_string(num);
  4421. res.set_redirect(url);
  4422. })
  4423. .Post("/binary",
  4424. [&](const Request &req, Response &res) {
  4425. EXPECT_EQ(4U, req.body.size());
  4426. EXPECT_EQ("application/octet-stream",
  4427. req.get_header_value("Content-Type"));
  4428. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4429. res.set_content(req.body, "application/octet-stream");
  4430. })
  4431. .Put("/binary",
  4432. [&](const Request &req, Response &res) {
  4433. EXPECT_EQ(4U, req.body.size());
  4434. EXPECT_EQ("application/octet-stream",
  4435. req.get_header_value("Content-Type"));
  4436. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4437. res.set_content(req.body, "application/octet-stream");
  4438. })
  4439. .Patch("/binary",
  4440. [&](const Request &req, Response &res) {
  4441. EXPECT_EQ(4U, req.body.size());
  4442. EXPECT_EQ("application/octet-stream",
  4443. req.get_header_value("Content-Type"));
  4444. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4445. res.set_content(req.body, "application/octet-stream");
  4446. })
  4447. .Delete("/binary",
  4448. [&](const Request &req, Response &res) {
  4449. EXPECT_EQ(4U, req.body.size());
  4450. EXPECT_EQ("application/octet-stream",
  4451. req.get_header_value("Content-Type"));
  4452. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4453. res.set_content(req.body, "application/octet-stream");
  4454. })
  4455. .Get("/issue1772",
  4456. [&](const Request & /*req*/, Response &res) {
  4457. res.status = 401;
  4458. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4459. })
  4460. .Delete("/issue609",
  4461. [](const httplib::Request &, httplib::Response &res,
  4462. const httplib::ContentReader &) {
  4463. res.set_content("ok", "text/plain");
  4464. })
  4465. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4466. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4467. .Get("/compress",
  4468. [&](const Request & /*req*/, Response &res) {
  4469. res.set_content(
  4470. "12345678901234567890123456789012345678901234567890123456789"
  4471. "01234567890123456789012345678901234567890",
  4472. "text/plain");
  4473. })
  4474. .Get("/compress-with-charset",
  4475. [&](const Request & /*req*/, Response &res) {
  4476. res.set_content(
  4477. "12345678901234567890123456789012345678901234567890123456789"
  4478. "01234567890123456789012345678901234567890",
  4479. "application/json; charset=utf-8");
  4480. })
  4481. .Get("/nocompress",
  4482. [&](const Request & /*req*/, Response &res) {
  4483. res.set_content(
  4484. "12345678901234567890123456789012345678901234567890123456789"
  4485. "01234567890123456789012345678901234567890",
  4486. "application/octet-stream");
  4487. })
  4488. .Post("/compress-multipart",
  4489. [&](const Request &req, Response & /*res*/) {
  4490. EXPECT_EQ(2u, req.form.fields.size());
  4491. ASSERT_TRUE(!req.form.has_field("???"));
  4492. {
  4493. const auto &text = req.form.get_field("key1");
  4494. EXPECT_EQ("test", text);
  4495. }
  4496. {
  4497. const auto &text = req.form.get_field("key2");
  4498. EXPECT_EQ("--abcdefg123", text);
  4499. }
  4500. })
  4501. #endif
  4502. ;
  4503. persons_["john"] = "programmer";
  4504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4505. svr_.wait_until_ready();
  4506. }
  4507. virtual void TearDown() {
  4508. svr_.stop();
  4509. if (!request_threads_.empty()) {
  4510. std::this_thread::sleep_for(std::chrono::seconds(1));
  4511. for (auto &t : request_threads_) {
  4512. t.join();
  4513. }
  4514. }
  4515. t_.join();
  4516. }
  4517. map<string, string> persons_;
  4518. #ifdef CPPHTTPLIB_SSL_ENABLED
  4519. SSLClient cli_;
  4520. SSLServer svr_;
  4521. #else
  4522. Client cli_;
  4523. Server svr_;
  4524. #endif
  4525. thread t_;
  4526. std::vector<thread> request_threads_;
  4527. };
  4528. TEST_F(ServerTest, GetMethod200) {
  4529. auto res = cli_.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ("HTTP/1.1", res->version);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. EXPECT_EQ("OK", res->reason);
  4534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4535. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4536. EXPECT_EQ("Hello World!", res->body);
  4537. }
  4538. TEST_F(ServerTest, GetEmptyFile) {
  4539. auto res = cli_.Get("/empty_file");
  4540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4543. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4544. EXPECT_EQ("", res->body);
  4545. }
  4546. TEST_F(ServerTest, GetFileContent) {
  4547. auto res = cli_.Get("/file_content");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4551. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4552. EXPECT_EQ("test.html", res->body);
  4553. }
  4554. TEST_F(ServerTest, GetFileContentWithRange) {
  4555. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4559. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4560. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4561. EXPECT_EQ("est", res->body);
  4562. }
  4563. TEST_F(ServerTest, GetFileContentWithContentType) {
  4564. auto res = cli_.Get("/file_content_with_content_type");
  4565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4568. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4569. EXPECT_EQ("file\n", res->body);
  4570. }
  4571. TEST_F(ServerTest, GetInvalidFileContent) {
  4572. auto res = cli_.Get("/invalid_file_content");
  4573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4575. }
  4576. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4577. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ("HTTP/1.1", res->version);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4582. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4583. EXPECT_EQ("Hello World!", res->body);
  4584. }
  4585. TEST_F(ServerTest, GetMethod302) {
  4586. auto res = cli_.Get("/");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::Found_302, res->status);
  4589. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4590. }
  4591. TEST_F(ServerTest, GetMethod302Redirect) {
  4592. cli_.set_follow_location(true);
  4593. auto res = cli_.Get("/");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ("Hello World!", res->body);
  4597. EXPECT_EQ("/hi", res->location);
  4598. }
  4599. TEST_F(ServerTest, GetMethod404) {
  4600. auto res = cli_.Get("/invalid");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4603. }
  4604. TEST_F(ServerTest, HeadMethod200) {
  4605. auto res = cli_.Head("/hi");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4609. EXPECT_TRUE(res->body.empty());
  4610. }
  4611. TEST_F(ServerTest, HeadMethod200Static) {
  4612. auto res = cli_.Head("/mount/dir/index.html");
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. EXPECT_EQ(StatusCode::OK_200, res->status);
  4615. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4616. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4617. EXPECT_TRUE(res->body.empty());
  4618. }
  4619. TEST_F(ServerTest, HeadMethod404) {
  4620. auto res = cli_.Head("/invalid");
  4621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4623. EXPECT_TRUE(res->body.empty());
  4624. }
  4625. TEST_F(ServerTest, GetMethodPersonJohn) {
  4626. auto res = cli_.Get("/person/john");
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("programmer", res->body);
  4631. }
  4632. TEST_F(ServerTest, PostMethod1) {
  4633. auto res = cli_.Get("/person/john1");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4636. res = cli_.Post("/person", "name=john1&note=coder",
  4637. "application/x-www-form-urlencoded");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. ASSERT_EQ(StatusCode::OK_200, res->status);
  4640. res = cli_.Get("/person/john1");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. ASSERT_EQ(StatusCode::OK_200, res->status);
  4643. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4644. ASSERT_EQ("coder", res->body);
  4645. }
  4646. TEST_F(ServerTest, PostMethod2) {
  4647. auto res = cli_.Get("/person/john2");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4650. Params params;
  4651. params.emplace("name", "john2");
  4652. params.emplace("note", "coder");
  4653. res = cli_.Post("/person", params);
  4654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4655. ASSERT_EQ(StatusCode::OK_200, res->status);
  4656. res = cli_.Get("/person/john2");
  4657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4658. ASSERT_EQ(StatusCode::OK_200, res->status);
  4659. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4660. ASSERT_EQ("coder", res->body);
  4661. }
  4662. TEST_F(ServerTest, PutMethod3) {
  4663. auto res = cli_.Get("/person/john3");
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4666. Params params;
  4667. params.emplace("name", "john3");
  4668. params.emplace("note", "coder");
  4669. res = cli_.Put("/person", params);
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. ASSERT_EQ(StatusCode::OK_200, res->status);
  4672. res = cli_.Get("/person/john3");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4676. ASSERT_EQ("coder", res->body);
  4677. }
  4678. TEST_F(ServerTest, DeleteMethod1) {
  4679. auto res = cli_.Get("/person/john4");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4682. Params params;
  4683. params.emplace("name", "john4");
  4684. params.emplace("note", "coder");
  4685. res = cli_.Post("/person", params);
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. ASSERT_EQ(StatusCode::OK_200, res->status);
  4688. res = cli_.Get("/person/john4");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. ASSERT_EQ(StatusCode::OK_200, res->status);
  4691. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4692. ASSERT_EQ("coder", res->body);
  4693. Params delete_params;
  4694. delete_params.emplace("name", "john4");
  4695. res = cli_.Delete("/person", delete_params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. ASSERT_EQ("DELETED", res->body);
  4699. res = cli_.Get("/person/john4");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4702. }
  4703. TEST_F(ServerTest, DeleteMethod2) {
  4704. auto res = cli_.Get("/person/john5");
  4705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4706. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4707. Params params;
  4708. params.emplace("name", "john5");
  4709. params.emplace("note", "developer");
  4710. res = cli_.Post("/person", params);
  4711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4712. ASSERT_EQ(StatusCode::OK_200, res->status);
  4713. res = cli_.Get("/person/john5");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. ASSERT_EQ(StatusCode::OK_200, res->status);
  4716. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4717. ASSERT_EQ("developer", res->body);
  4718. Params delete_params;
  4719. delete_params.emplace("name", "john5");
  4720. Headers headers;
  4721. headers.emplace("Custom-Header", "test-value");
  4722. res = cli_.Delete("/person", headers, delete_params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. ASSERT_EQ("DELETED", res->body);
  4726. res = cli_.Get("/person/john5");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4729. }
  4730. TEST_F(ServerTest, DeleteMethod3) {
  4731. auto res = cli_.Get("/person/john6");
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4734. Params params;
  4735. params.emplace("name", "john6");
  4736. params.emplace("note", "tester");
  4737. res = cli_.Post("/person", params);
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. ASSERT_EQ(StatusCode::OK_200, res->status);
  4740. res = cli_.Get("/person/john6");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. ASSERT_EQ(StatusCode::OK_200, res->status);
  4743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4744. ASSERT_EQ("tester", res->body);
  4745. Params delete_params;
  4746. delete_params.emplace("name", "john6");
  4747. Headers headers;
  4748. headers.emplace("Custom-Header", "test-value");
  4749. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. ASSERT_EQ(StatusCode::OK_200, res->status);
  4752. ASSERT_EQ("DELETED", res->body);
  4753. res = cli_.Get("/person/john6");
  4754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4755. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4756. }
  4757. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4758. Params params;
  4759. params.emplace("json", JSON_DATA);
  4760. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4762. ASSERT_EQ(StatusCode::OK_200, res->status);
  4763. ASSERT_EQ(JSON_DATA, res->body);
  4764. }
  4765. TEST_F(ServerTest, PostEmptyContent) {
  4766. auto res = cli_.Post("/empty", "", "text/plain");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. ASSERT_EQ("empty", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4772. auto res = cli_.Post("/empty-no-content-type");
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. ASSERT_EQ("empty-no-content-type", res->body);
  4776. }
  4777. TEST_F(ServerTest, PostPathOnly) {
  4778. auto res = cli_.Post("/path-only");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("path-only", res->body);
  4782. }
  4783. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4784. auto res = cli_.Post("/path-headers-only",
  4785. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::OK_200, res->status);
  4788. ASSERT_EQ("path-headers-only", res->body);
  4789. }
  4790. TEST_F(ServerTest, PostLarge) {
  4791. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ(LARGE_DATA, res->body);
  4795. }
  4796. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4797. auto res = cli_.Put("/empty-no-content-type");
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. ASSERT_EQ(StatusCode::OK_200, res->status);
  4800. ASSERT_EQ("empty-no-content-type", res->body);
  4801. }
  4802. TEST_F(ServerTest, GetMethodDir) {
  4803. auto res = cli_.Get("/dir/");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4807. auto body = R"(<html>
  4808. <head>
  4809. </head>
  4810. <body>
  4811. <a href="/dir/test.html">Test</a>
  4812. <a href="/hi">hi</a>
  4813. </body>
  4814. </html>
  4815. )";
  4816. EXPECT_EQ(body, res->body);
  4817. }
  4818. TEST_F(ServerTest, GetMethodDirTest) {
  4819. auto res = cli_.Get("/dir/test.html");
  4820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4823. EXPECT_EQ("test.html", res->body);
  4824. }
  4825. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4826. auto res = cli_.Get("/dir/../dir/test.html");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4830. EXPECT_EQ("test.html", res->body);
  4831. }
  4832. TEST_F(ServerTest, GetMethodInvalidPath) {
  4833. auto res = cli_.Get("/dir/../test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4836. }
  4837. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4838. auto res = cli_.Get("/../www/dir/test.html");
  4839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4841. }
  4842. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4843. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4846. }
  4847. TEST_F(ServerTest, GetMethodDirMountTest) {
  4848. auto res = cli_.Get("/mount/dir/test.html");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4852. EXPECT_EQ("test.html", res->body);
  4853. }
  4854. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4855. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4857. EXPECT_EQ(StatusCode::OK_200, res->status);
  4858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4859. EXPECT_EQ("test.html", res->body);
  4860. }
  4861. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4862. auto res = cli_.Get("/mount/dir/../test.html");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4865. }
  4866. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4867. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4872. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4875. }
  4876. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4877. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4880. }
  4881. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4882. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4885. }
  4886. TEST_F(ServerTest, PostMethod303) {
  4887. auto res = cli_.Post("/1", "body", "text/plain");
  4888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4889. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4890. EXPECT_EQ("/2", res->get_header_value("Location"));
  4891. }
  4892. TEST_F(ServerTest, PostMethod303Redirect) {
  4893. cli_.set_follow_location(true);
  4894. auto res = cli_.Post("/1", "body", "text/plain");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("redirected.", res->body);
  4898. EXPECT_EQ("/2", res->location);
  4899. }
  4900. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4901. auto res = cli_.Get("/dir/test.abcde");
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ(StatusCode::OK_200, res->status);
  4904. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4905. EXPECT_EQ("abcde", res->body);
  4906. }
  4907. TEST_F(ServerTest, StaticFileRange) {
  4908. auto res =
  4909. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4912. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4913. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("cd"), res->body);
  4917. }
  4918. TEST_F(ServerTest, StaticFileRanges) {
  4919. auto res = cli_.Get("/dir/test.abcde",
  4920. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4923. EXPECT_TRUE(
  4924. res->get_header_value("Content-Type")
  4925. .find(
  4926. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4927. 0);
  4928. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4929. }
  4930. TEST_F(ServerTest, StaticFileRangeHead) {
  4931. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4934. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4935. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4936. EXPECT_EQ(true, res->has_header("Content-Range"));
  4937. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4938. }
  4939. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4940. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4942. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ(true, res->has_header("Content-Range"));
  4946. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4947. res->get_header_value("Content-Range"));
  4948. EXPECT_EQ("LAST\n", res->body);
  4949. }
  4950. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4951. auto res =
  4952. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4956. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4957. EXPECT_EQ(true, res->has_header("Content-Range"));
  4958. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4959. }
  4960. TEST_F(ServerTest, StaticFileBigFile) {
  4961. auto res = cli_.Get("/dir/1MB.txt");
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4965. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4966. }
  4967. TEST_F(ServerTest, InvalidBaseDirMount) {
  4968. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4969. }
  4970. TEST_F(ServerTest, Binary) {
  4971. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4972. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4973. "application/octet-stream");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ(4U, res->body.size());
  4977. res = cli_.Put("/binary", binary.data(), binary.size(),
  4978. "application/octet-stream");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. ASSERT_EQ(StatusCode::OK_200, res->status);
  4981. ASSERT_EQ(4U, res->body.size());
  4982. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4983. "application/octet-stream");
  4984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4985. ASSERT_EQ(StatusCode::OK_200, res->status);
  4986. ASSERT_EQ(4U, res->body.size());
  4987. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4988. "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. }
  4993. TEST_F(ServerTest, BinaryString) {
  4994. auto binary = std::string("\x00\x01\x02\x03", 4);
  4995. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. ASSERT_EQ(StatusCode::OK_200, res->status);
  4998. ASSERT_EQ(4U, res->body.size());
  4999. res = cli_.Put("/binary", binary, "application/octet-stream");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. ASSERT_EQ(StatusCode::OK_200, res->status);
  5002. ASSERT_EQ(4U, res->body.size());
  5003. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. ASSERT_EQ(StatusCode::OK_200, res->status);
  5006. ASSERT_EQ(4U, res->body.size());
  5007. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5009. ASSERT_EQ(StatusCode::OK_200, res->status);
  5010. ASSERT_EQ(4U, res->body.size());
  5011. }
  5012. TEST_F(ServerTest, EmptyRequest) {
  5013. auto res = cli_.Get("");
  5014. ASSERT_TRUE(!res);
  5015. EXPECT_EQ(Error::Connection, res.error());
  5016. }
  5017. TEST_F(ServerTest, LongRequest) {
  5018. std::string request;
  5019. for (size_t i = 0; i < 545; i++) {
  5020. request += "/TooLongRequest";
  5021. }
  5022. request += "OK";
  5023. auto res = cli_.Get(request.c_str());
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5026. }
  5027. TEST_F(ServerTest, TooLongRequest) {
  5028. std::string request;
  5029. for (size_t i = 0; i < 546; i++) {
  5030. request += "/TooLongRequest";
  5031. }
  5032. request += "_NG";
  5033. auto start = std::chrono::high_resolution_clock::now();
  5034. cli_.set_keep_alive(true);
  5035. auto res = cli_.Get(request.c_str());
  5036. auto end = std::chrono::high_resolution_clock::now();
  5037. auto elapsed =
  5038. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5039. .count();
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5042. EXPECT_LE(elapsed, 1000);
  5043. EXPECT_EQ("close", res->get_header_value("Connection"));
  5044. EXPECT_FALSE(cli_.is_socket_open());
  5045. }
  5046. TEST_F(ServerTest, AlmostTooLongRequest) {
  5047. // test for #2046 - URI length check shouldn't include other content on req
  5048. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5049. // leading /, space, HTTP/1.1)
  5050. std::string request =
  5051. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5052. auto res = cli_.Get(request.c_str());
  5053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. }
  5056. TEST_F(ServerTest, LongHeader) {
  5057. Request req;
  5058. req.method = "GET";
  5059. req.path = "/hi";
  5060. std::string host_and_port;
  5061. host_and_port += HOST;
  5062. host_and_port += ":";
  5063. host_and_port += std::to_string(PORT);
  5064. req.headers.emplace("Host", host_and_port.c_str());
  5065. req.headers.emplace("Accept", "*/*");
  5066. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5067. req.headers.emplace(
  5068. "Header-Name",
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5097. "@@@@@@@@@@@@@@@@");
  5098. auto res = std::make_shared<Response>();
  5099. auto error = Error::Success;
  5100. auto ret = cli_.send(req, *res, error);
  5101. ASSERT_TRUE(ret);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, LongQueryValue) {
  5105. auto start = std::chrono::high_resolution_clock::now();
  5106. cli_.set_keep_alive(true);
  5107. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5108. auto end = std::chrono::high_resolution_clock::now();
  5109. auto elapsed =
  5110. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5111. .count();
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5114. EXPECT_LE(elapsed, 1000);
  5115. EXPECT_EQ("close", res->get_header_value("Connection"));
  5116. EXPECT_FALSE(cli_.is_socket_open());
  5117. }
  5118. TEST_F(ServerTest, TooLongQueryValue) {
  5119. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5120. ASSERT_FALSE(res);
  5121. EXPECT_EQ(Error::Read, res.error());
  5122. }
  5123. TEST_F(ServerTest, TooLongHeader) {
  5124. Request req;
  5125. req.method = "GET";
  5126. req.path = "/hi";
  5127. std::string host_and_port;
  5128. host_and_port += HOST;
  5129. host_and_port += ":";
  5130. host_and_port += std::to_string(PORT);
  5131. req.headers.emplace("Host", host_and_port.c_str());
  5132. req.headers.emplace("Accept", "*/*");
  5133. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5134. req.headers.emplace(
  5135. "Header-Name",
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5164. "@@@@@@@@@@@@@@@@@");
  5165. auto res = std::make_shared<Response>();
  5166. auto error = Error::Success;
  5167. auto ret = cli_.send(req, *res, error);
  5168. ASSERT_TRUE(ret);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. }
  5171. TEST_F(ServerTest, HeaderCountAtLimit) {
  5172. // Test with headers just under the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5175. // This should keep us just under the 100 header limit
  5176. for (int i = 0; i < 95; i++) {
  5177. std::string name = "X-Test-Header-" + std::to_string(i);
  5178. std::string value = "value" + std::to_string(i);
  5179. headers.emplace(name, value);
  5180. }
  5181. // This should work fine as we're under the limit
  5182. auto res = cli_.Get("/hi", headers);
  5183. EXPECT_TRUE(res);
  5184. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5185. }
  5186. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5187. // Test with many headers to exceed the 100 limit
  5188. httplib::Headers headers;
  5189. // Add 150 headers to definitely exceed the 100 limit
  5190. for (int i = 0; i < 150; i++) {
  5191. std::string name = "X-Test-Header-" + std::to_string(i);
  5192. std::string value = "value" + std::to_string(i);
  5193. headers.emplace(name, value);
  5194. }
  5195. // This should fail due to exceeding header count limit
  5196. cli_.set_keep_alive(true);
  5197. auto res = cli_.Get("/hi", headers);
  5198. // The server should respond with 400 Bad Request
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5201. EXPECT_EQ("close", res->get_header_value("Connection"));
  5202. EXPECT_FALSE(cli_.is_socket_open());
  5203. }
  5204. TEST_F(ServerTest, PercentEncoding) {
  5205. auto res = cli_.Get("/e%6edwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, PercentEncodingUnicode) {
  5210. auto res = cli_.Get("/e%u006edwith%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. }
  5214. TEST_F(ServerTest, InvalidPercentEncoding) {
  5215. auto res = cli_.Get("/%endwith%");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5218. }
  5219. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5220. auto res = cli_.Get("/%uendwith%");
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5223. }
  5224. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5225. auto res = cli_.Get("/hello?aaa=bbb%");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5228. }
  5229. TEST_F(ServerTest, PlusSignEncoding) {
  5230. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5232. EXPECT_EQ(StatusCode::OK_200, res->status);
  5233. EXPECT_EQ("a +b", res->body);
  5234. }
  5235. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5236. // This test simulates a potential DoS attack using many headers
  5237. // to verify our security fix prevents memory exhaustion
  5238. httplib::Headers attack_headers;
  5239. // Attempt to add many headers like an attacker would (200 headers to far
  5240. // exceed limit)
  5241. for (int i = 0; i < 200; i++) {
  5242. std::string name = "X-Attack-Header-" + std::to_string(i);
  5243. std::string value = "attack_payload_" + std::to_string(i);
  5244. attack_headers.emplace(name, value);
  5245. }
  5246. // Try to POST with excessive headers
  5247. cli_.set_keep_alive(true);
  5248. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5249. // Should either fail or return 400 Bad Request due to security limit
  5250. if (res) {
  5251. // If we get a response, it should be 400 Bad Request
  5252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5253. EXPECT_EQ("close", res->get_header_value("Connection"));
  5254. }
  5255. EXPECT_FALSE(cli_.is_socket_open());
  5256. }
  5257. TEST_F(ServerTest, MultipartFormData) {
  5258. UploadFormDataItems items = {
  5259. {"text1", "text default", "", ""},
  5260. {"text2", "aωb", "", ""},
  5261. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5262. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5263. {"file3", "", "", "application/octet-stream"},
  5264. {"file4", "", "", " application/json tmp-string "}};
  5265. auto res = cli_.Post("/multipart", items);
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. }
  5269. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5270. UploadFormDataItems items = {
  5271. {"text", "default text", "", ""},
  5272. {"multi_text1", "aaaaa", "", ""},
  5273. {"multi_text1", "bbbbb", "", ""},
  5274. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5275. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5276. "application/json"},
  5277. };
  5278. auto res = cli_.Post("/multipart/multi_file_values", items);
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. }
  5282. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5283. auto res = cli_.Get("/hi");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5287. EXPECT_EQ("Hello World!", res->body);
  5288. }
  5289. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5290. Request req;
  5291. req.method = "POST";
  5292. req.path = "/chunked";
  5293. std::string host_and_port;
  5294. host_and_port += HOST;
  5295. host_and_port += ":";
  5296. host_and_port += std::to_string(PORT);
  5297. req.headers.emplace("Host", host_and_port.c_str());
  5298. req.headers.emplace("Accept", "*/*");
  5299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5300. req.headers.emplace("Content-Type", "text/plain");
  5301. req.headers.emplace("Content-Length", "0");
  5302. req.headers.emplace(
  5303. "Transfer-Encoding",
  5304. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5305. // Client does not chunk, so make a chunked body manually.
  5306. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5307. auto res = std::make_shared<Response>();
  5308. auto error = Error::Success;
  5309. auto ret = cli_.send(req, *res, error);
  5310. ASSERT_TRUE(ret);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. }
  5313. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5314. // rather than treat them as valid lengths.
  5315. template <typename ClientT>
  5316. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5317. Request req;
  5318. req.method = "POST";
  5319. req.path = "/chunked";
  5320. std::string host_and_port;
  5321. host_and_port += HOST;
  5322. host_and_port += ":";
  5323. host_and_port += std::to_string(PORT);
  5324. req.headers.emplace("Host", host_and_port.c_str());
  5325. req.headers.emplace("Content-Length", "0");
  5326. req.headers.emplace("Transfer-Encoding", "chunked");
  5327. req.body = body;
  5328. auto res = std::make_shared<Response>();
  5329. auto error = Error::Success;
  5330. ASSERT_TRUE(cli.send(req, *res, error));
  5331. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5332. }
  5333. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5334. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5335. }
  5336. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5337. expect_chunked_body_rejected(
  5338. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5339. }
  5340. TEST_F(ServerTest, GetStreamed2) {
  5341. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5344. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5345. EXPECT_EQ(true, res->has_header("Content-Range"));
  5346. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5347. EXPECT_EQ(std::string("ab"), res->body);
  5348. }
  5349. TEST_F(ServerTest, GetStreamed) {
  5350. auto res = cli_.Get("/streamed");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. EXPECT_EQ(StatusCode::OK_200, res->status);
  5353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5354. EXPECT_EQ(std::string("aaabbb"), res->body);
  5355. }
  5356. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5357. auto res = cli_.Get("/streamed-without-length",
  5358. Headers{make_range_header({{0, -1}})});
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ(false, res->has_header("Content-Length"));
  5362. EXPECT_EQ(false, res->has_header("Content-Range"));
  5363. EXPECT_EQ(std::string("abcdefg"), res->body);
  5364. }
  5365. TEST_F(ServerTest, GetStreamedWithRange1) {
  5366. auto res =
  5367. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5371. EXPECT_EQ(true, res->has_header("Content-Range"));
  5372. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5373. EXPECT_EQ(std::string("def"), res->body);
  5374. }
  5375. TEST_F(ServerTest, GetStreamedWithRange2) {
  5376. auto res =
  5377. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5380. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ(true, res->has_header("Content-Range"));
  5382. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5383. EXPECT_EQ(std::string("bcdefg"), res->body);
  5384. }
  5385. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5386. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5389. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5390. EXPECT_EQ(true, res->has_header("Content-Range"));
  5391. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5392. EXPECT_EQ(std::string("efg"), res->body);
  5393. }
  5394. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5395. auto res =
  5396. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5399. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ(false, res->has_header("Content-Range"));
  5401. EXPECT_EQ(0U, res->body.size());
  5402. }
  5403. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5404. // Only a 206 is served as a partial representation. Under any other status
  5405. // `apply_ranges()` reported the full content length, so the body must match
  5406. // that header, and the content provider must never be asked for an offset
  5407. // outside the representation.
  5408. auto check = [&](int status, const char *range) {
  5409. auto path =
  5410. std::string("/streamed-with-range?status=") + std::to_string(status);
  5411. auto ctx = path + " Range: " + range;
  5412. auto res = cli_.Get(path, Headers{{"Range", range}});
  5413. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5414. EXPECT_EQ(status, res->status) << ctx;
  5415. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5417. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5418. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5419. };
  5420. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5421. check(403, "bytes=3-5");
  5422. // The offset is far past the representation.
  5423. check(403, "bytes=100000-100200");
  5424. // `first_pos` is still -1 here, and the bounds asserts in
  5425. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5426. check(403, "bytes=-3");
  5427. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5428. // multipart branch would have written one that is empty.
  5429. check(403, "bytes=1-2, 4-5");
  5430. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5431. // covers the whole representation.
  5432. check(200, "bytes=3-5");
  5433. check(200, "bytes=1-2, 4-5");
  5434. }
  5435. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5436. auto res =
  5437. cli_.Get("/streamed-with-range",
  5438. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5439. "92233720368547758079223372036854775807"}});
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5442. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5443. EXPECT_EQ(false, res->has_header("Content-Range"));
  5444. EXPECT_EQ(0U, res->body.size());
  5445. }
  5446. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5447. auto res = cli_.Get(
  5448. "/with-range",
  5449. Headers{{"Range",
  5450. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5451. {"Accept-Encoding", ""}});
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5454. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5455. EXPECT_EQ(true, res->has_header("Content-Range"));
  5456. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5457. EXPECT_EQ(std::string("abcdefg"), res->body);
  5458. }
  5459. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5460. auto res = cli_.Get("/with-range", Headers{
  5461. {"Range", "bytes=0-"},
  5462. {"Accept-Encoding", ""},
  5463. });
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5467. EXPECT_EQ(true, res->has_header("Content-Range"));
  5468. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5469. EXPECT_EQ(std::string("abcdefg"), res->body);
  5470. }
  5471. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5472. auto res = cli_.Get("/streamed-with-range",
  5473. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5476. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5477. EXPECT_EQ(false, res->has_header("Content-Range"));
  5478. EXPECT_EQ(267U, res->body.size());
  5479. // Check that both range contents are present
  5480. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5481. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5482. // Check that Content-Range headers are present for both ranges
  5483. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5484. std::string::npos);
  5485. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5486. std::string::npos);
  5487. }
  5488. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5489. Ranges ranges;
  5490. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5491. ranges.emplace_back(0, -1);
  5492. }
  5493. auto res = cli_.Get("/streamed-with-range?error",
  5494. Headers{{make_range_header(ranges)}});
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5497. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5498. EXPECT_EQ(false, res->has_header("Content-Range"));
  5499. EXPECT_EQ(0U, res->body.size());
  5500. }
  5501. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5502. auto res = cli_.Get("/streamed-with-range",
  5503. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5506. EXPECT_EQ(5U, res->body.size());
  5507. // Check that overlapping ranges are coalesced into a single range
  5508. EXPECT_EQ("bcdef", res->body);
  5509. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5510. // Should be single range, not multipart
  5511. EXPECT_TRUE(res->has_header("Content-Range"));
  5512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(268U, res->body.size());
  5520. // Check that both range contents are present
  5521. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5522. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5523. // Check that Content-Range headers are present for both ranges
  5524. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5525. std::string::npos);
  5526. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5527. std::string::npos);
  5528. }
  5529. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5530. auto res = cli_.Get("/streamed-with-range",
  5531. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5534. EXPECT_EQ(269U, res->body.size());
  5535. // Check that both duplicate range contents are present
  5536. size_t first_abc = res->body.find("abc\r\n");
  5537. EXPECT_TRUE(first_abc != std::string::npos);
  5538. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5539. EXPECT_TRUE(second_abc != std::string::npos);
  5540. // Check that Content-Range headers are present for both ranges
  5541. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5542. EXPECT_TRUE(first_range != std::string::npos);
  5543. size_t second_range =
  5544. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5545. EXPECT_TRUE(second_range != std::string::npos);
  5546. }
  5547. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5548. auto res =
  5549. cli_.Get("/streamed-with-range?error",
  5550. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5553. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5554. EXPECT_EQ(false, res->has_header("Content-Range"));
  5555. EXPECT_EQ(0U, res->body.size());
  5556. }
  5557. TEST_F(ServerTest, GetStreamedEndless) {
  5558. uint64_t offset = 0;
  5559. auto res = cli_.Get("/streamed-cancel",
  5560. [&](const char * /*data*/, uint64_t data_length) {
  5561. if (offset < 100) {
  5562. offset += data_length;
  5563. return true;
  5564. }
  5565. return false;
  5566. });
  5567. ASSERT_TRUE(!res);
  5568. EXPECT_EQ(Error::Canceled, res.error());
  5569. }
  5570. TEST_F(ServerTest, ClientStop) {
  5571. std::atomic_size_t count{4};
  5572. std::vector<std::thread> threads;
  5573. for (auto i = count.load(); i != 0; --i) {
  5574. threads.emplace_back([&]() {
  5575. auto res = cli_.Get("/streamed-cancel",
  5576. [&](const char *, uint64_t) { return true; });
  5577. --count;
  5578. ASSERT_TRUE(!res);
  5579. EXPECT_TRUE(res.error() == Error::Canceled ||
  5580. res.error() == Error::Read || res.error() == Error::Write);
  5581. });
  5582. }
  5583. std::this_thread::sleep_for(std::chrono::seconds(2));
  5584. while (count != 0) {
  5585. cli_.stop();
  5586. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5587. }
  5588. for (auto &t : threads) {
  5589. t.join();
  5590. }
  5591. }
  5592. TEST_F(ServerTest, GetWithRange1) {
  5593. auto res = cli_.Get("/with-range", Headers{
  5594. make_range_header({{3, 5}}),
  5595. {"Accept-Encoding", ""},
  5596. });
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5599. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5600. EXPECT_EQ(true, res->has_header("Content-Range"));
  5601. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5602. EXPECT_EQ(std::string("def"), res->body);
  5603. }
  5604. TEST_F(ServerTest, GetWithRange2) {
  5605. auto res = cli_.Get("/with-range", Headers{
  5606. make_range_header({{1, -1}}),
  5607. {"Accept-Encoding", ""},
  5608. });
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5611. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5612. EXPECT_EQ(true, res->has_header("Content-Range"));
  5613. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5614. EXPECT_EQ(std::string("bcdefg"), res->body);
  5615. }
  5616. TEST_F(ServerTest, GetWithRange3) {
  5617. auto res = cli_.Get("/with-range", Headers{
  5618. make_range_header({{0, 0}}),
  5619. {"Accept-Encoding", ""},
  5620. });
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ(true, res->has_header("Content-Range"));
  5625. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5626. EXPECT_EQ(std::string("a"), res->body);
  5627. }
  5628. TEST_F(ServerTest, GetWithRange4) {
  5629. auto res = cli_.Get("/with-range", Headers{
  5630. make_range_header({{-1, 2}}),
  5631. {"Accept-Encoding", ""},
  5632. });
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5635. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5636. EXPECT_EQ(true, res->has_header("Content-Range"));
  5637. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5638. EXPECT_EQ(std::string("fg"), res->body);
  5639. }
  5640. TEST_F(ServerTest, GetWithRange5) {
  5641. auto res = cli_.Get("/with-range", Headers{
  5642. make_range_header({{0, 5}}),
  5643. {"Accept-Encoding", ""},
  5644. });
  5645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5646. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5647. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ(true, res->has_header("Content-Range"));
  5649. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5650. EXPECT_EQ(std::string("abcdef"), res->body);
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5653. auto res =
  5654. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeMultipart) {
  5659. auto res =
  5660. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5663. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(267U, res->body.size());
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5668. auto res = cli_.Get("/with-range",
  5669. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5672. }
  5673. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5674. auto res = cli_.Get("/with-range-customized-response",
  5675. Headers{{make_range_header({{1, 2}})}});
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5678. EXPECT_EQ(true, res->has_header("Content-Length"));
  5679. EXPECT_EQ(false, res->has_header("Content-Range"));
  5680. EXPECT_EQ(JSON_DATA, res->body);
  5681. }
  5682. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5683. auto res = cli_.Get("/with-range-customized-response",
  5684. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5687. EXPECT_EQ(true, res->has_header("Content-Length"));
  5688. EXPECT_EQ(false, res->has_header("Content-Range"));
  5689. EXPECT_EQ(JSON_DATA, res->body);
  5690. }
  5691. TEST_F(ServerTest, Issue1772) {
  5692. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5695. }
  5696. TEST_F(ServerTest, Issue609) {
  5697. auto res = cli_.Delete("/issue609");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ(std::string("ok"), res->body);
  5701. }
  5702. TEST_F(ServerTest, GetStreamedChunked) {
  5703. auto res = cli_.Get("/streamed-chunked");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ(std::string("123456789"), res->body);
  5707. }
  5708. TEST_F(ServerTest, GetStreamedChunked2) {
  5709. auto res = cli_.Get("/streamed-chunked2");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ(std::string("123456789"), res->body);
  5713. }
  5714. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5715. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. EXPECT_EQ(std::string("123456789"), res->body);
  5719. EXPECT_TRUE(res->has_header("Trailer"));
  5720. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5721. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5722. // Trailers are now stored separately from headers (security fix)
  5723. EXPECT_EQ(2U, res->trailers.size());
  5724. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5725. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5726. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5727. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5728. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5729. // Verify trailers are NOT in headers (security verification)
  5730. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5731. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5732. }
  5733. TEST_F(ServerTest, LargeChunkedPost) {
  5734. Request req;
  5735. req.method = "POST";
  5736. req.path = "/large-chunked";
  5737. std::string host_and_port;
  5738. host_and_port += HOST;
  5739. host_and_port += ":";
  5740. host_and_port += std::to_string(PORT);
  5741. req.headers.emplace("Host", host_and_port.c_str());
  5742. req.headers.emplace("Accept", "*/*");
  5743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5744. req.headers.emplace("Content-Type", "text/plain");
  5745. req.headers.emplace("Content-Length", "0");
  5746. req.headers.emplace("Transfer-Encoding", "chunked");
  5747. std::string long_string(30 * 1024u, 'a');
  5748. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5749. // Attempt to make a large enough post to exceed OS buffers, to test that
  5750. // the server handles short reads if the full chunk data isn't available.
  5751. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5752. auto res = std::make_shared<Response>();
  5753. auto error = Error::Success;
  5754. auto ret = cli_.send(req, *res, error);
  5755. ASSERT_TRUE(ret);
  5756. EXPECT_EQ(StatusCode::OK_200, res->status);
  5757. }
  5758. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5759. auto res = cli_.Get("/remote_addr");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5763. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5764. }
  5765. TEST_F(ServerTest, GetMethodLocalAddr) {
  5766. auto res = cli_.Get("/local_addr");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5770. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5771. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5772. }
  5773. TEST_F(ServerTest, HTTPResponseSplitting) {
  5774. auto res = cli_.Get("/http_response_splitting");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. EXPECT_EQ(StatusCode::OK_200, res->status);
  5777. }
  5778. TEST_F(ServerTest, SlowRequest) {
  5779. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5780. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5781. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5782. }
  5783. #if 0
  5784. TEST_F(ServerTest, SlowPost) {
  5785. char buffer[64 * 1024];
  5786. memset(buffer, 0x42, sizeof(buffer));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. auto ret = sink.write(buffer, sizeof(buffer));
  5791. EXPECT_TRUE(ret);
  5792. return true;
  5793. },
  5794. "text/plain");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, SlowPostFail) {
  5799. char buffer[64 * 1024];
  5800. memset(buffer, 0x42, sizeof(buffer));
  5801. cli_.set_write_timeout(std::chrono::seconds(0));
  5802. auto res = cli_.Post(
  5803. "/slowpost", 64 * 1024 * 1024,
  5804. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5805. sink.write(buffer, sizeof(buffer));
  5806. return true;
  5807. },
  5808. "text/plain");
  5809. ASSERT_TRUE(!res);
  5810. EXPECT_EQ(Error::Write, res.error());
  5811. }
  5812. #endif
  5813. TEST_F(ServerTest, Put) {
  5814. auto res = cli_.Put("/put", "PUT", "text/plain");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("PUT", res->body);
  5818. }
  5819. TEST_F(ServerTest, PutWithContentProvider) {
  5820. auto res = cli_.Put(
  5821. "/put", 3,
  5822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5823. sink.os << "PUT";
  5824. return true;
  5825. },
  5826. "text/plain");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::OK_200, res->status);
  5829. EXPECT_EQ("PUT", res->body);
  5830. }
  5831. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5832. auto res = cli_.Post(
  5833. "/post", 42,
  5834. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5835. return false;
  5836. },
  5837. "text/plain");
  5838. ASSERT_TRUE(!res);
  5839. EXPECT_EQ(Error::Canceled, res.error());
  5840. }
  5841. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5842. auto res = cli_.Put(
  5843. "/put",
  5844. [](size_t /*offset*/, DataSink &sink) {
  5845. sink.os << "PUT";
  5846. sink.done();
  5847. return true;
  5848. },
  5849. "text/plain");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. EXPECT_EQ("PUT", res->body);
  5853. }
  5854. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5855. auto res = cli_.Post(
  5856. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5857. "text/plain");
  5858. ASSERT_TRUE(!res);
  5859. EXPECT_EQ(Error::Canceled, res.error());
  5860. }
  5861. TEST_F(ServerTest, PostLoopBack) {
  5862. std::string body;
  5863. auto res = cli_.Post(
  5864. "/post-loopback", 9,
  5865. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5866. EXPECT_EQ(9u, length);
  5867. sink.write("123", 3);
  5868. sink.write("456", 3);
  5869. sink.write("789", 3);
  5870. return true;
  5871. },
  5872. "text/plain",
  5873. [&body](const char *data, size_t data_length) {
  5874. body.append(data, data_length);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("123456789", body);
  5880. }
  5881. TEST_F(ServerTest, PutLoopBack) {
  5882. std::string body;
  5883. auto res = cli_.Put(
  5884. "/put-loopback", 9,
  5885. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5886. EXPECT_EQ(9u, length);
  5887. sink.write("123", 3);
  5888. sink.write("456", 3);
  5889. sink.write("789", 3);
  5890. return true;
  5891. },
  5892. "text/plain",
  5893. [&body](const char *data, size_t data_length) {
  5894. body.append(data, data_length);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. EXPECT_EQ("123456789", body);
  5900. }
  5901. TEST_F(ServerTest, PatchLoopBack) {
  5902. std::string body;
  5903. auto res = cli_.Patch(
  5904. "/patch-loopback", 9,
  5905. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5906. EXPECT_EQ(9u, length);
  5907. sink.write("123", 3);
  5908. sink.write("456", 3);
  5909. sink.write("789", 3);
  5910. return true;
  5911. },
  5912. "text/plain",
  5913. [&body](const char *data, size_t data_length) {
  5914. body.append(data, data_length);
  5915. return true;
  5916. });
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ("123456789", body);
  5920. }
  5921. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5922. std::string body;
  5923. auto res = cli_.Post(
  5924. "/post-loopback",
  5925. [](size_t /*offset*/, DataSink &sink) {
  5926. sink.write("123", 3);
  5927. sink.write("456", 3);
  5928. sink.write("789", 3);
  5929. sink.done();
  5930. return true;
  5931. },
  5932. "text/plain",
  5933. [&body](const char *data, size_t data_length) {
  5934. body.append(data, data_length);
  5935. return true;
  5936. });
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("123456789", body);
  5940. }
  5941. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5942. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5943. cli_.set_compress(true);
  5944. auto res = cli_.Put(
  5945. "/put", 3,
  5946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5947. sink.os << "PUT";
  5948. return true;
  5949. },
  5950. "text/plain");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. EXPECT_EQ("PUT", res->body);
  5954. }
  5955. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5956. cli_.set_compress(true);
  5957. auto res = cli_.Post(
  5958. "/post", 42,
  5959. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5960. return false;
  5961. },
  5962. "text/plain");
  5963. ASSERT_TRUE(!res);
  5964. EXPECT_EQ(Error::Canceled, res.error());
  5965. }
  5966. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5967. cli_.set_compress(true);
  5968. auto res = cli_.Put(
  5969. "/put",
  5970. [](size_t /*offset*/, DataSink &sink) {
  5971. sink.os << "PUT";
  5972. sink.done();
  5973. return true;
  5974. },
  5975. "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ("PUT", res->body);
  5979. }
  5980. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5981. cli_.set_compress(true);
  5982. auto res = cli_.Post(
  5983. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5984. "text/plain");
  5985. ASSERT_TRUE(!res);
  5986. EXPECT_EQ(Error::Canceled, res.error());
  5987. }
  5988. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5989. cli_.set_compress(true);
  5990. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ(LARGE_DATA, res->body);
  5994. }
  5995. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5998. Client cli(s.c_str());
  5999. cli.enable_server_certificate_verification(false);
  6000. #else
  6001. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6002. Client cli(s.c_str());
  6003. #endif
  6004. cli.set_compress(true);
  6005. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. EXPECT_EQ(LARGE_DATA, res->body);
  6009. // The compressed size should be less than a 10th of the original. May vary
  6010. // depending on the zlib library.
  6011. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6012. static_cast<uint64_t>(10 * 1024 * 1024));
  6013. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6014. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6015. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6016. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6017. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6018. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6019. #endif
  6020. }
  6021. TEST_F(ServerTest, PutContentWithDeflate) {
  6022. cli_.set_compress(false);
  6023. Headers headers;
  6024. headers.emplace("Content-Encoding", "deflate");
  6025. // PUT in deflate format:
  6026. auto res = cli_.Put("/put", headers,
  6027. "\170\234\013\010\015\001\0\001\361\0\372", "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, GetStreamedChunkedWithGzip) {
  6033. Headers headers;
  6034. headers.emplace("Accept-Encoding", "gzip, deflate");
  6035. auto res = cli_.Get("/streamed-chunked", headers);
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::OK_200, res->status);
  6038. EXPECT_EQ(std::string("123456789"), res->body);
  6039. }
  6040. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6041. Headers headers;
  6042. headers.emplace("Accept-Encoding", "gzip, deflate");
  6043. auto res = cli_.Get("/streamed-chunked2", headers);
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ(std::string("123456789"), res->body);
  6047. }
  6048. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6049. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. }
  6053. TEST(GzipDecompressor, ChunkedDecompression) {
  6054. std::string data;
  6055. for (size_t i = 0; i < 32 * 1024; ++i) {
  6056. data.push_back(static_cast<char>('a' + i % 26));
  6057. }
  6058. std::string compressed_data;
  6059. {
  6060. httplib::detail::gzip_compressor compressor;
  6061. bool result = compressor.compress(
  6062. data.data(), data.size(),
  6063. /*last=*/true,
  6064. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6065. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6066. compressed_data_size);
  6067. return true;
  6068. });
  6069. ASSERT_TRUE(result);
  6070. }
  6071. std::string decompressed_data;
  6072. {
  6073. httplib::detail::gzip_decompressor decompressor;
  6074. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6075. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6076. size_t chunk_size = 130;
  6077. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6078. chunk_begin += chunk_size) {
  6079. size_t current_chunk_size =
  6080. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6081. bool result = decompressor.decompress(
  6082. compressed_data.data() + chunk_begin, current_chunk_size,
  6083. [&](const char *decompressed_data_chunk,
  6084. size_t decompressed_data_chunk_size) {
  6085. decompressed_data.insert(decompressed_data.size(),
  6086. decompressed_data_chunk,
  6087. decompressed_data_chunk_size);
  6088. return true;
  6089. });
  6090. ASSERT_TRUE(result);
  6091. }
  6092. }
  6093. ASSERT_EQ(data, decompressed_data);
  6094. }
  6095. TEST(GzipDecompressor, DeflateDecompression) {
  6096. std::string original_text = "Raw deflate without gzip";
  6097. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6098. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6099. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6100. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6101. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6102. std::string decompressed_data;
  6103. {
  6104. httplib::detail::gzip_decompressor decompressor;
  6105. bool result = decompressor.decompress(
  6106. compressed_data.data(), compressed_data.size(),
  6107. [&](const char *decompressed_data_chunk,
  6108. size_t decompressed_data_chunk_size) {
  6109. decompressed_data.insert(decompressed_data.size(),
  6110. decompressed_data_chunk,
  6111. decompressed_data_chunk_size);
  6112. return true;
  6113. });
  6114. ASSERT_TRUE(result);
  6115. }
  6116. ASSERT_EQ(original_text, decompressed_data);
  6117. }
  6118. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6119. std::string original_text = "Raw deflate without gzip";
  6120. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6121. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6122. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6123. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6124. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6125. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6126. std::string decompressed_data;
  6127. {
  6128. httplib::detail::gzip_decompressor decompressor;
  6129. bool result = decompressor.decompress(
  6130. compressed_data.data(), compressed_data.size(),
  6131. [&](const char *decompressed_data_chunk,
  6132. size_t decompressed_data_chunk_size) {
  6133. decompressed_data.insert(decompressed_data.size(),
  6134. decompressed_data_chunk,
  6135. decompressed_data_chunk_size);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(result);
  6139. }
  6140. ASSERT_EQ(original_text, decompressed_data);
  6141. }
  6142. #endif
  6143. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6144. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6145. Headers headers;
  6146. headers.emplace("Accept-Encoding", "br");
  6147. auto res = cli_.Get("/streamed-chunked", headers);
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. EXPECT_EQ(std::string("123456789"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6153. Headers headers;
  6154. headers.emplace("Accept-Encoding", "br");
  6155. auto res = cli_.Get("/streamed-chunked2", headers);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ(std::string("123456789"), res->body);
  6159. }
  6160. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6161. cli_.set_compress(true);
  6162. auto res = cli_.Put(
  6163. "/put", 3,
  6164. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6165. sink.os << "PUT";
  6166. return true;
  6167. },
  6168. "text/plain");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. EXPECT_EQ("PUT", res->body);
  6172. }
  6173. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6174. cli_.set_compress(true);
  6175. auto res = cli_.Put(
  6176. "/put",
  6177. [](size_t /*offset*/, DataSink &sink) {
  6178. sink.os << "PUT";
  6179. sink.done();
  6180. return true;
  6181. },
  6182. "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PUT", res->body);
  6186. }
  6187. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6188. cli_.set_compress(true);
  6189. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ(LARGE_DATA, res->body);
  6193. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6194. }
  6195. #endif
  6196. TEST_F(ServerTest, Patch) {
  6197. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("PATCH", res->body);
  6201. }
  6202. TEST_F(ServerTest, Delete) {
  6203. auto res = cli_.Delete("/delete");
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("DELETE", res->body);
  6207. }
  6208. TEST_F(ServerTest, DeleteContentReceiver) {
  6209. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ("content", res->body);
  6213. }
  6214. TEST_F(ServerTest, Options) {
  6215. auto res = cli_.Options("*");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6219. EXPECT_TRUE(res->body.empty());
  6220. }
  6221. TEST_F(ServerTest, URL) {
  6222. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. TEST_F(ServerTest, ArrayParam) {
  6227. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. }
  6231. TEST_F(ServerTest, ArrayParamValues) {
  6232. auto res =
  6233. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. }
  6237. TEST_F(ServerTest, NoMultipleHeaders) {
  6238. Headers headers = {{"Content-Length", "5"}};
  6239. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6240. "text/plain");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::OK_200, res->status);
  6243. }
  6244. TEST_F(ServerTest, PostContentReceiver) {
  6245. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::OK_200, res->status);
  6248. ASSERT_EQ("content", res->body);
  6249. }
  6250. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6251. UploadFormDataItems items = {
  6252. {"text1", "text default", "", ""},
  6253. {"text2", "aωb", "", ""},
  6254. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6255. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6256. {"file3", "", "", "application/octet-stream"},
  6257. };
  6258. auto res = cli_.Post("/content_receiver", items);
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::OK_200, res->status);
  6261. }
  6262. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. };
  6270. auto boundary = std::string("+++++");
  6271. std::string body;
  6272. for (const auto &item : items) {
  6273. body += "--" + boundary + "\r\n";
  6274. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6275. if (!item.filename.empty()) {
  6276. body += "; filename=\"" + item.filename + "\"";
  6277. }
  6278. body += "\r\n";
  6279. if (!item.content_type.empty()) {
  6280. body += "Content-Type: " + item.content_type + "\r\n";
  6281. }
  6282. body += "\r\n";
  6283. body += item.content + "\r\n";
  6284. }
  6285. body += "--" + boundary + "--\r\n";
  6286. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6287. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::OK_200, res->status);
  6290. }
  6291. TEST(MultipartFormDataTest, FieldEscaping) {
  6292. Server svr;
  6293. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6294. const ContentReader &content_reader) {
  6295. ASSERT_TRUE(req.is_multipart_form_data());
  6296. std::vector<FormData> received;
  6297. content_reader(
  6298. [&](const FormData &file) {
  6299. received.push_back(file);
  6300. return true;
  6301. },
  6302. [&](const char *data, size_t data_length) {
  6303. received.back().content.append(data, data_length);
  6304. return true;
  6305. });
  6306. // '"', CR and LF in names and filenames are escaped following the
  6307. // WHATWG HTML standard, so each part still parses as a single part
  6308. // with no injected headers. Content types get CR/LF escaped too,
  6309. // while '"' (legal there, e.g. quoted charset) is preserved.
  6310. ASSERT_EQ(4U, received.size());
  6311. EXPECT_EQ("na%22me", received[0].name);
  6312. EXPECT_EQ("quoted name", received[0].content);
  6313. EXPECT_EQ("file", received[1].name);
  6314. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6315. received[1].filename);
  6316. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6317. EXPECT_EQ("injected", received[1].content);
  6318. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6319. EXPECT_EQ("my%22file.txt", received[2].filename);
  6320. EXPECT_EQ("cr lf name", received[2].content);
  6321. EXPECT_EQ("typed", received[3].name);
  6322. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6323. received[3].content_type);
  6324. EXPECT_EQ("typed content", received[3].content);
  6325. });
  6326. auto port = svr.bind_to_any_port("localhost");
  6327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6328. auto se = detail::scope_exit([&] {
  6329. svr.stop();
  6330. t.join();
  6331. ASSERT_FALSE(svr.is_running());
  6332. });
  6333. svr.wait_until_ready();
  6334. Client cli("localhost", port);
  6335. UploadFormDataItems items = {
  6336. {"na\"me", "quoted name", "", ""},
  6337. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6338. "application/octet-stream"},
  6339. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6340. {"typed", "typed content", "",
  6341. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6342. };
  6343. auto res = cli.Post("/post", items);
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. }
  6347. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6348. const UploadFormDataItems items = {
  6349. {"name1", "Content 1", "", ""},
  6350. {"name2", "Content 2", "file2.txt", "text/plain"},
  6351. };
  6352. Server svr;
  6353. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6354. const ContentReader &content_reader) {
  6355. ASSERT_TRUE(req.is_multipart_form_data());
  6356. std::vector<FormData> received;
  6357. content_reader(
  6358. [&](const FormData &file) {
  6359. received.push_back(file);
  6360. return true;
  6361. },
  6362. [&](const char *data, size_t data_length) {
  6363. received.back().content.append(data, data_length);
  6364. return true;
  6365. });
  6366. ASSERT_EQ(2U, received.size());
  6367. EXPECT_EQ("name1", received[0].name);
  6368. EXPECT_EQ("Content 1", received[0].content);
  6369. EXPECT_EQ("name2", received[1].name);
  6370. EXPECT_EQ("Content 2", received[1].content);
  6371. EXPECT_EQ("file2.txt", received[1].filename);
  6372. EXPECT_EQ("text/plain", received[1].content_type);
  6373. });
  6374. auto port = svr.bind_to_any_port("localhost");
  6375. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6376. auto se = detail::scope_exit([&] {
  6377. svr.stop();
  6378. t.join();
  6379. ASSERT_FALSE(svr.is_running());
  6380. });
  6381. svr.wait_until_ready();
  6382. Client cli("localhost", port);
  6383. // Whole-body serialization with a generated boundary
  6384. {
  6385. MultipartFormDataWriter writer;
  6386. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6387. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6388. writer.content_type());
  6389. auto body = writer.serialize(items);
  6390. EXPECT_EQ(body.size(), writer.content_length(items));
  6391. auto res = cli.Post("/post", body, writer.content_type());
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. }
  6395. // Per-part framing with a custom boundary via a content provider
  6396. {
  6397. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6398. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6399. MultipartFormDataWriter writer("custom-boundary_123");
  6400. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6401. std::string body;
  6402. for (const auto &item : items) {
  6403. body += writer.item_begin(item);
  6404. body += item.content;
  6405. body += MultipartFormDataWriter::item_end();
  6406. }
  6407. body += writer.finish();
  6408. EXPECT_EQ(body.size(), writer.content_length(items));
  6409. auto res = cli.Post(
  6410. "/post", body.size(),
  6411. [&](size_t offset, size_t length, DataSink &sink) {
  6412. sink.write(body.data() + offset, length);
  6413. return true;
  6414. },
  6415. writer.content_type());
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. }
  6419. }
  6420. TEST_F(ServerTest, PostContentReceiverGzip) {
  6421. cli_.set_compress(true);
  6422. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("content", res->body);
  6426. }
  6427. TEST_F(ServerTest, PutContentReceiver) {
  6428. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. ASSERT_EQ(StatusCode::OK_200, res->status);
  6431. ASSERT_EQ("content", res->body);
  6432. }
  6433. TEST_F(ServerTest, PatchContentReceiver) {
  6434. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. ASSERT_EQ(StatusCode::OK_200, res->status);
  6437. ASSERT_EQ("content", res->body);
  6438. }
  6439. template <typename ClientType>
  6440. void TestWithHeadersAndContentReceiver(
  6441. ClientType &cli,
  6442. std::function<Result(ClientType &, const std::string &, const Headers &,
  6443. const std::string &, const std::string &,
  6444. ContentReceiver, DownloadProgress)>
  6445. request_func) {
  6446. Headers headers;
  6447. headers.emplace("X-Custom-Header", "test-value");
  6448. std::string received_body;
  6449. auto res = request_func(
  6450. cli, "/content_receiver", headers, "content", "application/json",
  6451. [&](const char *data, size_t data_length) {
  6452. received_body.append(data, data_length);
  6453. return true;
  6454. },
  6455. nullptr);
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ("content", received_body);
  6459. }
  6460. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6461. #ifdef CPPHTTPLIB_SSL_ENABLED
  6462. using ClientT = SSLClient;
  6463. #else
  6464. using ClientT = Client;
  6465. #endif
  6466. TestWithHeadersAndContentReceiver<ClientT>(
  6467. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6468. const std::string &body, const std::string &content_type,
  6469. ContentReceiver receiver, DownloadProgress progress) {
  6470. return cli.Post(path, headers, body, content_type, receiver, progress);
  6471. });
  6472. }
  6473. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6474. #ifdef CPPHTTPLIB_SSL_ENABLED
  6475. using ClientT = SSLClient;
  6476. #else
  6477. using ClientT = Client;
  6478. #endif
  6479. TestWithHeadersAndContentReceiver<ClientT>(
  6480. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6481. const std::string &body, const std::string &content_type,
  6482. ContentReceiver receiver, DownloadProgress progress) {
  6483. return cli.Put(path, headers, body, content_type, receiver, progress);
  6484. });
  6485. }
  6486. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6487. #ifdef CPPHTTPLIB_SSL_ENABLED
  6488. using ClientT = SSLClient;
  6489. #else
  6490. using ClientT = Client;
  6491. #endif
  6492. TestWithHeadersAndContentReceiver<ClientT>(
  6493. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6494. const std::string &body, const std::string &content_type,
  6495. ContentReceiver receiver, DownloadProgress progress) {
  6496. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6497. });
  6498. }
  6499. template <typename ClientType>
  6500. void TestWithHeadersAndContentReceiverWithProgress(
  6501. ClientType &cli,
  6502. std::function<Result(ClientType &, const std::string &, const Headers &,
  6503. const std::string &, const std::string &,
  6504. ContentReceiver, DownloadProgress)>
  6505. request_func) {
  6506. Headers headers;
  6507. headers.emplace("X-Test-Header", "progress-test");
  6508. std::string received_body;
  6509. auto progress_called = false;
  6510. auto res = request_func(
  6511. cli, "/content_receiver", headers, "content", "text/plain",
  6512. [&](const char *data, size_t data_length) {
  6513. received_body.append(data, data_length);
  6514. return true;
  6515. },
  6516. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6517. progress_called = true;
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("content", received_body);
  6523. EXPECT_TRUE(progress_called);
  6524. }
  6525. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6526. #ifdef CPPHTTPLIB_SSL_ENABLED
  6527. using ClientT = SSLClient;
  6528. #else
  6529. using ClientT = Client;
  6530. #endif
  6531. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6532. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6533. const std::string &body, const std::string &content_type,
  6534. ContentReceiver receiver, DownloadProgress progress) {
  6535. return cli.Post(path, headers, body, content_type, receiver, progress);
  6536. });
  6537. }
  6538. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6539. #ifdef CPPHTTPLIB_SSL_ENABLED
  6540. using ClientT = SSLClient;
  6541. #else
  6542. using ClientT = Client;
  6543. #endif
  6544. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6545. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6546. const std::string &body, const std::string &content_type,
  6547. ContentReceiver receiver, DownloadProgress progress) {
  6548. return cli.Put(path, headers, body, content_type, receiver, progress);
  6549. });
  6550. }
  6551. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6552. #ifdef CPPHTTPLIB_SSL_ENABLED
  6553. using ClientT = SSLClient;
  6554. #else
  6555. using ClientT = Client;
  6556. #endif
  6557. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6558. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6559. const std::string &body, const std::string &content_type,
  6560. ContentReceiver receiver, DownloadProgress progress) {
  6561. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6562. });
  6563. }
  6564. template <typename ClientType>
  6565. void TestWithHeadersAndContentReceiverError(
  6566. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6567. const Headers &, const std::string &,
  6568. const std::string &, ContentReceiver)>
  6569. request_func) {
  6570. Headers headers;
  6571. headers.emplace("X-Error-Test", "true");
  6572. std::string received_body;
  6573. auto receiver_failed = false;
  6574. auto res =
  6575. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6576. [&](const char *data, size_t data_length) {
  6577. received_body.append(data, data_length);
  6578. receiver_failed = true;
  6579. return false;
  6580. });
  6581. ASSERT_FALSE(res);
  6582. EXPECT_TRUE(receiver_failed);
  6583. }
  6584. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6585. #ifdef CPPHTTPLIB_SSL_ENABLED
  6586. using ClientT = SSLClient;
  6587. #else
  6588. using ClientT = Client;
  6589. #endif
  6590. TestWithHeadersAndContentReceiverError<ClientT>(
  6591. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6592. const std::string &body, const std::string &content_type,
  6593. ContentReceiver receiver) {
  6594. return cli.Post(path, headers, body, content_type, receiver);
  6595. });
  6596. }
  6597. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6598. #ifdef CPPHTTPLIB_SSL_ENABLED
  6599. using ClientT = SSLClient;
  6600. #else
  6601. using ClientT = Client;
  6602. #endif
  6603. TestWithHeadersAndContentReceiverError<ClientT>(
  6604. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6605. const std::string &body, const std::string &content_type,
  6606. ContentReceiver receiver) {
  6607. return cli.Put(path, headers, body, content_type, receiver);
  6608. });
  6609. }
  6610. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6611. #ifdef CPPHTTPLIB_SSL_ENABLED
  6612. using ClientT = SSLClient;
  6613. #else
  6614. using ClientT = Client;
  6615. #endif
  6616. TestWithHeadersAndContentReceiverError<ClientT>(
  6617. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6618. const std::string &body, const std::string &content_type,
  6619. ContentReceiver receiver) {
  6620. return cli.Patch(path, headers, body, content_type, receiver);
  6621. });
  6622. }
  6623. TEST_F(ServerTest, PostQueryStringAndBody) {
  6624. auto res =
  6625. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. }
  6629. TEST_F(ServerTest, HTTP2Magic) {
  6630. Request req;
  6631. req.method = "PRI";
  6632. req.path = "*";
  6633. req.body = "SM";
  6634. auto res = std::make_shared<Response>();
  6635. auto error = Error::Success;
  6636. auto ret = cli_.send(req, *res, error);
  6637. ASSERT_TRUE(ret);
  6638. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6639. }
  6640. TEST_F(ServerTest, KeepAlive) {
  6641. auto res = cli_.Get("/hi");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6645. EXPECT_EQ("Hello World!", res->body);
  6646. res = cli_.Get("/hi");
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(StatusCode::OK_200, res->status);
  6649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6650. EXPECT_EQ("Hello World!", res->body);
  6651. res = cli_.Get("/hi");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::OK_200, res->status);
  6654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6655. EXPECT_EQ("Hello World!", res->body);
  6656. res = cli_.Get("/not-exist");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. res = cli_.Post("/empty", "", "text/plain");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6663. EXPECT_EQ("empty", res->body);
  6664. EXPECT_EQ("close", res->get_header_value("Connection"));
  6665. res = cli_.Post(
  6666. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6667. "text/plain");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6671. EXPECT_EQ("empty", res->body);
  6672. cli_.set_keep_alive(false);
  6673. res = cli_.Get("/last-request");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. }
  6678. TEST_F(ServerTest, TooManyRedirect) {
  6679. cli_.set_follow_location(true);
  6680. auto res = cli_.Get("/redirect/0");
  6681. ASSERT_TRUE(!res);
  6682. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6683. }
  6684. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6685. Request req;
  6686. req.method = "FOOBAR";
  6687. req.path = "/hi";
  6688. cli_.set_keep_alive(true);
  6689. auto res = cli_.send(req);
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ("close", res->get_header_value("Connection"));
  6693. EXPECT_FALSE(cli_.is_socket_open());
  6694. }
  6695. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6696. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6697. TEST_F(ServerTest, Gzip) {
  6698. Headers headers;
  6699. headers.emplace("Accept-Encoding", "gzip, deflate");
  6700. auto res = cli_.Get("/compress", headers);
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6704. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6706. "7890123456789012345678901234567890",
  6707. res->body);
  6708. EXPECT_EQ(StatusCode::OK_200, res->status);
  6709. }
  6710. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6711. Headers headers;
  6712. headers.emplace("Accept-Encoding", "gzip, deflate");
  6713. auto res = cli_.Get("/compress-with-charset", headers);
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6716. EXPECT_EQ("application/json; charset=utf-8",
  6717. res->get_header_value("Content-Type"));
  6718. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6719. "7890123456789012345678901234567890",
  6720. res->body);
  6721. EXPECT_EQ(StatusCode::OK_200, res->status);
  6722. }
  6723. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6724. Headers headers;
  6725. headers.emplace("Accept-Encoding", "");
  6726. auto res = cli_.Get("/compress", headers);
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6731. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6732. "7890123456789012345678901234567890",
  6733. res->body);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. TEST_F(ServerTest, GzipWithContentReceiver) {
  6737. Headers headers;
  6738. headers.emplace("Accept-Encoding", "gzip, deflate");
  6739. std::string body;
  6740. auto res = cli_.Get("/compress", headers,
  6741. [&](const char *data, uint64_t data_length) {
  6742. EXPECT_EQ(100U, data_length);
  6743. body.append(data, data_length);
  6744. return true;
  6745. });
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6748. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6749. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6750. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6751. "7890123456789012345678901234567890",
  6752. body);
  6753. EXPECT_EQ(StatusCode::OK_200, res->status);
  6754. }
  6755. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. cli_.set_decompress(false);
  6759. auto res = cli_.Get("/compress", headers);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6763. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6764. EXPECT_EQ(33U, res->body.size());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. }
  6767. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "");
  6770. std::string body;
  6771. auto res = cli_.Get("/compress", headers,
  6772. [&](const char *data, uint64_t data_length) {
  6773. EXPECT_EQ(100U, data_length);
  6774. body.append(data, data_length);
  6775. return true;
  6776. });
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6780. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6781. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6782. "7890123456789012345678901234567890",
  6783. body);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. }
  6786. TEST_F(ServerTest, NoGzip) {
  6787. Headers headers;
  6788. headers.emplace("Accept-Encoding", "gzip, deflate");
  6789. auto res = cli_.Get("/nocompress", headers);
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6792. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6795. "7890123456789012345678901234567890",
  6796. res->body);
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. }
  6799. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6800. Headers headers;
  6801. headers.emplace("Accept-Encoding", "gzip, deflate");
  6802. std::string body;
  6803. auto res = cli_.Get("/nocompress", headers,
  6804. [&](const char *data, uint64_t data_length) {
  6805. EXPECT_EQ(100U, data_length);
  6806. body.append(data, data_length);
  6807. return true;
  6808. });
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6811. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6813. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6814. "7890123456789012345678901234567890",
  6815. body);
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. }
  6818. TEST_F(ServerTest, MultipartFormDataGzip) {
  6819. UploadFormDataItems items = {
  6820. {"key1", "test", "", ""},
  6821. {"key2", "--abcdefg123", "", ""},
  6822. };
  6823. cli_.set_compress(true);
  6824. auto res = cli_.Post("/compress-multipart", items);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6830. TEST_F(ServerTest, Brotli) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "br");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6839. "7890123456789012345678901234567890",
  6840. res->body);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. #endif
  6844. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6845. TEST_F(ServerTest, Zstd) {
  6846. Headers headers;
  6847. headers.emplace("Accept-Encoding", "zstd");
  6848. auto res = cli_.Get("/compress", headers);
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6851. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6852. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6854. "7890123456789012345678901234567890",
  6855. res->body);
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. }
  6858. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6859. Headers headers;
  6860. headers.emplace("Accept-Encoding", "");
  6861. auto res = cli_.Get("/compress", headers);
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6865. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6867. "7890123456789012345678901234567890",
  6868. res->body);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6872. Headers headers;
  6873. headers.emplace("Accept-Encoding", "zstd");
  6874. std::string body;
  6875. auto res = cli_.Get("/compress", headers,
  6876. [&](const char *data, uint64_t data_length) {
  6877. EXPECT_EQ(100U, data_length);
  6878. body.append(data, data_length);
  6879. return true;
  6880. });
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6886. "7890123456789012345678901234567890",
  6887. body);
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. }
  6890. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6891. Headers headers;
  6892. headers.emplace("Accept-Encoding", "zstd");
  6893. cli_.set_decompress(false);
  6894. auto res = cli_.Get("/compress", headers);
  6895. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6896. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6897. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6898. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. ASSERT_EQ(26U, res->body.size());
  6905. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6906. 0);
  6907. }
  6908. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6909. Headers headers;
  6910. headers.emplace("Accept-Encoding", "");
  6911. std::string body;
  6912. auto res = cli_.Get("/compress", headers,
  6913. [&](const char *data, uint64_t data_length) {
  6914. EXPECT_EQ(100U, data_length);
  6915. body.append(data, data_length);
  6916. return true;
  6917. });
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6921. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6922. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6923. "7890123456789012345678901234567890",
  6924. body);
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. }
  6927. TEST_F(ServerTest, NoZstd) {
  6928. Headers headers;
  6929. headers.emplace("Accept-Encoding", "zstd");
  6930. auto res = cli_.Get("/nocompress", headers);
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6933. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6934. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6936. "7890123456789012345678901234567890",
  6937. res->body);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6941. Headers headers;
  6942. headers.emplace("Accept-Encoding", "zstd");
  6943. std::string body;
  6944. auto res = cli_.Get("/nocompress", headers,
  6945. [&](const char *data, uint64_t data_length) {
  6946. EXPECT_EQ(100U, data_length);
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6952. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6953. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6954. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6955. "7890123456789012345678901234567890",
  6956. body);
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. }
  6959. // TODO: How to enable zstd ??
  6960. TEST_F(ServerTest, MultipartFormDataZstd) {
  6961. UploadFormDataItems items = {
  6962. {"key1", "test", "", ""},
  6963. {"key2", "--abcdefg123", "", ""},
  6964. };
  6965. Headers headers;
  6966. headers.emplace("Accept-Encoding", "zstd");
  6967. cli_.set_compress(true);
  6968. auto res = cli_.Post("/compress-multipart", headers, items);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::OK_200, res->status);
  6971. }
  6972. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6973. Headers headers;
  6974. headers.emplace("Accept-Encoding", "zstd");
  6975. cli_.set_compress(true);
  6976. auto res = cli_.Put(
  6977. "/put", headers, 3,
  6978. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6979. sink.os << "PUT";
  6980. return true;
  6981. },
  6982. "text/plain");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. EXPECT_EQ("PUT", res->body);
  6986. }
  6987. // Pre-compression logging tests
  6988. TEST_F(ServerTest, PreCompressionLogging) {
  6989. // Test data for compression (matches the actual /compress endpoint content)
  6990. const std::string test_content =
  6991. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6992. "3456789012345678901234567890";
  6993. // Variables to capture logging data
  6994. std::string pre_compression_body;
  6995. std::string pre_compression_content_type;
  6996. std::string pre_compression_content_encoding;
  6997. std::string post_compression_body;
  6998. std::string post_compression_content_type;
  6999. std::string post_compression_content_encoding;
  7000. // Set up pre-compression logger
  7001. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7002. const Response &res) {
  7003. pre_compression_body = res.body;
  7004. pre_compression_content_type = res.get_header_value("Content-Type");
  7005. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7006. });
  7007. // Set up post-compression logger
  7008. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7009. post_compression_body = res.body;
  7010. post_compression_content_type = res.get_header_value("Content-Type");
  7011. post_compression_content_encoding =
  7012. res.get_header_value("Content-Encoding");
  7013. });
  7014. // Test with gzip compression
  7015. Headers headers;
  7016. headers.emplace("Accept-Encoding", "gzip");
  7017. auto res = cli_.Get("/compress", headers);
  7018. // Verify response was compressed
  7019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7020. EXPECT_EQ(StatusCode::OK_200, res->status);
  7021. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7022. // Verify pre-compression logger captured uncompressed content
  7023. EXPECT_EQ(test_content, pre_compression_body);
  7024. EXPECT_EQ("text/plain", pre_compression_content_type);
  7025. EXPECT_TRUE(pre_compression_content_encoding
  7026. .empty()); // No encoding header before compression
  7027. // Verify post-compression logger captured compressed content
  7028. EXPECT_NE(test_content,
  7029. post_compression_body); // Should be different after compression
  7030. EXPECT_EQ("text/plain", post_compression_content_type);
  7031. EXPECT_EQ("gzip", post_compression_content_encoding);
  7032. // Verify compressed content is smaller
  7033. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7034. }
  7035. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7036. const std::string test_content =
  7037. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7038. "3456789012345678901234567890";
  7039. std::string pre_compression_body;
  7040. std::string post_compression_body;
  7041. svr_.set_pre_compression_logger(
  7042. [&](const Request & /*req*/, const Response &res) {
  7043. pre_compression_body = res.body;
  7044. });
  7045. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7046. post_compression_body = res.body;
  7047. });
  7048. Headers headers;
  7049. headers.emplace("Accept-Encoding", "br");
  7050. auto res = cli_.Get("/compress", headers);
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7054. // Verify pre-compression content is uncompressed
  7055. EXPECT_EQ(test_content, pre_compression_body);
  7056. // Verify post-compression content is compressed
  7057. EXPECT_NE(test_content, post_compression_body);
  7058. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7059. }
  7060. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7061. const std::string test_content =
  7062. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7063. "3456789012345678901234567890";
  7064. std::string pre_compression_body;
  7065. std::string post_compression_body;
  7066. svr_.set_pre_compression_logger(
  7067. [&](const Request & /*req*/, const Response &res) {
  7068. pre_compression_body = res.body;
  7069. });
  7070. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7071. post_compression_body = res.body;
  7072. });
  7073. // Request without compression (use /nocompress endpoint)
  7074. Headers headers;
  7075. auto res = cli_.Get("/nocompress", headers);
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::OK_200, res->status);
  7078. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7079. // Pre-compression logger should not be called when no compression is applied
  7080. EXPECT_TRUE(
  7081. pre_compression_body.empty()); // Pre-compression logger not called
  7082. EXPECT_EQ(
  7083. test_content,
  7084. post_compression_body); // Post-compression logger captures final content
  7085. }
  7086. TEST_F(ServerTest, LoggerSeesContentLength) {
  7087. size_t logged_content_length = 0;
  7088. std::string logged_content_length_header;
  7089. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7090. logged_content_length = res.content_length_;
  7091. logged_content_length_header = res.get_header_value("Content-Length");
  7092. });
  7093. auto res = cli_.Get("/nocompress");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. EXPECT_EQ(res->body.size(), logged_content_length);
  7097. EXPECT_EQ(std::to_string(logged_content_length),
  7098. logged_content_length_header);
  7099. }
  7100. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7101. const std::string test_content =
  7102. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7103. "3456789012345678901234567890";
  7104. std::string pre_compression_body;
  7105. bool pre_logger_called = false;
  7106. // Set only pre-compression logger
  7107. svr_.set_pre_compression_logger(
  7108. [&](const Request & /*req*/, const Response &res) {
  7109. pre_compression_body = res.body;
  7110. pre_logger_called = true;
  7111. });
  7112. Headers headers;
  7113. headers.emplace("Accept-Encoding", "gzip");
  7114. auto res = cli_.Get("/compress", headers);
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7118. // Verify pre-compression logger was called
  7119. EXPECT_TRUE(pre_logger_called);
  7120. EXPECT_EQ(test_content, pre_compression_body);
  7121. }
  7122. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7123. {
  7124. // Test with Expect: 100-continue header - success case
  7125. // Server returns 100 Continue, client sends body, server returns 200 OK
  7126. Request req;
  7127. req.method = "POST";
  7128. req.path = "/post-large";
  7129. req.set_header("Expect", "100-continue");
  7130. req.body = LARGE_DATA;
  7131. Response res;
  7132. auto error = Error::Success;
  7133. cli_.set_keep_alive(true);
  7134. auto ret = cli_.send(req, res, error);
  7135. EXPECT_TRUE(ret);
  7136. EXPECT_EQ(StatusCode::OK_200, res.status);
  7137. EXPECT_EQ(LARGE_DATA, res.body);
  7138. }
  7139. {
  7140. // Test with Expect: 100-continue header - error case
  7141. // Client should not send the body when server returns an error
  7142. Request req;
  7143. req.method = "POST";
  7144. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7145. req.set_header("Expect", "100-continue");
  7146. req.body = LARGE_DATA;
  7147. Response res;
  7148. auto error = Error::Success;
  7149. auto start = std::chrono::high_resolution_clock::now();
  7150. cli_.set_keep_alive(true);
  7151. auto ret = cli_.send(req, res, error);
  7152. auto end = std::chrono::high_resolution_clock::now();
  7153. auto elapsed =
  7154. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7155. .count();
  7156. // With Expect: 100-continue, request completes successfully but with error
  7157. EXPECT_TRUE(ret);
  7158. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7159. EXPECT_EQ("close", res.get_header_value("Connection"));
  7160. EXPECT_FALSE(cli_.is_socket_open());
  7161. EXPECT_LE(elapsed, 2000);
  7162. }
  7163. {
  7164. // Send an extra GET request to ensure error recovery without hanging
  7165. Request req;
  7166. req.method = "GET";
  7167. req.path = "/hi";
  7168. auto start = std::chrono::high_resolution_clock::now();
  7169. auto res = cli_.send(req);
  7170. auto end = std::chrono::high_resolution_clock::now();
  7171. auto elapsed =
  7172. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7173. .count();
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("Hello World!", res->body);
  7177. EXPECT_LE(elapsed, 500);
  7178. }
  7179. }
  7180. TEST(ZstdDecompressor, ChunkedDecompression) {
  7181. std::string data;
  7182. for (size_t i = 0; i < 32 * 1024; ++i) {
  7183. data.push_back(static_cast<char>('a' + i % 26));
  7184. }
  7185. std::string compressed_data;
  7186. {
  7187. httplib::detail::zstd_compressor compressor;
  7188. bool result = compressor.compress(
  7189. data.data(), data.size(),
  7190. /*last=*/true,
  7191. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7192. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7193. compressed_data_size);
  7194. return true;
  7195. });
  7196. ASSERT_TRUE(result);
  7197. }
  7198. std::string decompressed_data;
  7199. {
  7200. httplib::detail::zstd_decompressor decompressor;
  7201. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7202. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7203. size_t chunk_size = 130;
  7204. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7205. chunk_begin += chunk_size) {
  7206. size_t current_chunk_size =
  7207. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7208. bool result = decompressor.decompress(
  7209. compressed_data.data() + chunk_begin, current_chunk_size,
  7210. [&](const char *decompressed_data_chunk,
  7211. size_t decompressed_data_chunk_size) {
  7212. decompressed_data.insert(decompressed_data.size(),
  7213. decompressed_data_chunk,
  7214. decompressed_data_chunk_size);
  7215. return true;
  7216. });
  7217. ASSERT_TRUE(result);
  7218. }
  7219. }
  7220. ASSERT_EQ(data, decompressed_data);
  7221. }
  7222. TEST(ZstdDecompressor, Decompress) {
  7223. std::string original_text = "Compressed with ZSTD";
  7224. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7225. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7226. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7227. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7228. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7229. std::string decompressed_data;
  7230. {
  7231. httplib::detail::zstd_decompressor decompressor;
  7232. bool result = decompressor.decompress(
  7233. compressed_data.data(), compressed_data.size(),
  7234. [&](const char *decompressed_data_chunk,
  7235. size_t decompressed_data_chunk_size) {
  7236. decompressed_data.insert(decompressed_data.size(),
  7237. decompressed_data_chunk,
  7238. decompressed_data_chunk_size);
  7239. return true;
  7240. });
  7241. ASSERT_TRUE(result);
  7242. }
  7243. ASSERT_EQ(original_text, decompressed_data);
  7244. }
  7245. #endif
  7246. // Sends a raw request to a server listening at HOST:PORT.
  7247. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7248. std::string *resp = nullptr, int port = PORT) {
  7249. auto error = Error::Success;
  7250. auto client_sock = detail::create_client_socket(
  7251. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7252. /*connection_timeout_sec=*/5, 0,
  7253. /*read_timeout_sec=*/5, 0,
  7254. /*write_timeout_sec=*/5, 0, std::string(), error);
  7255. if (client_sock == INVALID_SOCKET) { return false; }
  7256. auto ret = detail::process_client_socket(
  7257. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7258. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7259. if (req.size() !=
  7260. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7261. return false;
  7262. }
  7263. char buf[512];
  7264. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7265. while (line_reader.getline()) {
  7266. if (resp) { *resp += line_reader.ptr(); }
  7267. }
  7268. return true;
  7269. });
  7270. detail::close_socket(client_sock);
  7271. return ret;
  7272. }
  7273. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7274. Server svr;
  7275. std::string header_value;
  7276. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7277. header_value = req.get_header_value("foo");
  7278. res.set_content("ok", "text/plain");
  7279. });
  7280. thread t = thread([&] { svr.listen(HOST, PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. t.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7288. // like characters are not treated the same - use vertical tab and escape.
  7289. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7290. "foo: \t \v bar \x1B\t \r\n"
  7291. "Connection: close\r\n"
  7292. "\r\n";
  7293. std::string res;
  7294. ASSERT_TRUE(send_request(5, req, &res));
  7295. EXPECT_EQ(header_value, "");
  7296. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7297. }
  7298. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7299. Server svr;
  7300. std::string received;
  7301. svr.Get("/order", [&](const Request &req, Response &res) {
  7302. received = entries_to_string(req.headers);
  7303. res.set_content("ok", "text/plain");
  7304. });
  7305. auto port = svr.bind_to_any_port(HOST);
  7306. thread t = thread([&] { svr.listen_after_bind(); });
  7307. auto se = detail::scope_exit([&] {
  7308. svr.stop();
  7309. t.join();
  7310. ASSERT_FALSE(svr.is_running());
  7311. });
  7312. svr.wait_until_ready();
  7313. const std::string req = "GET /order HTTP/1.1\r\n"
  7314. "X-First: 1\r\n"
  7315. "X-Dup: a\r\n"
  7316. "X-Second: 2\r\n"
  7317. "X-Dup: b\r\n"
  7318. "Connection: close\r\n"
  7319. "\r\n";
  7320. std::string res;
  7321. ASSERT_TRUE(send_request(5, req, &res, port));
  7322. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7323. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7324. }
  7325. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7326. Server svr;
  7327. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7328. res.set_header("Set-Cookie", "first=1");
  7329. res.set_header("X-Between", "y");
  7330. res.set_header("Set-Cookie", "second=2");
  7331. res.set_content("ok", "text/plain");
  7332. });
  7333. auto port = svr.bind_to_any_port(HOST);
  7334. thread t = thread([&] { svr.listen_after_bind(); });
  7335. auto se = detail::scope_exit([&] {
  7336. svr.stop();
  7337. t.join();
  7338. ASSERT_FALSE(svr.is_running());
  7339. });
  7340. svr.wait_until_ready();
  7341. Client cli(HOST, port);
  7342. auto res = cli.Get("/cookies");
  7343. ASSERT_TRUE(res);
  7344. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7345. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7346. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7347. }
  7348. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7349. Server svr;
  7350. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7351. auto i = new int(0);
  7352. res.set_header("Trailer", "X-Safe, X-Reflected");
  7353. res.set_chunked_content_provider(
  7354. "text/plain",
  7355. [i](size_t /*offset*/, DataSink &sink) {
  7356. if (*i == 0) {
  7357. sink.os << "body";
  7358. } else {
  7359. Headers trailer;
  7360. // A valid trailer that must survive.
  7361. trailer.emplace("X-Safe", "safe");
  7362. // Attacker-controlled value carrying CR/LF (response splitting).
  7363. trailer.emplace("X-Reflected",
  7364. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7365. // Attacker-controlled name carrying CR/LF.
  7366. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7367. sink.done_with_trailer(trailer);
  7368. }
  7369. (*i)++;
  7370. return true;
  7371. },
  7372. [i](bool /*success*/) { delete i; });
  7373. });
  7374. thread t = thread([&] { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7382. "Host: " + HOST +
  7383. "\r\n"
  7384. "Connection: close\r\n"
  7385. "\r\n";
  7386. std::string res;
  7387. ASSERT_TRUE(send_request(5, req, &res));
  7388. // The injected fields must not appear anywhere in the raw response.
  7389. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7390. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7391. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7392. // Invalid trailers are dropped entirely, matching set_header().
  7393. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7394. // The valid trailer still passes through.
  7395. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7396. }
  7397. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7398. Server svr;
  7399. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7400. // res.headers is a public field an application can populate directly,
  7401. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7402. // A valid header that must survive.
  7403. res.headers.emplace("X-Safe", "safe");
  7404. // Attacker-controlled value carrying CR/LF (response splitting).
  7405. res.headers.emplace("X-Reflected",
  7406. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7407. // Attacker-controlled name carrying CR/LF.
  7408. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7409. res.set_content("body", "text/plain");
  7410. });
  7411. thread t = thread([&] { svr.listen(HOST, PORT); });
  7412. auto se = detail::scope_exit([&] {
  7413. svr.stop();
  7414. t.join();
  7415. ASSERT_FALSE(svr.is_running());
  7416. });
  7417. svr.wait_until_ready();
  7418. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7419. "Host: " + HOST +
  7420. "\r\n"
  7421. "Connection: close\r\n"
  7422. "\r\n";
  7423. std::string res;
  7424. ASSERT_TRUE(send_request(5, req, &res));
  7425. // The injected fields must not appear anywhere in the raw response.
  7426. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7427. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7428. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7429. // Invalid headers are dropped entirely, matching set_header().
  7430. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7431. // The valid header still passes through.
  7432. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7433. }
  7434. // Forward declaration: in split builds split.py strips `inline` and moves the
  7435. // definition into httplib.cc, so detail::write_request_line is not visible from
  7436. // the public httplib.h. Re-declaring it here lets the tests link against the
  7437. // symbol in both header-only and split builds.
  7438. namespace httplib {
  7439. namespace detail {
  7440. ssize_t write_request_line(Stream &strm, const std::string &method,
  7441. const std::string &path);
  7442. } // namespace detail
  7443. } // namespace httplib
  7444. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7445. // A well-formed target is written verbatim.
  7446. {
  7447. detail::BufferStream strm;
  7448. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7449. EXPECT_GT(n, 0);
  7450. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7451. }
  7452. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7453. // otherwise it splits the request line and injects a header or a whole
  7454. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7455. // when path encoding is disabled.
  7456. const std::string evil_targets[] = {
  7457. "/a\r\nInjected: pwned",
  7458. "/a\rInjected",
  7459. "/a\nInjected",
  7460. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7461. };
  7462. for (const auto &evil : evil_targets) {
  7463. detail::BufferStream strm;
  7464. auto n = detail::write_request_line(strm, "GET", evil);
  7465. EXPECT_LT(n, 0);
  7466. EXPECT_TRUE(strm.get_buffer().empty());
  7467. }
  7468. }
  7469. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7470. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7471. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7472. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7473. // client must fail cleanly with Error::Write instead of putting a
  7474. // request-line-less, header-injecting request on the wire.
  7475. Server svr;
  7476. svr.Get("/a", [](const Request &, Response &res) {
  7477. res.set_content("ok", "text/plain");
  7478. });
  7479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7480. auto se = detail::scope_exit([&] {
  7481. svr.stop();
  7482. thread.join();
  7483. ASSERT_FALSE(svr.is_running());
  7484. });
  7485. svr.wait_until_ready();
  7486. {
  7487. Client cli(HOST, PORT);
  7488. cli.set_path_encode(false);
  7489. // The request is rejected before anything is written, so the connection
  7490. // stays silent and the subsequent response read would otherwise block for
  7491. // the full default read timeout. Shorten it -- the assertion is on the
  7492. // error, not the timeout.
  7493. cli.set_read_timeout(1, 0);
  7494. auto res = cli.Get("/a\r\nInjected: pwned");
  7495. EXPECT_FALSE(res);
  7496. EXPECT_EQ(Error::Write, res.error());
  7497. }
  7498. }
  7499. // Sends a raw request and verifies that there isn't a crash or exception.
  7500. static void test_raw_request(const std::string &req,
  7501. std::string *out = nullptr) {
  7502. Server svr;
  7503. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7504. res.set_content("ok", "text/plain");
  7505. });
  7506. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7507. res.set_content("ok", "text/plain");
  7508. });
  7509. svr.Get("/header_field_value_check",
  7510. [&](const Request & /*req*/, Response &res) {
  7511. res.set_content("ok", "text/plain");
  7512. });
  7513. // Server read timeout must be longer than the client read timeout for the
  7514. // bug to reproduce, probably to force the server to process a request
  7515. // without a trailing blank line.
  7516. const time_t client_read_timeout_sec = 1;
  7517. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7518. bool listen_thread_ok = false;
  7519. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7520. auto se = detail::scope_exit([&] {
  7521. svr.stop();
  7522. t.join();
  7523. ASSERT_FALSE(svr.is_running());
  7524. EXPECT_TRUE(listen_thread_ok);
  7525. });
  7526. svr.wait_until_ready();
  7527. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7528. }
  7529. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7530. // A certain header line causes an exception if the header property is parsed
  7531. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7532. test_raw_request(
  7533. "GET /hi HTTP/1.1\r\n"
  7534. " : "
  7535. " "
  7536. " ");
  7537. }
  7538. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7539. // A certain header line causes an exception if the header property *name* is
  7540. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7541. // greedy matcher and requires backtracking when there are a lot of ":"
  7542. // characters.
  7543. // This occurs with libc++ but not libstdc++.
  7544. test_raw_request(
  7545. "GET /hi HTTP/1.1\r\n"
  7546. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7547. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7548. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7549. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7550. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7551. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7552. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7553. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7554. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7555. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7556. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7557. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7558. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7559. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7560. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7561. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7562. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7563. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7564. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7565. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7566. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7567. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7568. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7569. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7570. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7571. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7572. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7573. "&&&%%%");
  7574. }
  7575. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7576. // Make sure this doesn't crash the server.
  7577. // In a previous version of the header line regex, the "\r" rendered the line
  7578. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7579. // a new position where the leading white space ended and the field value
  7580. // began.
  7581. // The crash occurs with libc++ but not libstdc++.
  7582. test_raw_request("GET /hi HTTP/1.1\r\n"
  7583. "a:" +
  7584. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7585. "\r\n"
  7586. "\r\n");
  7587. }
  7588. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7589. std::string out;
  7590. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7591. "Content-Type: text/plain\r\n"
  7592. "Transfer-Encoding: chunked\r\n"
  7593. "\r\n"
  7594. "nothex\r\n",
  7595. &out);
  7596. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7597. }
  7598. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7599. std::string out;
  7600. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7601. "Content-Type: text/plain\r\n"
  7602. "Transfer-Encoding: chunked\r\n"
  7603. "\r\n"
  7604. "3\r\n"
  7605. "xyz\r\n"
  7606. "NaN\r\n",
  7607. &out);
  7608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7609. }
  7610. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7611. std::string out;
  7612. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7613. "Content-Type: text/plain\r\n"
  7614. "Transfer-Encoding: chunked\r\n"
  7615. "\r\n"
  7616. // Length is too large for 64 bits.
  7617. "1ffffffffffffffff\r\n"
  7618. "xyz\r\n",
  7619. &out);
  7620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7621. }
  7622. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7623. test_raw_request("GET /hi HTTP/1.1\r\n"
  7624. "Content-Type: text/plain\r\n\r");
  7625. }
  7626. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7627. std::string out;
  7628. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7629. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7630. }
  7631. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7632. Server svr;
  7633. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7634. EXPECT_TRUE(!req.remote_addr.empty());
  7635. });
  7636. thread t = thread([&] { svr.listen(HOST, PORT); });
  7637. auto se = detail::scope_exit([&] {
  7638. svr.stop();
  7639. t.join();
  7640. ASSERT_FALSE(svr.is_running());
  7641. });
  7642. svr.wait_until_ready();
  7643. // Send an invalid request line to trigger Bad Request
  7644. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7645. std::string out;
  7646. ASSERT_TRUE(send_request(5, bad_req, &out));
  7647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7648. }
  7649. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7650. std::string out;
  7651. std::string request(
  7652. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7653. test_raw_request(request, &out);
  7654. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7655. }
  7656. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7657. std::string out;
  7658. std::string request(
  7659. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7660. test_raw_request(request, &out);
  7661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7662. }
  7663. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7664. std::string out;
  7665. std::string request(
  7666. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7667. test_raw_request(request, &out);
  7668. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7669. }
  7670. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7671. std::string out;
  7672. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7673. "Test: \r\n\r\n",
  7674. &out);
  7675. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7676. }
  7677. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7678. Server svr;
  7679. std::string x_custom;
  7680. std::string cookie;
  7681. std::string xff;
  7682. std::string x_unicode;
  7683. std::string x_iis;
  7684. svr.Get("/check", [&](const Request &req, Response &res) {
  7685. x_custom = req.get_header_value("X-Custom");
  7686. cookie = req.get_header_value("Cookie");
  7687. xff = req.get_header_value("X-Forwarded-For");
  7688. x_unicode = req.get_header_value("X-Unicode");
  7689. x_iis = req.get_header_value("X-IIS");
  7690. res.set_content("ok", "text/plain");
  7691. });
  7692. thread t = thread([&] { svr.listen(HOST, PORT); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. t.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. });
  7698. svr.wait_until_ready();
  7699. const std::string req = "GET /check HTTP/1.1\r\n"
  7700. "Host: localhost\r\n"
  7701. "X-Custom: a%0D%0AInjected: b\r\n"
  7702. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7703. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7704. "X-Unicode: %E3%81%82\r\n"
  7705. "X-IIS: %u00E9\r\n"
  7706. "Connection: close\r\n"
  7707. "\r\n";
  7708. std::string res;
  7709. ASSERT_TRUE(send_request(5, req, &res));
  7710. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7711. // Every value must be returned verbatim (wire form), with no decoding.
  7712. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7713. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7714. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7715. EXPECT_EQ("%E3%81%82", x_unicode);
  7716. EXPECT_EQ("%u00E9", x_iis);
  7717. }
  7718. // Applications that previously relied on automatic percent-decoding can
  7719. // reproduce the old behavior by explicitly calling decode_path_component()
  7720. // or, for RFC 3986 conformance, decode_uri_component().
  7721. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7722. Server svr;
  7723. std::string decoded;
  7724. svr.Get("/check", [&](const Request &req, Response &res) {
  7725. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7726. res.set_content("ok", "text/plain");
  7727. });
  7728. thread t = thread([&] { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. t.join();
  7732. ASSERT_FALSE(svr.is_running());
  7733. });
  7734. svr.wait_until_ready();
  7735. const std::string req = "GET /check HTTP/1.1\r\n"
  7736. "Host: localhost\r\n"
  7737. "X-Custom: hello%20world\r\n"
  7738. "Connection: close\r\n"
  7739. "\r\n";
  7740. std::string res;
  7741. ASSERT_TRUE(send_request(5, req, &res));
  7742. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7743. EXPECT_EQ("hello world", decoded);
  7744. }
  7745. // Regression test for #2033. Browsers send Referer values that include
  7746. // percent-encoded characters such as %0A inside the URL. Decoding the
  7747. // header value would either trip the post-decode CR/LF/NUL guard (the
  7748. // original bug, returning 400) or, after that guard was relaxed, silently
  7749. // store a literal LF — both unacceptable. The wire form must round-trip.
  7750. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7751. Server svr;
  7752. std::string referer;
  7753. svr.Get("/check", [&](const Request &req, Response &res) {
  7754. referer = req.get_header_value("Referer");
  7755. res.set_content("ok", "text/plain");
  7756. });
  7757. thread t = thread([&] { svr.listen(HOST, PORT); });
  7758. auto se = detail::scope_exit([&] {
  7759. svr.stop();
  7760. t.join();
  7761. ASSERT_FALSE(svr.is_running());
  7762. });
  7763. svr.wait_until_ready();
  7764. const std::string req = "GET /check HTTP/1.1\r\n"
  7765. "Host: localhost\r\n"
  7766. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7767. "Connection: close\r\n"
  7768. "\r\n";
  7769. std::string res;
  7770. ASSERT_TRUE(send_request(5, req, &res));
  7771. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7772. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7773. }
  7774. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7775. Server svr;
  7776. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7777. res.set_header("Cache-Control", "no-cache");
  7778. res.set_chunked_content_provider(
  7779. "text/event-stream", [](size_t offset, DataSink &sink) {
  7780. std::string s = "data:";
  7781. s += std::to_string(offset);
  7782. s += "\n\n";
  7783. auto ret = sink.write(s.data(), s.size());
  7784. EXPECT_TRUE(ret);
  7785. std::this_thread::sleep_for(std::chrono::seconds(1));
  7786. return true;
  7787. });
  7788. });
  7789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7790. svr.wait_until_ready();
  7791. Client client(HOST, PORT);
  7792. const Headers headers = {{"Accept", "text/event-stream"}};
  7793. auto get_thread = std::thread([&client, &headers]() {
  7794. auto res = client.Get(
  7795. "/events", headers,
  7796. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7797. });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. get_thread.join();
  7801. listen_thread.join();
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. // Give GET time to get a few messages.
  7805. std::this_thread::sleep_for(std::chrono::seconds(2));
  7806. }
  7807. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7808. httplib::Server svr;
  7809. svr.Post("/hi",
  7810. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7811. res.status = StatusCode::OK_200;
  7812. });
  7813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7814. svr.wait_until_ready();
  7815. Client cli(HOST, PORT);
  7816. auto res = cli.Post("/hi", "data", "text/plain");
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::OK_200, res->status);
  7819. svr.stop();
  7820. thread.join();
  7821. ASSERT_FALSE(svr.is_running());
  7822. res = cli.Post("/hi", "data", "text/plain");
  7823. ASSERT_FALSE(res);
  7824. }
  7825. TEST(ServerStopTest, ListenFailure) {
  7826. Server svr;
  7827. auto t = thread([&]() {
  7828. auto ret = svr.listen("????", PORT);
  7829. EXPECT_FALSE(ret);
  7830. });
  7831. svr.wait_until_ready();
  7832. svr.stop();
  7833. t.join();
  7834. }
  7835. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7836. TEST(ServerStopTest, Decommision) {
  7837. Server svr;
  7838. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7839. for (int i = 0; i < 4; i++) {
  7840. auto is_even = !(i % 2);
  7841. std::thread t{[&] {
  7842. try {
  7843. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7844. if (is_even) {
  7845. throw std::runtime_error("Some thing that happens to go wrong.");
  7846. }
  7847. svr.listen(HOST, PORT);
  7848. } catch (...) { svr.decommission(); }
  7849. }};
  7850. svr.wait_until_ready();
  7851. // Server is up
  7852. {
  7853. Client cli(HOST, PORT);
  7854. auto res = cli.Get("/hi");
  7855. if (is_even) {
  7856. EXPECT_FALSE(res);
  7857. } else {
  7858. EXPECT_TRUE(res);
  7859. EXPECT_EQ("hi...", res->body);
  7860. }
  7861. }
  7862. svr.stop();
  7863. t.join();
  7864. // Server is down...
  7865. {
  7866. Client cli(HOST, PORT);
  7867. auto res = cli.Get("/hi");
  7868. EXPECT_FALSE(res);
  7869. }
  7870. }
  7871. }
  7872. #endif
  7873. // Helper function for string body upload progress tests
  7874. template <typename SetupHandler, typename ClientCall>
  7875. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7876. ClientCall &&client_call,
  7877. const string &body) {
  7878. Server svr;
  7879. setup_handler(svr);
  7880. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7881. auto se = detail::scope_exit([&] {
  7882. svr.stop();
  7883. t.join();
  7884. });
  7885. svr.wait_until_ready();
  7886. Client cli(HOST, PORT);
  7887. vector<uint64_t> progress_values;
  7888. bool progress_called = false;
  7889. auto res =
  7890. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7891. progress_values.push_back(current);
  7892. progress_called = true;
  7893. return true;
  7894. });
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(200, res->status);
  7897. EXPECT_TRUE(progress_called);
  7898. }
  7899. TEST(UploadProgressTest, PostStringBodyBasic) {
  7900. TestStringBodyUploadProgress(
  7901. [](Server &svr) {
  7902. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7903. res.set_content("received", "text/plain");
  7904. });
  7905. },
  7906. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7907. return cli.Post("/test", body, "text/plain", progress_callback);
  7908. },
  7909. "test data for upload progress");
  7910. }
  7911. TEST(UploadProgressTest, PutStringBodyBasic) {
  7912. TestStringBodyUploadProgress(
  7913. [](Server &svr) {
  7914. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7915. res.set_content("put received", "text/plain");
  7916. });
  7917. },
  7918. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7919. return cli.Put("/test", body, "text/plain", progress_callback);
  7920. },
  7921. "put test data for upload progress");
  7922. }
  7923. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7924. TestStringBodyUploadProgress(
  7925. [](Server &svr) {
  7926. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7927. res.set_content("patch received", "text/plain");
  7928. });
  7929. },
  7930. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7931. return cli.Patch("/test", body, "text/plain", progress_callback);
  7932. },
  7933. "patch test data for upload progress");
  7934. }
  7935. // Helper function for content provider upload progress tests
  7936. template <typename SetupHandler, typename ClientCall>
  7937. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7938. ClientCall &&client_call) {
  7939. Server svr;
  7940. setup_handler(svr);
  7941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7942. auto se = detail::scope_exit([&] {
  7943. svr.stop();
  7944. t.join();
  7945. });
  7946. svr.wait_until_ready();
  7947. Client cli(HOST, PORT);
  7948. vector<uint64_t> progress_values;
  7949. auto res =
  7950. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7951. progress_values.push_back(current);
  7952. return true;
  7953. });
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(200, res->status);
  7956. EXPECT_FALSE(progress_values.empty());
  7957. }
  7958. TEST(UploadProgressTest, PostContentProviderProgress) {
  7959. TestContentProviderUploadProgress(
  7960. [](Server &svr) {
  7961. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7962. res.set_content("provider received", "text/plain");
  7963. });
  7964. },
  7965. [](Client &cli, UploadProgress progress_callback) {
  7966. return cli.Post(
  7967. "/test", 10,
  7968. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7969. sink.os << "test data";
  7970. return true;
  7971. },
  7972. "text/plain", progress_callback);
  7973. });
  7974. }
  7975. // Helper function for multipart upload progress tests
  7976. template <typename SetupHandler, typename ClientCall>
  7977. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7978. ClientCall &&client_call,
  7979. const string &endpoint) {
  7980. Server svr;
  7981. setup_handler(svr);
  7982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7983. auto se = detail::scope_exit([&] {
  7984. svr.stop();
  7985. t.join();
  7986. });
  7987. svr.wait_until_ready();
  7988. Client cli(HOST, PORT);
  7989. vector<uint64_t> progress_values;
  7990. UploadFormDataItems items = {
  7991. {"field1", "value1", "", ""},
  7992. {"field2", "longer value for progress tracking test", "", ""},
  7993. {"file1", "file content data for upload progress", "test.txt",
  7994. "text/plain"}};
  7995. auto res = client_call(cli, endpoint, items,
  7996. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7997. progress_values.push_back(current);
  7998. return true;
  7999. });
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(200, res->status);
  8002. EXPECT_FALSE(progress_values.empty());
  8003. }
  8004. TEST(UploadProgressTest, PostMultipartProgress) {
  8005. TestMultipartUploadProgress(
  8006. [](Server &svr) {
  8007. svr.Post("/multipart", [](const Request &req, Response &res) {
  8008. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8009. res.set_content("multipart received", "text/plain");
  8010. });
  8011. },
  8012. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8013. UploadProgress progress_callback) {
  8014. return cli.Post(endpoint, items, progress_callback);
  8015. },
  8016. "/multipart");
  8017. }
  8018. // Helper function for basic download progress tests
  8019. template <typename SetupHandler, typename ClientCall>
  8020. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8021. ClientCall &&client_call, const string &endpoint,
  8022. size_t expected_content_size) {
  8023. Server svr;
  8024. setup_handler(svr);
  8025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8026. auto se = detail::scope_exit([&] {
  8027. svr.stop();
  8028. t.join();
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli(HOST, PORT);
  8032. vector<uint64_t> progress_values;
  8033. auto res = client_call(cli, endpoint,
  8034. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8035. progress_values.push_back(current);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ(200, res->status);
  8040. EXPECT_FALSE(progress_values.empty());
  8041. EXPECT_EQ(expected_content_size, res->body.size());
  8042. }
  8043. TEST(DownloadProgressTest, GetBasic) {
  8044. TestBasicDownloadProgress(
  8045. [](Server &svr) {
  8046. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8047. string content(1000, 'D');
  8048. res.set_content(content, "text/plain");
  8049. });
  8050. },
  8051. [](Client &cli, const string &endpoint,
  8052. DownloadProgress progress_callback) {
  8053. return cli.Get(endpoint, progress_callback);
  8054. },
  8055. "/download", 1000u);
  8056. }
  8057. // Helper function for content receiver download progress tests
  8058. template <typename SetupHandler, typename ClientCall>
  8059. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8060. ClientCall &&client_call,
  8061. const string &endpoint,
  8062. size_t expected_content_size) {
  8063. Server svr;
  8064. setup_handler(svr);
  8065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8066. auto se = detail::scope_exit([&] {
  8067. svr.stop();
  8068. t.join();
  8069. });
  8070. svr.wait_until_ready();
  8071. Client cli(HOST, PORT);
  8072. vector<uint64_t> progress_values;
  8073. string received_body;
  8074. auto res = client_call(
  8075. cli, endpoint,
  8076. [&](const char *data, size_t data_length) -> bool {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8081. progress_values.push_back(current);
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(200, res->status);
  8086. EXPECT_FALSE(progress_values.empty());
  8087. EXPECT_EQ(expected_content_size, received_body.size());
  8088. EXPECT_TRUE(res->body.empty());
  8089. }
  8090. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8091. TestContentReceiverDownloadProgress(
  8092. [](Server &svr) {
  8093. svr.Get("/download-receiver",
  8094. [](const Request & /*req*/, Response &res) {
  8095. string content(2000, 'R');
  8096. res.set_content(content, "text/plain");
  8097. });
  8098. },
  8099. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8100. DownloadProgress progress_callback) {
  8101. return cli.Get(endpoint, content_receiver, progress_callback);
  8102. },
  8103. "/download-receiver", 2000u);
  8104. }
  8105. TEST(StreamingTest, NoContentLengthStreaming) {
  8106. Server svr;
  8107. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8108. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8109. if (offset < 6) {
  8110. sink.os << (offset < 3 ? "a" : "b");
  8111. } else {
  8112. sink.done();
  8113. }
  8114. return true;
  8115. });
  8116. });
  8117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8118. auto listen_se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. listen_thread.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. });
  8123. svr.wait_until_ready();
  8124. Client client(HOST, PORT);
  8125. auto get_thread = std::thread([&client]() {
  8126. std::string s;
  8127. auto res =
  8128. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8129. s += std::string(data, len);
  8130. return true;
  8131. });
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ("aaabbb", s);
  8135. });
  8136. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8137. // Give GET time to get a few messages.
  8138. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8139. }
  8140. TEST(MountTest, Unmount) {
  8141. Server svr;
  8142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8143. auto se = detail::scope_exit([&] {
  8144. svr.stop();
  8145. listen_thread.join();
  8146. ASSERT_FALSE(svr.is_running());
  8147. });
  8148. svr.wait_until_ready();
  8149. Client cli("localhost", PORT);
  8150. svr.set_mount_point("/mount2", "./www2");
  8151. auto res = cli.Get("/");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. res = cli.Get("/mount2/dir/test.html");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. svr.set_mount_point("/", "./www");
  8158. res = cli.Get("/dir/");
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. svr.remove_mount_point("/");
  8162. res = cli.Get("/dir/");
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8165. svr.remove_mount_point("/mount2");
  8166. res = cli.Get("/mount2/dir/test.html");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8169. }
  8170. TEST(MountTest, PathSegmentBoundary) {
  8171. Server svr;
  8172. svr.set_mount_point("/mount2", "./www2");
  8173. svr.set_mount_point("/", "./www");
  8174. auto port = svr.bind_to_any_port(HOST);
  8175. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8176. auto se = detail::scope_exit([&] {
  8177. svr.stop();
  8178. listen_thread.join();
  8179. ASSERT_FALSE(svr.is_running());
  8180. });
  8181. svr.wait_until_ready();
  8182. Client cli(HOST, port);
  8183. auto res = cli.Get("/mount2/dir/test.html");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. // "/mount2" must not match part-way through a path segment.
  8187. res = cli.Get("/mount2dir/test.html");
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8190. // A mount point ending in '/' keeps matching every path below it.
  8191. res = cli.Get("/dir/test.html");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST(MountTest, Redicect) {
  8196. Server svr;
  8197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8198. auto se = detail::scope_exit([&] {
  8199. svr.stop();
  8200. listen_thread.join();
  8201. ASSERT_FALSE(svr.is_running());
  8202. });
  8203. svr.set_mount_point("/", "./www");
  8204. svr.wait_until_ready();
  8205. Client cli("localhost", PORT);
  8206. auto res = cli.Get("/dir/");
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. res = cli.Get("/dir");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8212. res = cli.Get("/file");
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::OK_200, res->status);
  8215. res = cli.Get("/file/");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8218. cli.set_follow_location(true);
  8219. res = cli.Get("/dir");
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. }
  8223. TEST(MountTest, MultibytesPathName) {
  8224. Server svr;
  8225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8226. auto se = detail::scope_exit([&] {
  8227. svr.stop();
  8228. listen_thread.join();
  8229. ASSERT_FALSE(svr.is_running());
  8230. });
  8231. svr.set_mount_point("/", "./www");
  8232. svr.wait_until_ready();
  8233. Client cli("localhost", PORT);
  8234. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8238. }
  8239. #ifdef _WIN32
  8240. // Issue #2435: mmap::open() must succeed even when another handle holds
  8241. // the file open for writing (e.g. an active log file).
  8242. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8243. const char *path = "mmap_concurrent_writer_test.txt";
  8244. const char *content = "hello";
  8245. {
  8246. std::ofstream f(path, std::ios::binary);
  8247. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8248. }
  8249. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8250. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8251. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8252. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8253. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8254. detail::mmap m(path);
  8255. ASSERT_TRUE(m.is_open());
  8256. EXPECT_EQ(strlen(content), m.size());
  8257. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8258. }
  8259. #endif
  8260. #ifndef _WIN32
  8261. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8262. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8263. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8264. TEST(MmapTest, FailedMappingIsNotOpen) {
  8265. const char *path = "./mmap_failed_mapping_test_dir";
  8266. ASSERT_EQ(0, ::mkdir(path, 0755));
  8267. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8268. detail::mmap m(path);
  8269. EXPECT_FALSE(m.is_open());
  8270. EXPECT_EQ(0U, m.size());
  8271. EXPECT_NE(static_cast<const void *>(m.data()),
  8272. static_cast<const void *>(MAP_FAILED));
  8273. }
  8274. #endif
  8275. TEST(KeepAliveTest, ReadTimeout) {
  8276. Server svr;
  8277. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8278. std::this_thread::sleep_for(std::chrono::seconds(2));
  8279. res.set_content("a", "text/plain");
  8280. });
  8281. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8282. res.set_content("b", "text/plain");
  8283. });
  8284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. listen_thread.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. Client cli("localhost", PORT);
  8292. cli.set_keep_alive(true);
  8293. cli.set_read_timeout(std::chrono::seconds(1));
  8294. auto resa = cli.Get("/a");
  8295. ASSERT_FALSE(resa);
  8296. EXPECT_EQ(Error::Read, resa.error());
  8297. auto resb = cli.Get("/b");
  8298. ASSERT_TRUE(resb);
  8299. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8300. EXPECT_EQ("b", resb->body);
  8301. }
  8302. TEST(KeepAliveTest, MaxCount) {
  8303. size_t keep_alive_max_count = 3;
  8304. Server svr;
  8305. svr.set_keep_alive_max_count(keep_alive_max_count);
  8306. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8307. res.set_content("Hello World!", "text/plain");
  8308. });
  8309. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8310. auto se = detail::scope_exit([&] {
  8311. svr.stop();
  8312. listen_thread.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. });
  8315. svr.wait_until_ready();
  8316. Client cli(HOST, PORT);
  8317. cli.set_keep_alive(true);
  8318. for (size_t i = 0; i < 5; i++) {
  8319. auto result = cli.Get("/hi");
  8320. ASSERT_TRUE(result);
  8321. EXPECT_EQ(StatusCode::OK_200, result->status);
  8322. if (i == keep_alive_max_count - 1) {
  8323. EXPECT_EQ("close", result->get_header_value("Connection"));
  8324. } else {
  8325. EXPECT_FALSE(result->has_header("Connection"));
  8326. }
  8327. }
  8328. }
  8329. TEST(KeepAliveTest, Issue1041) {
  8330. Server svr;
  8331. svr.set_keep_alive_timeout(3);
  8332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8333. res.set_content("Hello World!", "text/plain");
  8334. });
  8335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8336. auto se = detail::scope_exit([&] {
  8337. svr.stop();
  8338. listen_thread.join();
  8339. ASSERT_FALSE(svr.is_running());
  8340. });
  8341. svr.wait_until_ready();
  8342. Client cli(HOST, PORT);
  8343. cli.set_keep_alive(true);
  8344. auto result = cli.Get("/hi");
  8345. ASSERT_TRUE(result);
  8346. EXPECT_EQ(StatusCode::OK_200, result->status);
  8347. std::this_thread::sleep_for(std::chrono::seconds(5));
  8348. result = cli.Get("/hi");
  8349. ASSERT_TRUE(result);
  8350. EXPECT_EQ(StatusCode::OK_200, result->status);
  8351. }
  8352. TEST(KeepAliveTest, Issue1959) {
  8353. Server svr;
  8354. svr.set_keep_alive_timeout(5);
  8355. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8356. res.set_content("a", "text/plain");
  8357. });
  8358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8359. auto se = detail::scope_exit([&] {
  8360. if (!svr.is_running()) return;
  8361. svr.stop();
  8362. listen_thread.join();
  8363. ASSERT_FALSE(svr.is_running());
  8364. });
  8365. svr.wait_until_ready();
  8366. Client cli("localhost", PORT);
  8367. cli.set_keep_alive(true);
  8368. using namespace std::chrono;
  8369. auto start = steady_clock::now();
  8370. cli.Get("/a");
  8371. svr.stop();
  8372. listen_thread.join();
  8373. auto end = steady_clock::now();
  8374. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8375. EXPECT_LT(elapsed, 5000);
  8376. }
  8377. #ifdef CPPHTTPLIB_SSL_ENABLED
  8378. TEST(KeepAliveTest, SSLClientReconnection) {
  8379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8380. ASSERT_TRUE(svr.is_valid());
  8381. svr.set_keep_alive_timeout(1);
  8382. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8383. res.set_content("Hello World!", "text/plain");
  8384. });
  8385. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8386. auto se = detail::scope_exit([&] {
  8387. svr.stop();
  8388. listen_thread.join();
  8389. ASSERT_FALSE(svr.is_running());
  8390. });
  8391. svr.wait_until_ready();
  8392. SSLClient cli(HOST, PORT);
  8393. cli.enable_server_certificate_verification(false);
  8394. cli.set_keep_alive(true);
  8395. auto result = cli.Get("/hi");
  8396. ASSERT_TRUE(result);
  8397. EXPECT_EQ(StatusCode::OK_200, result->status);
  8398. result = cli.Get("/hi");
  8399. ASSERT_TRUE(result);
  8400. EXPECT_EQ(StatusCode::OK_200, result->status);
  8401. std::this_thread::sleep_for(std::chrono::seconds(2));
  8402. // Recoonect
  8403. result = cli.Get("/hi");
  8404. ASSERT_TRUE(result);
  8405. EXPECT_EQ(StatusCode::OK_200, result->status);
  8406. result = cli.Get("/hi");
  8407. ASSERT_TRUE(result);
  8408. EXPECT_EQ(StatusCode::OK_200, result->status);
  8409. }
  8410. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8412. ASSERT_TRUE(svr.is_valid());
  8413. svr.set_keep_alive_timeout(1);
  8414. std::string content = "reconnect";
  8415. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8416. res.set_content("Hello World!", "text/plain");
  8417. });
  8418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8419. auto se = detail::scope_exit([&] {
  8420. svr.stop();
  8421. listen_thread.join();
  8422. ASSERT_FALSE(svr.is_running());
  8423. });
  8424. svr.wait_until_ready();
  8425. SSLClient cli(HOST, PORT);
  8426. cli.enable_server_certificate_verification(false);
  8427. cli.set_keep_alive(true);
  8428. auto result = cli.Post(
  8429. "/hi", content.size(),
  8430. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8431. sink.write(content.c_str(), content.size());
  8432. return true;
  8433. },
  8434. "text/plain");
  8435. ASSERT_TRUE(result);
  8436. EXPECT_EQ(200, result->status);
  8437. std::this_thread::sleep_for(std::chrono::seconds(2));
  8438. // Recoonect
  8439. result = cli.Post(
  8440. "/hi", content.size(),
  8441. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8442. sink.write(content.c_str(), content.size());
  8443. return true;
  8444. },
  8445. "text/plain");
  8446. ASSERT_TRUE(result);
  8447. EXPECT_EQ(200, result->status);
  8448. result = cli.Post(
  8449. "/hi", content.size(),
  8450. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8451. sink.write(content.c_str(), content.size());
  8452. return true;
  8453. },
  8454. "text/plain");
  8455. ASSERT_TRUE(result);
  8456. EXPECT_EQ(200, result->status);
  8457. }
  8458. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8459. using namespace httplib::tls;
  8460. {
  8461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8462. ASSERT_TRUE(svr.is_valid());
  8463. svr.Get("/sni", [&](const Request &req, Response &res) {
  8464. std::string expected = req.sni();
  8465. EXPECT_EQ(expected, req.get_param_value("expected"));
  8466. res.set_content("ok", "text/plain");
  8467. });
  8468. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. listen_thread.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. {
  8476. SSLClient cli("localhost", PORT);
  8477. cli.enable_server_certificate_verification(false);
  8478. auto res = cli.Get("/sni?expected=localhost");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. }
  8481. {
  8482. SSLClient cli("::1", PORT);
  8483. cli.enable_server_certificate_verification(false);
  8484. auto res = cli.Get("/sni?expected=");
  8485. // NOTE: This may fail if the server is listening on IPv4 only
  8486. // (e.g., when localhost resolves to 127.0.0.1 only)
  8487. if (res) {
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. } else {
  8490. EXPECT_EQ(Error::Connection, res.error());
  8491. }
  8492. }
  8493. }
  8494. }
  8495. #endif
  8496. TEST(ClientProblemDetectionTest, ContentProvider) {
  8497. Server svr;
  8498. size_t content_length = 1024 * 1024;
  8499. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8500. res.set_content_provider(
  8501. content_length, "text/plain",
  8502. [&](size_t offset, size_t length, DataSink &sink) {
  8503. auto out_len = std::min(length, static_cast<size_t>(1024));
  8504. std::string out(out_len, '@');
  8505. sink.write(out.data(), out_len);
  8506. return offset < 4096;
  8507. },
  8508. [](bool success) { ASSERT_FALSE(success); });
  8509. });
  8510. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8511. res.set_content_provider(
  8512. 0, "text/plain",
  8513. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8514. EXPECT_TRUE(false);
  8515. return true;
  8516. },
  8517. [](bool success) { ASSERT_FALSE(success); });
  8518. });
  8519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8520. auto se = detail::scope_exit([&] {
  8521. svr.stop();
  8522. listen_thread.join();
  8523. ASSERT_FALSE(svr.is_running());
  8524. });
  8525. svr.wait_until_ready();
  8526. Client cli("localhost", PORT);
  8527. {
  8528. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8529. size_t /*data_length*/) { return false; });
  8530. ASSERT_FALSE(res);
  8531. }
  8532. {
  8533. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8534. size_t /*data_length*/) { return false; });
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. }
  8537. }
  8538. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8539. Server svr;
  8540. svr.set_error_handler([](Request const &, Response &res) -> void {
  8541. res.set_chunked_content_provider(
  8542. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8543. sink.os << "hello";
  8544. sink.os << "world";
  8545. sink.done();
  8546. return true;
  8547. });
  8548. });
  8549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. listen_thread.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. Client cli("localhost", PORT);
  8557. auto res = cli.Get("/");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8560. EXPECT_EQ("helloworld", res->body);
  8561. }
  8562. TEST(LongPollingTest, ClientCloseDetection) {
  8563. Server svr;
  8564. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8565. res.set_chunked_content_provider(
  8566. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8567. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8568. sink.os << "hello";
  8569. auto count = 10;
  8570. while (count > 0 && sink.is_writable()) {
  8571. this_thread::sleep_for(chrono::milliseconds(10));
  8572. count--;
  8573. }
  8574. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8575. return true;
  8576. });
  8577. });
  8578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8579. auto se = detail::scope_exit([&] {
  8580. svr.stop();
  8581. listen_thread.join();
  8582. ASSERT_FALSE(svr.is_running());
  8583. });
  8584. svr.wait_until_ready();
  8585. Client cli("localhost", PORT);
  8586. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8587. EXPECT_EQ("hello", string(data, data_length));
  8588. return false; // close the socket immediately.
  8589. });
  8590. ASSERT_FALSE(res);
  8591. }
  8592. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8593. Server svr;
  8594. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8595. res.set_chunked_content_provider(
  8596. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8597. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8598. sink.os << "hello";
  8599. EXPECT_TRUE(sink.os.good());
  8600. // Wait for the client to close the connection
  8601. auto count = 10;
  8602. while (count > 0 && sink.is_writable()) {
  8603. this_thread::sleep_for(chrono::milliseconds(10));
  8604. count--;
  8605. }
  8606. // After client disconnect, write repeatedly until the socket
  8607. // write actually fails (small writes may be absorbed by the
  8608. // kernel buffer)
  8609. std::string chunk(1024, 'x');
  8610. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8611. sink.os << chunk;
  8612. }
  8613. EXPECT_TRUE(sink.os.fail());
  8614. return true;
  8615. });
  8616. });
  8617. auto port = svr.bind_to_any_port("localhost");
  8618. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8619. auto se = detail::scope_exit([&] {
  8620. svr.stop();
  8621. listen_thread.join();
  8622. ASSERT_FALSE(svr.is_running());
  8623. });
  8624. svr.wait_until_ready();
  8625. Client cli("localhost", port);
  8626. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8627. EXPECT_EQ("hello", string(data, data_length));
  8628. return false; // close the socket immediately.
  8629. });
  8630. ASSERT_FALSE(res);
  8631. }
  8632. TEST(GetWithParametersTest, GetWithParameters) {
  8633. Server svr;
  8634. svr.Get("/", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("world", req.get_param_value("hello"));
  8636. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8637. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8638. });
  8639. svr.Get("/params", [&](const Request &req, Response &) {
  8640. EXPECT_EQ("world", req.get_param_value("hello"));
  8641. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8642. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8643. });
  8644. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8645. EXPECT_EQ("resource-id", req.matches[1]);
  8646. EXPECT_EQ("foo", req.get_param_value("param1"));
  8647. EXPECT_EQ("bar", req.get_param_value("param2"));
  8648. });
  8649. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8650. EXPECT_EQ("user-id", req.path_params.at("id"));
  8651. EXPECT_EQ("foo", req.get_param_value("param1"));
  8652. EXPECT_EQ("bar", req.get_param_value("param2"));
  8653. });
  8654. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. listen_thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. Params params;
  8664. params.emplace("hello", "world");
  8665. params.emplace("hello2", "world2");
  8666. params.emplace("hello3", "world3");
  8667. auto res = cli.Get("/", params, Headers{});
  8668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. {
  8672. Client cli(HOST, PORT);
  8673. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. {
  8678. Client cli(HOST, PORT);
  8679. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. }
  8683. {
  8684. Client cli(HOST, PORT);
  8685. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::OK_200, res->status);
  8688. }
  8689. }
  8690. TEST(GetWithParametersTest, GetWithParameters2) {
  8691. Server svr;
  8692. svr.Get("/", [&](const Request &req, Response &res) {
  8693. auto text = req.get_param_value("hello");
  8694. res.set_content(text, "text/plain");
  8695. });
  8696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8697. auto se = detail::scope_exit([&] {
  8698. svr.stop();
  8699. listen_thread.join();
  8700. ASSERT_FALSE(svr.is_running());
  8701. });
  8702. svr.wait_until_ready();
  8703. Client cli("localhost", PORT);
  8704. Params params;
  8705. params.emplace("hello", "world");
  8706. std::string body;
  8707. auto res = cli.Get("/", params, Headers{},
  8708. [&](const char *data, size_t data_length) {
  8709. body.append(data, data_length);
  8710. return true;
  8711. });
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_EQ("world", body);
  8715. }
  8716. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8717. Server svr;
  8718. svr.Get("/search", [&](const Request &req, Response &res) {
  8719. auto q = req.get_param_value("q");
  8720. res.set_content(q, "text/plain");
  8721. });
  8722. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8723. auto se = detail::scope_exit([&] {
  8724. svr.stop();
  8725. listen_thread.join();
  8726. ASSERT_FALSE(svr.is_running());
  8727. });
  8728. svr.wait_until_ready();
  8729. Client cli("localhost", PORT);
  8730. // Verify that Get(path, params) works without requiring Headers argument
  8731. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8733. EXPECT_EQ(StatusCode::OK_200, res->status);
  8734. EXPECT_EQ("cpp-httplib", res->body);
  8735. }
  8736. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8737. auto host = "httpbingo.org";
  8738. auto path = std::string{"/range/32"};
  8739. #ifdef CPPHTTPLIB_SSL_ENABLED
  8740. SSLClient cli(host);
  8741. #else
  8742. Client cli(host);
  8743. #endif
  8744. cli.set_default_headers({make_range_header({{1, 10}})});
  8745. cli.set_connection_timeout(5);
  8746. {
  8747. auto res = cli.Get(path);
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ("bcdefghijk", res->body);
  8750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8751. }
  8752. {
  8753. auto res = cli.Get(path);
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. EXPECT_EQ("bcdefghijk", res->body);
  8756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8757. }
  8758. }
  8759. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8760. Server svr;
  8761. svr.set_default_headers({{"Hello", "World"}});
  8762. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8763. res.set_content("ok", "text/plain");
  8764. });
  8765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8766. auto se = detail::scope_exit([&] {
  8767. svr.stop();
  8768. listen_thread.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. Client cli("localhost", PORT);
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("ok", res->body);
  8777. EXPECT_EQ("World", res->get_header_value("Hello"));
  8778. }
  8779. #ifdef CPPHTTPLIB_SSL_ENABLED
  8780. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8784. std::this_thread::sleep_for(std::chrono::seconds(2));
  8785. res.set_content("a", "text/plain");
  8786. });
  8787. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8788. res.set_content("b", "text/plain");
  8789. });
  8790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8791. auto se = detail::scope_exit([&] {
  8792. svr.stop();
  8793. listen_thread.join();
  8794. ASSERT_FALSE(svr.is_running());
  8795. });
  8796. svr.wait_until_ready();
  8797. SSLClient cli("localhost", PORT);
  8798. cli.enable_server_certificate_verification(false);
  8799. cli.set_keep_alive(true);
  8800. cli.set_read_timeout(std::chrono::seconds(1));
  8801. auto resa = cli.Get("/a");
  8802. ASSERT_TRUE(!resa);
  8803. EXPECT_EQ(Error::Read, resa.error());
  8804. auto resb = cli.Get("/b");
  8805. ASSERT_TRUE(resb);
  8806. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8807. EXPECT_EQ("b", resb->body);
  8808. }
  8809. #endif
  8810. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8811. protected:
  8812. ServerTestWithAI_PASSIVE()
  8813. : cli_(HOST, PORT)
  8814. #ifdef CPPHTTPLIB_SSL_ENABLED
  8815. ,
  8816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8817. #endif
  8818. {
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. cli_.enable_server_certificate_verification(false);
  8821. #endif
  8822. }
  8823. virtual void SetUp() {
  8824. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8825. res.set_content("Hello World!", "text/plain");
  8826. });
  8827. t_ = thread(
  8828. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8829. svr_.wait_until_ready();
  8830. }
  8831. virtual void TearDown() {
  8832. svr_.stop();
  8833. t_.join();
  8834. }
  8835. #ifdef CPPHTTPLIB_SSL_ENABLED
  8836. SSLClient cli_;
  8837. SSLServer svr_;
  8838. #else
  8839. Client cli_;
  8840. Server svr_;
  8841. #endif
  8842. thread t_;
  8843. };
  8844. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8845. auto res = cli_.Get("/hi");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("Hello World!", res->body);
  8850. }
  8851. class ServerUpDownTest : public ::testing::Test {
  8852. protected:
  8853. ServerUpDownTest() : cli_(HOST, PORT) {}
  8854. virtual void SetUp() {
  8855. t_ = thread([&]() {
  8856. svr_.bind_to_any_port(HOST);
  8857. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8858. ASSERT_TRUE(svr_.listen_after_bind());
  8859. });
  8860. svr_.wait_until_ready();
  8861. }
  8862. virtual void TearDown() {
  8863. svr_.stop();
  8864. t_.join();
  8865. }
  8866. Client cli_;
  8867. Server svr_;
  8868. thread t_;
  8869. };
  8870. TEST_F(ServerUpDownTest, QuickStartStop) {
  8871. // Should not crash, especially when run with
  8872. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8873. }
  8874. class PayloadMaxLengthTest : public ::testing::Test {
  8875. protected:
  8876. PayloadMaxLengthTest()
  8877. : cli_(HOST, PORT)
  8878. #ifdef CPPHTTPLIB_SSL_ENABLED
  8879. ,
  8880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8881. #endif
  8882. {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. cli_.enable_server_certificate_verification(false);
  8885. #endif
  8886. }
  8887. virtual void SetUp() {
  8888. svr_.set_payload_max_length(8);
  8889. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8890. res.set_content("test", "text/plain");
  8891. });
  8892. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8893. svr_.wait_until_ready();
  8894. }
  8895. virtual void TearDown() {
  8896. svr_.stop();
  8897. t_.join();
  8898. }
  8899. #ifdef CPPHTTPLIB_SSL_ENABLED
  8900. SSLClient cli_;
  8901. SSLServer svr_;
  8902. #else
  8903. Client cli_;
  8904. Server svr_;
  8905. #endif
  8906. thread t_;
  8907. };
  8908. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8909. auto res = cli_.Post("/test", "123456789", "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8912. res = cli_.Post("/test", "12345678", "text/plain");
  8913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8917. // Test chunked encoding with payload exceeding the 8-byte limit
  8918. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8919. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8922. }
  8923. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8924. // Test chunked encoding with payload within the 8-byte limit
  8925. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8926. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8931. // Test using send_request to send chunked data exceeding payload limit
  8932. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8933. "Host: " +
  8934. std::string(HOST) + ":" + std::to_string(PORT) +
  8935. "\r\n"
  8936. "Transfer-Encoding: chunked\r\n"
  8937. "Connection: close\r\n"
  8938. "\r\n"
  8939. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8940. "0123456789\r\n"
  8941. "0\r\n" // End chunk
  8942. "\r\n";
  8943. std::string response;
  8944. bool result = send_request(1, chunked_request, &response);
  8945. if (!result) {
  8946. // If send_request fails, it might be because the server closed the
  8947. // connection due to payload limit enforcement, which is acceptable
  8948. SUCCEED()
  8949. << "Server rejected oversized chunked request (connection closed)";
  8950. } else {
  8951. // If we got a response, check if it's an error response or connection was
  8952. // closed early Short response length indicates connection was closed due to
  8953. // payload limit
  8954. if (response.length() <= 10) {
  8955. SUCCEED() << "Server closed connection for oversized chunked request";
  8956. } else {
  8957. // Check for error status codes
  8958. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8959. response.find("Payload Too Large") != std::string::npos ||
  8960. response.find("400") != std::string::npos);
  8961. }
  8962. }
  8963. }
  8964. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8965. // Test request without Content-Length header exceeding payload limit
  8966. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8967. "Host: " +
  8968. std::string(HOST) + ":" +
  8969. std::to_string(PORT) +
  8970. "\r\n"
  8971. "Connection: close\r\n"
  8972. "\r\n";
  8973. // Add payload exceeding the 8-byte limit
  8974. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8975. request_without_content_length += large_payload;
  8976. std::string response;
  8977. bool result = send_request(1, request_without_content_length, &response);
  8978. if (!result) {
  8979. // If send_request fails, server likely closed connection due to payload
  8980. // limit
  8981. SUCCEED() << "Server rejected oversized request without Content-Length "
  8982. "(connection closed)";
  8983. } else {
  8984. // Check if server responded with error or closed connection early
  8985. if (response.length() <= 10) {
  8986. SUCCEED() << "Server closed connection for oversized request without "
  8987. "Content-Length";
  8988. } else {
  8989. // Check for error status codes
  8990. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8991. response.find("Payload Too Large") != std::string::npos ||
  8992. response.find("400") != std::string::npos);
  8993. }
  8994. }
  8995. }
  8996. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8997. // Test request without Content-Length header within payload limit
  8998. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8999. "Host: " +
  9000. std::string(HOST) + ":" +
  9001. std::to_string(PORT) +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. // Add payload within the 8-byte limit
  9006. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9007. request_without_content_length += small_payload;
  9008. std::string response;
  9009. bool result = send_request(1, request_without_content_length, &response);
  9010. // For requests without Content-Length, the server may have different behavior
  9011. // The key is that it should not reject due to payload limit for small
  9012. // payloads
  9013. if (result) {
  9014. // Check for any HTTP response (success or error, but not connection closed)
  9015. if (response.length() > 10) {
  9016. SUCCEED()
  9017. << "Server processed request without Content-Length within limit";
  9018. } else {
  9019. // Short response might indicate connection closed, which is acceptable
  9020. SUCCEED() << "Server closed connection for request without "
  9021. "Content-Length (acceptable behavior)";
  9022. }
  9023. } else {
  9024. // Connection failure might be due to protocol requirements
  9025. SUCCEED() << "Connection issue with request without Content-Length "
  9026. "(environment-specific)";
  9027. }
  9028. }
  9029. class LargePayloadMaxLengthTest : public ::testing::Test {
  9030. protected:
  9031. LargePayloadMaxLengthTest()
  9032. : cli_(HOST, PORT)
  9033. #ifdef CPPHTTPLIB_SSL_ENABLED
  9034. ,
  9035. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9036. #endif
  9037. {
  9038. #ifdef CPPHTTPLIB_SSL_ENABLED
  9039. cli_.enable_server_certificate_verification(false);
  9040. #endif
  9041. }
  9042. virtual void SetUp() {
  9043. // Set 10MB payload limit
  9044. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9045. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9047. res.set_content("Large payload test", "text/plain");
  9048. });
  9049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9050. svr_.wait_until_ready();
  9051. }
  9052. virtual void TearDown() {
  9053. svr_.stop();
  9054. t_.join();
  9055. }
  9056. #ifdef CPPHTTPLIB_SSL_ENABLED
  9057. SSLClient cli_;
  9058. SSLServer svr_;
  9059. #else
  9060. Client cli_;
  9061. Server svr_;
  9062. #endif
  9063. thread t_;
  9064. };
  9065. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9066. // Test chunked encoding with payload within 10MB limit
  9067. std::string medium_payload(5 * 1024 * 1024,
  9068. 'A'); // 5MB payload, within 10MB limit
  9069. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. }
  9073. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9074. // Test chunked encoding with payload exceeding 10MB limit
  9075. std::string large_payload(12 * 1024 * 1024,
  9076. 'B'); // 12MB payload, exceeds 10MB limit
  9077. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9078. // Server may either return 413 or close the connection
  9079. if (res) {
  9080. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9081. } else {
  9082. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9083. }
  9084. }
  9085. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9086. // Test request without Content-Length header within 10MB limit
  9087. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9088. "Host: " +
  9089. std::string(HOST) + ":" +
  9090. std::to_string(PORT) +
  9091. "\r\n"
  9092. "Connection: close\r\n"
  9093. "\r\n";
  9094. // Add 1MB payload (within 10MB limit)
  9095. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9096. request_without_content_length += medium_payload;
  9097. std::string response;
  9098. bool result = send_request(5, request_without_content_length, &response);
  9099. if (result) {
  9100. // Should get a proper HTTP response for payloads within limit
  9101. if (response.length() > 10) {
  9102. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9103. "10MB limit";
  9104. } else {
  9105. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9106. "Content-Length)";
  9107. }
  9108. } else {
  9109. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9110. }
  9111. }
  9112. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9113. // Test request without Content-Length header exceeding 10MB limit
  9114. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9115. "Host: " +
  9116. std::string(HOST) + ":" +
  9117. std::to_string(PORT) +
  9118. "\r\n"
  9119. "Connection: close\r\n"
  9120. "\r\n";
  9121. // Add 12MB payload (exceeds 10MB limit)
  9122. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9123. request_without_content_length += large_payload;
  9124. std::string response;
  9125. bool result = send_request(10, request_without_content_length, &response);
  9126. if (!result) {
  9127. // Server should close connection due to payload limit
  9128. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9129. "(connection closed)";
  9130. } else {
  9131. // Check for error response
  9132. if (response.length() <= 10) {
  9133. SUCCEED()
  9134. << "Server closed connection for 12MB request exceeding 10MB limit";
  9135. } else {
  9136. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9137. response.find("Payload Too Large") != std::string::npos ||
  9138. response.find("400") != std::string::npos);
  9139. }
  9140. }
  9141. }
  9142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9143. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9144. // path.
  9145. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9146. Server svr;
  9147. const size_t LIMIT = 64 * 1024; // 64KB
  9148. svr.set_payload_max_length(LIMIT);
  9149. size_t total = 0;
  9150. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9151. const ContentReader &content_reader) {
  9152. content_reader([&](const char * /*data*/, size_t len) {
  9153. total += len;
  9154. return true;
  9155. });
  9156. res.status = 200;
  9157. res.set_content("stream_ok", "text/plain");
  9158. });
  9159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9160. auto se = detail::scope_exit([&] {
  9161. svr.stop();
  9162. thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. });
  9165. svr.wait_until_ready();
  9166. // Prepare 256KB raw data and gzip-compress it
  9167. std::string raw(256 * 1024, 'A');
  9168. std::string gz;
  9169. {
  9170. z_stream zs{};
  9171. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9172. Z_DEFAULT_STRATEGY);
  9173. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9174. zs.avail_in = static_cast<uInt>(raw.size());
  9175. char outbuf[4096];
  9176. int ret;
  9177. do {
  9178. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9179. zs.avail_out = sizeof(outbuf);
  9180. ret = deflate(&zs, Z_FINISH);
  9181. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9182. } while (ret != Z_STREAM_END);
  9183. deflateEnd(&zs);
  9184. }
  9185. Client cli(HOST, PORT);
  9186. cli.set_connection_timeout(std::chrono::seconds(5));
  9187. Headers headers = {{"Content-Encoding", "gzip"}};
  9188. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9189. "application/octet-stream");
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. // Server must reject oversized decompressed payloads with 413.
  9192. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9193. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9194. EXPECT_LE(total, LIMIT);
  9195. }
  9196. #ifndef CPPHTTPLIB_SSL_ENABLED
  9197. // For a request with neither Content-Length nor Transfer-Encoding, the
  9198. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9199. // compressed wire bytes straight to the ContentReader without ever routing
  9200. // them through the decompressor, so payload_max_length_ only bounded the
  9201. // compressed size on the wire, not the decompressed size.
  9202. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9203. Server svr;
  9204. const size_t LIMIT = 64 * 1024; // 64KB
  9205. svr.set_payload_max_length(LIMIT);
  9206. size_t total = 0;
  9207. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9208. const ContentReader &content_reader) {
  9209. content_reader([&](const char * /*data*/, size_t len) {
  9210. total += len;
  9211. return true;
  9212. });
  9213. res.status = 200;
  9214. res.set_content("stream_ok", "text/plain");
  9215. });
  9216. auto port = svr.bind_to_any_port(HOST);
  9217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9218. auto se = detail::scope_exit([&] {
  9219. svr.stop();
  9220. thread.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9225. // StreamingGzipDecompression test above.
  9226. std::string raw(256 * 1024, 'A');
  9227. std::string gz;
  9228. {
  9229. httplib::detail::gzip_compressor compressor;
  9230. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9231. [&](const char *chunk, size_t len) {
  9232. gz.append(chunk, len);
  9233. return true;
  9234. });
  9235. ASSERT_TRUE(result);
  9236. }
  9237. // Send the gzip body over raw TCP with neither Content-Length nor
  9238. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9239. // kicks in.
  9240. std::string req = "POST /stream HTTP/1.1\r\n"
  9241. "Host: " +
  9242. std::string(HOST) + ":" + std::to_string(port) +
  9243. "\r\n"
  9244. "Content-Encoding: gzip\r\n"
  9245. "Connection: close\r\n"
  9246. "\r\n" +
  9247. gz;
  9248. std::string response;
  9249. ASSERT_TRUE(send_request(5, req, &response, port));
  9250. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9251. EXPECT_LE(total, LIMIT);
  9252. }
  9253. #endif
  9254. #endif
  9255. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9256. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9257. // the payload must be passed through untouched instead of being rejected.
  9258. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9259. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9260. Server svr;
  9261. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9262. res.set_content(body, "image/jpeg");
  9263. res.set_header("Content-Encoding", "UTF-8");
  9264. });
  9265. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9266. res.set_content(body, "image/jpeg");
  9267. res.set_header("Content-Encoding", "identity");
  9268. });
  9269. svr.Post("/echo", [](const Request &req, Response &res) {
  9270. res.set_content(req.body, "image/jpeg");
  9271. });
  9272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9273. auto se = detail::scope_exit([&] {
  9274. svr.stop();
  9275. t.join();
  9276. ASSERT_FALSE(svr.is_running());
  9277. });
  9278. svr.wait_until_ready();
  9279. Client cli(HOST, PORT);
  9280. {
  9281. auto res = cli.Get("/image");
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ(body, res->body);
  9285. }
  9286. {
  9287. auto res = cli.Get("/identity");
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_EQ(StatusCode::OK_200, res->status);
  9290. EXPECT_EQ(body, res->body);
  9291. }
  9292. {
  9293. // The same applies to a request body reaching the server.
  9294. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9295. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(StatusCode::OK_200, res->status);
  9298. EXPECT_EQ(body, res->body);
  9299. }
  9300. }
  9301. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9302. // gzip-encoded response even when the build has no zlib support.
  9303. static const char GZIPPED_HELLO_WORLD[] = {
  9304. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9305. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9306. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9307. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9308. // A content coding cpp-httplib recognizes but was not built with must be
  9309. // reported as such. Handing the still-compressed payload back to the caller
  9310. // would silently corrupt it.
  9311. // A content coding is a whole token, not something the field value merely
  9312. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9313. // as "fibre" look like Brotli, and turned a multi-coding value like
  9314. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9315. // it was never meant to see.
  9316. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9317. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9318. Server svr;
  9319. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9320. res.set_content(body, "image/jpeg");
  9321. res.set_header("Content-Encoding", "fibre");
  9322. });
  9323. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9324. res.set_content(body, "image/jpeg");
  9325. res.set_header("Content-Encoding", "gzip, br");
  9326. });
  9327. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9328. res.set_content(body, "image/jpeg");
  9329. res.set_header("Content-Encoding", "x-zstd-ish");
  9330. });
  9331. auto port = svr.bind_to_any_port(HOST);
  9332. thread t = thread([&]() { svr.listen_after_bind(); });
  9333. auto se = detail::scope_exit([&] {
  9334. svr.stop();
  9335. t.join();
  9336. ASSERT_FALSE(svr.is_running());
  9337. });
  9338. svr.wait_until_ready();
  9339. Client cli(HOST, port);
  9340. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9341. auto res = cli.Get(path);
  9342. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9343. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9344. // Not a coding we recognize, so the payload comes back untouched
  9345. EXPECT_EQ(body, res->body) << path;
  9346. }
  9347. }
  9348. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9349. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9350. Server svr;
  9351. // "image/jpeg" keeps the server from applying a content coding of its own,
  9352. // so the hand-crafted Content-Encoding below survives.
  9353. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9354. res.set_content(gzipped, "image/jpeg");
  9355. res.set_header("Content-Encoding", "gzip");
  9356. });
  9357. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9358. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9359. res.set_content(gzipped, "image/jpeg");
  9360. res.set_header("Content-Encoding", "GZIP");
  9361. });
  9362. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9363. auto se = detail::scope_exit([&] {
  9364. svr.stop();
  9365. t.join();
  9366. ASSERT_FALSE(svr.is_running());
  9367. });
  9368. svr.wait_until_ready();
  9369. Client cli(HOST, PORT);
  9370. {
  9371. auto res = cli.Get("/gzipped");
  9372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ("Hello World!", res->body);
  9375. #else
  9376. ASSERT_FALSE(res);
  9377. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9378. #endif
  9379. }
  9380. {
  9381. // open_stream() must behave the same way.
  9382. auto handle = cli.open_stream("GET", "/gzipped");
  9383. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9384. ASSERT_TRUE(handle.is_valid());
  9385. std::string received;
  9386. char buf[256];
  9387. ssize_t n;
  9388. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9389. received.append(buf, static_cast<size_t>(n));
  9390. }
  9391. EXPECT_EQ("Hello World!", received);
  9392. #else
  9393. EXPECT_FALSE(handle.is_valid());
  9394. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9395. #endif
  9396. }
  9397. {
  9398. // A differently-cased coding must not be mistaken for an unknown one, or
  9399. // the body would be handed back still compressed.
  9400. auto res = cli.Get("/gzipped-uppercase");
  9401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9403. EXPECT_EQ("Hello World!", res->body);
  9404. #else
  9405. ASSERT_FALSE(res);
  9406. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9407. #endif
  9408. }
  9409. }
  9410. // Regression test for DoS vulnerability: a malicious server sending a response
  9411. // without Content-Length header must not cause unbounded memory consumption on
  9412. // the client side. The client should stop reading after a reasonable limit,
  9413. // similar to the server-side set_payload_max_length protection.
  9414. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9415. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9416. #ifndef _WIN32
  9417. signal(SIGPIPE, SIG_IGN);
  9418. #endif
  9419. auto server_thread = std::thread([] {
  9420. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9421. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9422. default_socket_options(srv);
  9423. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9424. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9425. sockaddr_in addr{};
  9426. addr.sin_family = AF_INET;
  9427. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9428. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9429. int opt = 1;
  9430. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9431. #ifdef _WIN32
  9432. reinterpret_cast<const char *>(&opt),
  9433. #else
  9434. &opt,
  9435. #endif
  9436. sizeof(opt));
  9437. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9438. ::listen(srv, 1);
  9439. sockaddr_in cli_addr{};
  9440. socklen_t cli_len = sizeof(cli_addr);
  9441. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9442. if (cli != INVALID_SOCKET) {
  9443. char buf[4096];
  9444. ::recv(cli, buf, sizeof(buf), 0);
  9445. // Malicious response: no Content-Length, no chunked encoding
  9446. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9447. "Connection: close\r\n"
  9448. "\r\n";
  9449. ::send(cli,
  9450. #ifdef _WIN32
  9451. static_cast<const char *>(response_header.c_str()),
  9452. static_cast<int>(response_header.size()),
  9453. #else
  9454. response_header.c_str(), response_header.size(),
  9455. #endif
  9456. 0);
  9457. // Send 10MB of data
  9458. std::string chunk(64 * 1024, 'A');
  9459. size_t total_sent = 0;
  9460. while (total_sent < MALICIOUS_DATA_SIZE) {
  9461. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9462. auto sent = ::send(cli,
  9463. #ifdef _WIN32
  9464. static_cast<const char *>(chunk.c_str()),
  9465. static_cast<int>(to_send),
  9466. #else
  9467. chunk.c_str(), to_send,
  9468. #endif
  9469. 0);
  9470. if (sent <= 0) break;
  9471. total_sent += static_cast<size_t>(sent);
  9472. }
  9473. detail::close_socket(cli);
  9474. }
  9475. detail::close_socket(srv);
  9476. });
  9477. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9478. size_t total_read = 0;
  9479. {
  9480. Client cli("127.0.0.1", PORT + 2);
  9481. cli.set_read_timeout(5, 0);
  9482. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9483. auto stream = cli.open_stream("GET", "/malicious");
  9484. ASSERT_TRUE(stream.is_valid());
  9485. char buffer[64 * 1024];
  9486. ssize_t n;
  9487. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9488. total_read += static_cast<size_t>(n);
  9489. }
  9490. } // StreamHandle and Client destroyed here, closing the socket
  9491. server_thread.join();
  9492. // With set_payload_max_length, the client must stop reading before consuming
  9493. // all 10MB. The read loop should be cut off at or near the configured limit.
  9494. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9495. << "Client read " << total_read << " bytes, exceeding the configured "
  9496. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9497. }
  9498. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9499. // the entire response body without truncation.
  9500. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9501. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9502. #ifndef _WIN32
  9503. signal(SIGPIPE, SIG_IGN);
  9504. #endif
  9505. auto server_thread = std::thread([] {
  9506. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9507. default_socket_options(srv);
  9508. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9509. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9510. sockaddr_in addr{};
  9511. addr.sin_family = AF_INET;
  9512. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9513. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9514. int opt = 1;
  9515. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9516. #ifdef _WIN32
  9517. reinterpret_cast<const char *>(&opt),
  9518. #else
  9519. &opt,
  9520. #endif
  9521. sizeof(opt));
  9522. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9523. ::listen(srv, 1);
  9524. sockaddr_in cli_addr{};
  9525. socklen_t cli_len = sizeof(cli_addr);
  9526. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9527. if (cli != INVALID_SOCKET) {
  9528. char buf[4096];
  9529. ::recv(cli, buf, sizeof(buf), 0);
  9530. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9531. "Connection: close\r\n"
  9532. "\r\n";
  9533. ::send(cli,
  9534. #ifdef _WIN32
  9535. static_cast<const char *>(response_header.c_str()),
  9536. static_cast<int>(response_header.size()),
  9537. #else
  9538. response_header.c_str(), response_header.size(),
  9539. #endif
  9540. 0);
  9541. std::string chunk(64 * 1024, 'A');
  9542. size_t total_sent = 0;
  9543. while (total_sent < DATA_SIZE) {
  9544. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9545. auto sent = ::send(cli,
  9546. #ifdef _WIN32
  9547. static_cast<const char *>(chunk.c_str()),
  9548. static_cast<int>(to_send),
  9549. #else
  9550. chunk.c_str(), to_send,
  9551. #endif
  9552. 0);
  9553. if (sent <= 0) break;
  9554. total_sent += static_cast<size_t>(sent);
  9555. }
  9556. #ifdef _WIN32
  9557. ::shutdown(cli, SD_SEND);
  9558. #else
  9559. ::shutdown(cli, SHUT_WR);
  9560. #endif
  9561. // Drain until the client closes its end, ensuring all data is delivered
  9562. char drain[1024];
  9563. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9564. detail::close_socket(cli);
  9565. }
  9566. detail::close_socket(srv);
  9567. });
  9568. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9569. size_t total_read = 0;
  9570. {
  9571. Client cli("127.0.0.1", PORT + 2);
  9572. cli.set_read_timeout(5, 0);
  9573. cli.set_payload_max_length(0); // 0 means no limit
  9574. auto stream = cli.open_stream("GET", "/data");
  9575. ASSERT_TRUE(stream.is_valid());
  9576. char buffer[64 * 1024];
  9577. ssize_t n;
  9578. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9579. total_read += static_cast<size_t>(n);
  9580. }
  9581. }
  9582. server_thread.join();
  9583. EXPECT_EQ(total_read, DATA_SIZE)
  9584. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9585. << " bytes without truncation, but only read " << total_read << " bytes.";
  9586. }
  9587. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9588. // enormous Content-Length must not cause the client to pre-allocate a huge
  9589. // response body buffer. The reservation is capped at payload_max_length_, and
  9590. // the read itself fails when the body exceeds the limit.
  9591. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9592. #ifndef _WIN32
  9593. signal(SIGPIPE, SIG_IGN);
  9594. #endif
  9595. auto server_thread = std::thread([] {
  9596. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9597. default_socket_options(srv);
  9598. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9599. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9600. sockaddr_in addr{};
  9601. addr.sin_family = AF_INET;
  9602. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9603. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9604. int opt = 1;
  9605. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9606. #ifdef _WIN32
  9607. reinterpret_cast<const char *>(&opt),
  9608. #else
  9609. &opt,
  9610. #endif
  9611. sizeof(opt));
  9612. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9613. ::listen(srv, 1);
  9614. sockaddr_in cli_addr{};
  9615. socklen_t cli_len = sizeof(cli_addr);
  9616. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9617. if (cli != INVALID_SOCKET) {
  9618. char buf[4096];
  9619. ::recv(cli, buf, sizeof(buf), 0);
  9620. // Malicious response: claim a 20GB body but send only a tiny payload.
  9621. std::string response = "HTTP/1.1 200 OK\r\n"
  9622. "Content-Length: 20000000000\r\n"
  9623. "\r\n"
  9624. "abc";
  9625. ::send(cli,
  9626. #ifdef _WIN32
  9627. static_cast<const char *>(response.c_str()),
  9628. static_cast<int>(response.size()),
  9629. #else
  9630. response.c_str(), response.size(),
  9631. #endif
  9632. 0);
  9633. detail::close_socket(cli);
  9634. }
  9635. detail::close_socket(srv);
  9636. });
  9637. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9638. {
  9639. Client cli("127.0.0.1", PORT + 2);
  9640. cli.set_read_timeout(5, 0);
  9641. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9642. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9643. // (server claims more bytes than payload_max_length permits), but it must
  9644. // not exhaust memory before getting there.
  9645. auto res = cli.Get("/malicious");
  9646. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9647. }
  9648. server_thread.join();
  9649. }
  9650. // Verify that content_receiver bypasses the default payload_max_length,
  9651. // allowing streaming downloads larger than 100MB without requiring an explicit
  9652. // set_payload_max_length call.
  9653. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9654. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9655. #ifndef _WIN32
  9656. signal(SIGPIPE, SIG_IGN);
  9657. #endif
  9658. auto server_thread = std::thread([] {
  9659. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9660. default_socket_options(srv);
  9661. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9662. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9663. sockaddr_in addr{};
  9664. addr.sin_family = AF_INET;
  9665. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9666. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9667. int opt = 1;
  9668. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9669. #ifdef _WIN32
  9670. reinterpret_cast<const char *>(&opt),
  9671. #else
  9672. &opt,
  9673. #endif
  9674. sizeof(opt));
  9675. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9676. ::listen(srv, 1);
  9677. sockaddr_in cli_addr{};
  9678. socklen_t cli_len = sizeof(cli_addr);
  9679. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9680. if (cli != INVALID_SOCKET) {
  9681. char buf[4096];
  9682. ::recv(cli, buf, sizeof(buf), 0);
  9683. // Response with Content-Length larger than default 100MB limit
  9684. auto content_length = std::to_string(DATA_SIZE);
  9685. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9686. "Content-Length: " +
  9687. content_length +
  9688. "\r\n"
  9689. "Connection: close\r\n"
  9690. "\r\n";
  9691. ::send(cli,
  9692. #ifdef _WIN32
  9693. static_cast<const char *>(response_header.c_str()),
  9694. static_cast<int>(response_header.size()),
  9695. #else
  9696. response_header.c_str(), response_header.size(),
  9697. #endif
  9698. 0);
  9699. std::string chunk(64 * 1024, 'A');
  9700. size_t total_sent = 0;
  9701. while (total_sent < DATA_SIZE) {
  9702. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9703. auto sent = ::send(cli,
  9704. #ifdef _WIN32
  9705. static_cast<const char *>(chunk.c_str()),
  9706. static_cast<int>(to_send),
  9707. #else
  9708. chunk.c_str(), to_send,
  9709. #endif
  9710. 0);
  9711. if (sent <= 0) break;
  9712. total_sent += static_cast<size_t>(sent);
  9713. }
  9714. detail::close_socket(cli);
  9715. }
  9716. detail::close_socket(srv);
  9717. });
  9718. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9719. size_t total_received = 0;
  9720. {
  9721. Client cli("127.0.0.1", PORT + 2);
  9722. cli.set_read_timeout(10, 0);
  9723. // Do NOT call set_payload_max_length — use the default 100MB limit
  9724. auto res =
  9725. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9726. total_received += data_length;
  9727. return true;
  9728. });
  9729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9730. EXPECT_EQ(StatusCode::OK_200, res->status);
  9731. }
  9732. server_thread.join();
  9733. EXPECT_EQ(total_received, DATA_SIZE)
  9734. << "With content_receiver, the client should read all " << DATA_SIZE
  9735. << " bytes despite the default 100MB payload_max_length, but only read "
  9736. << total_received << " bytes.";
  9737. }
  9738. // Verify that an explicit set_payload_max_length smaller than the response is
  9739. // enforced even when a content_receiver is used.
  9740. TEST(ClientVulnerabilityTest,
  9741. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9742. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9743. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9744. #ifndef _WIN32
  9745. signal(SIGPIPE, SIG_IGN);
  9746. #endif
  9747. auto server_thread = std::thread([] {
  9748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9749. default_socket_options(srv);
  9750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9752. sockaddr_in addr{};
  9753. addr.sin_family = AF_INET;
  9754. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9756. int opt = 1;
  9757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9758. #ifdef _WIN32
  9759. reinterpret_cast<const char *>(&opt),
  9760. #else
  9761. &opt,
  9762. #endif
  9763. sizeof(opt));
  9764. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9765. ::listen(srv, 1);
  9766. sockaddr_in cli_addr{};
  9767. socklen_t cli_len = sizeof(cli_addr);
  9768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9769. if (cli != INVALID_SOCKET) {
  9770. char buf[4096];
  9771. ::recv(cli, buf, sizeof(buf), 0);
  9772. auto content_length = std::to_string(DATA_SIZE);
  9773. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9774. "Content-Length: " +
  9775. content_length +
  9776. "\r\n"
  9777. "Connection: close\r\n"
  9778. "\r\n";
  9779. ::send(cli,
  9780. #ifdef _WIN32
  9781. static_cast<const char *>(response_header.c_str()),
  9782. static_cast<int>(response_header.size()),
  9783. #else
  9784. response_header.c_str(), response_header.size(),
  9785. #endif
  9786. 0);
  9787. std::string chunk(64 * 1024, 'A');
  9788. size_t total_sent = 0;
  9789. while (total_sent < DATA_SIZE) {
  9790. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9791. auto sent = ::send(cli,
  9792. #ifdef _WIN32
  9793. static_cast<const char *>(chunk.c_str()),
  9794. static_cast<int>(to_send),
  9795. #else
  9796. chunk.c_str(), to_send,
  9797. #endif
  9798. 0);
  9799. if (sent <= 0) break;
  9800. total_sent += static_cast<size_t>(sent);
  9801. }
  9802. detail::close_socket(cli);
  9803. }
  9804. detail::close_socket(srv);
  9805. });
  9806. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9807. size_t total_received = 0;
  9808. {
  9809. Client cli("127.0.0.1", PORT + 2);
  9810. cli.set_read_timeout(10, 0);
  9811. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9812. auto res =
  9813. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9814. total_received += data_length;
  9815. return true;
  9816. });
  9817. // Should fail because 200MB exceeds the explicit 150MB limit
  9818. EXPECT_FALSE(res);
  9819. }
  9820. server_thread.join();
  9821. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9822. << "Client with content_receiver should respect the explicit "
  9823. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9824. << total_received << " bytes.";
  9825. }
  9826. // Verify that an explicit set_payload_max_length larger than the response
  9827. // allows the content_receiver to read all data successfully.
  9828. TEST(ClientVulnerabilityTest,
  9829. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9830. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9831. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9832. #ifndef _WIN32
  9833. signal(SIGPIPE, SIG_IGN);
  9834. #endif
  9835. auto server_thread = std::thread([] {
  9836. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9837. default_socket_options(srv);
  9838. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9840. sockaddr_in addr{};
  9841. addr.sin_family = AF_INET;
  9842. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9843. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9844. int opt = 1;
  9845. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9846. #ifdef _WIN32
  9847. reinterpret_cast<const char *>(&opt),
  9848. #else
  9849. &opt,
  9850. #endif
  9851. sizeof(opt));
  9852. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9853. ::listen(srv, 1);
  9854. sockaddr_in cli_addr{};
  9855. socklen_t cli_len = sizeof(cli_addr);
  9856. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9857. if (cli != INVALID_SOCKET) {
  9858. char buf[4096];
  9859. ::recv(cli, buf, sizeof(buf), 0);
  9860. auto content_length = std::to_string(DATA_SIZE);
  9861. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9862. "Content-Length: " +
  9863. content_length +
  9864. "\r\n"
  9865. "Connection: close\r\n"
  9866. "\r\n";
  9867. ::send(cli,
  9868. #ifdef _WIN32
  9869. static_cast<const char *>(response_header.c_str()),
  9870. static_cast<int>(response_header.size()),
  9871. #else
  9872. response_header.c_str(), response_header.size(),
  9873. #endif
  9874. 0);
  9875. std::string chunk(64 * 1024, 'A');
  9876. size_t total_sent = 0;
  9877. while (total_sent < DATA_SIZE) {
  9878. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9879. auto sent = ::send(cli,
  9880. #ifdef _WIN32
  9881. static_cast<const char *>(chunk.c_str()),
  9882. static_cast<int>(to_send),
  9883. #else
  9884. chunk.c_str(), to_send,
  9885. #endif
  9886. 0);
  9887. if (sent <= 0) break;
  9888. total_sent += static_cast<size_t>(sent);
  9889. }
  9890. #ifdef _WIN32
  9891. ::shutdown(cli, SD_SEND);
  9892. #else
  9893. ::shutdown(cli, SHUT_WR);
  9894. #endif
  9895. char drain[1024];
  9896. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9897. detail::close_socket(cli);
  9898. }
  9899. detail::close_socket(srv);
  9900. });
  9901. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9902. size_t total_received = 0;
  9903. {
  9904. Client cli("127.0.0.1", PORT + 2);
  9905. cli.set_read_timeout(10, 0);
  9906. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9907. auto res =
  9908. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9909. total_received += data_length;
  9910. return true;
  9911. });
  9912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9913. EXPECT_EQ(StatusCode::OK_200, res->status);
  9914. }
  9915. server_thread.join();
  9916. EXPECT_EQ(total_received, DATA_SIZE)
  9917. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9918. << " bytes (larger than " << DATA_SIZE
  9919. << " bytes response), content_receiver should read all data, but only "
  9920. "read "
  9921. << total_received << " bytes.";
  9922. }
  9923. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9924. // Regression test for "zip bomb" attack on the client side: a malicious server
  9925. // sends a small gzip-compressed response that decompresses to a huge payload.
  9926. // The client must enforce payload_max_length on the decompressed size.
  9927. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9928. constexpr size_t DECOMPRESSED_SIZE =
  9929. 10 * 1024 * 1024; // 10MB after decompression
  9930. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9931. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9932. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9933. std::string compressed;
  9934. {
  9935. httplib::detail::gzip_compressor compressor;
  9936. bool ok =
  9937. compressor.compress(uncompressed.data(), uncompressed.size(),
  9938. /*last=*/true, [&](const char *buf, size_t len) {
  9939. compressed.append(buf, len);
  9940. return true;
  9941. });
  9942. ASSERT_TRUE(ok);
  9943. }
  9944. // Sanity: compressed data should be much smaller than the decompressed size
  9945. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9946. #ifndef _WIN32
  9947. signal(SIGPIPE, SIG_IGN);
  9948. #endif
  9949. // Set up the listening socket in the main thread so the server is guaranteed
  9950. // to be ready before the client connects (eliminates race condition).
  9951. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9952. default_socket_options(srv);
  9953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9955. sockaddr_in addr{};
  9956. addr.sin_family = AF_INET;
  9957. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9958. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9959. int opt = 1;
  9960. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9961. #ifdef _WIN32
  9962. reinterpret_cast<const char *>(&opt),
  9963. #else
  9964. &opt,
  9965. #endif
  9966. sizeof(opt));
  9967. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9968. ASSERT_EQ(0, ::listen(srv, 1));
  9969. auto server_thread = std::thread([&compressed, srv] {
  9970. sockaddr_in cli_addr{};
  9971. socklen_t cli_len = sizeof(cli_addr);
  9972. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9973. if (cli != INVALID_SOCKET) {
  9974. // Read the full HTTP request (until \r\n\r\n)
  9975. char buf[4096];
  9976. size_t total = 0;
  9977. while (total < sizeof(buf)) {
  9978. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9979. if (n <= 0) break;
  9980. total += static_cast<size_t>(n);
  9981. // Check for end of headers
  9982. if (total >= 4) {
  9983. std::string req(buf, total);
  9984. if (req.find("\r\n\r\n") != std::string::npos) break;
  9985. }
  9986. }
  9987. // Malicious response: gzip-compressed body, no Content-Length
  9988. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9989. "Content-Encoding: gzip\r\n"
  9990. "Connection: close\r\n"
  9991. "\r\n";
  9992. ::send(cli,
  9993. #ifdef _WIN32
  9994. static_cast<const char *>(response_header.c_str()),
  9995. static_cast<int>(response_header.size()),
  9996. #else
  9997. response_header.c_str(), response_header.size(),
  9998. #endif
  9999. 0);
  10000. // Send the compressed payload (small on the wire, huge when decompressed)
  10001. size_t total_sent = 0;
  10002. while (total_sent < compressed.size()) {
  10003. auto to_send = std::min(compressed.size() - total_sent,
  10004. static_cast<size_t>(64 * 1024));
  10005. auto sent =
  10006. ::send(cli,
  10007. #ifdef _WIN32
  10008. static_cast<const char *>(compressed.c_str() + total_sent),
  10009. static_cast<int>(to_send),
  10010. #else
  10011. compressed.c_str() + total_sent, to_send,
  10012. #endif
  10013. 0);
  10014. if (sent <= 0) break;
  10015. total_sent += static_cast<size_t>(sent);
  10016. }
  10017. detail::close_socket(cli);
  10018. }
  10019. });
  10020. auto se = detail::scope_exit([&] {
  10021. detail::close_socket(srv);
  10022. server_thread.join();
  10023. });
  10024. size_t total_decompressed = 0;
  10025. {
  10026. Client cli("127.0.0.1", PORT + 3);
  10027. cli.set_read_timeout(5, 0);
  10028. cli.set_decompress(true);
  10029. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10030. auto stream = cli.open_stream("GET", "/zipbomb");
  10031. ASSERT_TRUE(stream.is_valid());
  10032. char buffer[64 * 1024];
  10033. ssize_t n;
  10034. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10035. total_decompressed += static_cast<size_t>(n);
  10036. }
  10037. }
  10038. // The decompressed size must be capped by payload_max_length. Without
  10039. // protection, the client would decompress the full 10MB from a tiny
  10040. // compressed payload, enabling a zip bomb DoS attack.
  10041. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10042. << "Client decompressed " << total_decompressed
  10043. << " bytes from a gzip response. The decompressed size should be "
  10044. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10045. }
  10046. #endif
  10047. TEST(HostAndPortPropertiesTest, NoSSL) {
  10048. httplib::Client cli("www.google.com", 1234);
  10049. ASSERT_EQ("www.google.com", cli.host());
  10050. ASSERT_EQ(1234, cli.port());
  10051. }
  10052. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10053. httplib::Client cli("www.google.com:1234");
  10054. ASSERT_EQ("www.google.com", cli.host());
  10055. ASSERT_EQ(1234, cli.port());
  10056. }
  10057. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10058. // Port number that overflows int — should not crash, client becomes invalid
  10059. httplib::Client cli("http://www.google.com:99999999999999999999");
  10060. ASSERT_FALSE(cli.is_valid());
  10061. }
  10062. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10063. // Port 99999 exceeds valid range (1-65535) — should not crash
  10064. httplib::Client cli("http://www.google.com:99999");
  10065. ASSERT_FALSE(cli.is_valid());
  10066. }
  10067. #ifdef CPPHTTPLIB_SSL_ENABLED
  10068. TEST(HostAndPortPropertiesTest, SSL) {
  10069. httplib::SSLClient cli("www.google.com");
  10070. ASSERT_EQ("www.google.com", cli.host());
  10071. ASSERT_EQ(443, cli.port());
  10072. }
  10073. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10074. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10075. std::string cert;
  10076. read_file(CA_CERT_FILE, cert);
  10077. httplib::SSLClient httplib_client("www.google.com");
  10078. // Load CA store first time
  10079. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10080. // Load CA store second time (update)
  10081. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10082. // Verify client is still valid and can make connections
  10083. httplib_client.enable_server_certificate_verification(true);
  10084. auto res = httplib_client.Get("/");
  10085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10086. // Google may return 200 or 301 depending on various factors
  10087. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10088. res->status == StatusCode::MovedPermanently_301);
  10089. }
  10090. TEST(SSLClientTest, ServerNameIndication_Online) {
  10091. auto host = "httpbingo.org";
  10092. auto path = std::string{"/get"};
  10093. SSLClient cli(host, 443);
  10094. auto res = cli.Get(path);
  10095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10096. ASSERT_EQ(StatusCode::OK_200, res->status);
  10097. }
  10098. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10099. // Use a site that will cause SSL verification failure due to self-signed cert
  10100. SSLClient cli("self-signed.badssl.com", 443);
  10101. cli.enable_server_certificate_verification(true);
  10102. auto res = cli.Get("/");
  10103. ASSERT_TRUE(!res);
  10104. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10105. // Verify backend error is captured for SSLServerVerification
  10106. // This occurs when certificate verification fails
  10107. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10108. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10109. EXPECT_NE(0UL, res.ssl_backend_error());
  10110. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10111. // For OpenSSL, ssl_error is 0 for verification errors
  10112. EXPECT_EQ(0, res.ssl_error());
  10113. #if !defined(_WIN32) || \
  10114. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10115. // On non-Windows or when Windows Schannel is disabled, the error comes
  10116. // from OpenSSL's verification
  10117. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10118. res.ssl_backend_error());
  10119. #endif
  10120. #endif
  10121. }
  10122. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10123. // Use a site where hostname doesn't match the certificate
  10124. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10125. SSLClient cli("wrong.host.badssl.com", 443);
  10126. cli.enable_server_certificate_verification(true);
  10127. cli.enable_server_hostname_verification(true);
  10128. auto res = cli.Get("/");
  10129. ASSERT_TRUE(!res);
  10130. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10131. // Verify backend error is captured for hostname verification failure
  10132. EXPECT_NE(0UL, res.ssl_backend_error());
  10133. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10134. // For OpenSSL, ssl_error is 0 for verification errors
  10135. EXPECT_EQ(0, res.ssl_error());
  10136. #if !defined(_WIN32) || \
  10137. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10138. // On non-Windows or when Windows Schannel is disabled, the error comes
  10139. // from OpenSSL's hostname verification
  10140. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10141. res.ssl_backend_error());
  10142. #endif
  10143. #endif
  10144. }
  10145. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10146. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10147. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10148. SSLClient cli("www.google.com", 443);
  10149. cli.enable_server_certificate_verification(true);
  10150. auto res = cli.Get("/");
  10151. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10152. }
  10153. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10154. SSLClient cli("www.google.com", 443);
  10155. cli.enable_server_certificate_verification(true);
  10156. cli.enable_windows_certificate_verification(false);
  10157. auto res = cli.Get("/");
  10158. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10159. }
  10160. #endif
  10161. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10162. Client cli("https://google.com");
  10163. auto res = cli.Get("/");
  10164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10165. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10166. }
  10167. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10168. SSLClient cli("google.com");
  10169. cli.set_ca_cert_path(CA_CERT_FILE);
  10170. auto res = cli.Get("/");
  10171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10172. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10173. }
  10174. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10175. SSLClient cli("google.com");
  10176. cli.enable_server_certificate_verification(true);
  10177. cli.set_ca_cert_path("hello");
  10178. auto res = cli.Get("/");
  10179. ASSERT_TRUE(!res);
  10180. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10181. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10182. // should be set
  10183. EXPECT_EQ(0, res.ssl_error());
  10184. // Verify backend error is captured for SSLLoadingCerts
  10185. // This error occurs when loading CA certificates fails
  10186. EXPECT_NE(0UL, res.ssl_backend_error());
  10187. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10188. // OpenSSL specific error codes:
  10189. // > openssl errstr 0x80000002
  10190. // error:80000002:system library::No such file or directory
  10191. // > openssl errstr 0xA000126
  10192. // error:0A000126:SSL routines::unexpected eof while reading
  10193. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10194. res.ssl_backend_error() == 0xA000126);
  10195. #endif
  10196. }
  10197. TEST(SSLClientTest, ServerCertificateVerification4) {
  10198. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10199. ASSERT_TRUE(svr.is_valid());
  10200. svr.Get("/test", [&](const Request &, Response &res) {
  10201. res.set_content("test", "text/plain");
  10202. svr.stop();
  10203. ASSERT_TRUE(true);
  10204. });
  10205. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10206. auto se = detail::scope_exit([&] {
  10207. t.join();
  10208. ASSERT_FALSE(svr.is_running());
  10209. });
  10210. svr.wait_until_ready();
  10211. SSLClient cli("127.0.0.1", PORT);
  10212. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10213. cli.enable_server_certificate_verification(true);
  10214. cli.set_connection_timeout(30);
  10215. auto res = cli.Get("/test");
  10216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10217. ASSERT_EQ(StatusCode::OK_200, res->status);
  10218. }
  10219. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10220. std::string cert;
  10221. read_file(CA_CERT_FILE, cert);
  10222. SSLClient cli("google.com");
  10223. cli.load_ca_cert_store(cert.data(), cert.size());
  10224. const auto res = cli.Get("/");
  10225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10226. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10227. }
  10228. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10229. // clang-format off
  10230. static constexpr char cert[] =
  10231. "GlobalSign Root CA\n"
  10232. "==================\n"
  10233. "-----BEGIN CERTIFICATE-----\n"
  10234. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10235. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10236. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10237. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10238. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10239. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10240. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10241. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10242. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10243. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10244. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10245. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10246. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10247. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10248. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10249. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10250. "-----END CERTIFICATE-----\n";
  10251. // clang-format on
  10252. SSLClient cli("google.com");
  10253. cli.load_ca_cert_store(cert, sizeof(cert));
  10254. const auto res = cli.Get("/");
  10255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10256. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10257. }
  10258. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10259. SSLClient cli("www.youtube.com");
  10260. cli.set_ca_cert_path(CA_CERT_FILE);
  10261. cli.enable_server_certificate_verification(true);
  10262. cli.set_follow_location(true);
  10263. auto res = cli.Get("/");
  10264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10265. ASSERT_EQ(StatusCode::OK_200, res->status);
  10266. }
  10267. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10268. SSLClient cli("wWw.YouTube.Com");
  10269. cli.set_ca_cert_path(CA_CERT_FILE);
  10270. cli.enable_server_certificate_verification(true);
  10271. cli.enable_server_hostname_verification(true);
  10272. cli.set_follow_location(true);
  10273. auto res = cli.Get("/");
  10274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10275. ASSERT_EQ(StatusCode::OK_200, res->status);
  10276. }
  10277. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10278. SSLClient cli("gOoGlE.COm");
  10279. cli.enable_server_certificate_verification(true);
  10280. cli.enable_server_hostname_verification(true);
  10281. cli.set_follow_location(true);
  10282. auto res = cli.Get("/");
  10283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10284. ASSERT_EQ(StatusCode::OK_200, res->status);
  10285. }
  10286. TEST(SSLClientTest, Issue2004_Online) {
  10287. Client client("https://google.com");
  10288. client.set_follow_location(true);
  10289. auto res = client.Get("/");
  10290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10291. ASSERT_EQ(StatusCode::OK_200, res->status);
  10292. auto body = res->body;
  10293. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10294. }
  10295. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10296. // Create SSLClient with invalid cert/key to make is_valid() return false
  10297. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10298. "nonexistent_key.pem");
  10299. // is_valid() should be false due to cert loading failure
  10300. ASSERT_FALSE(cli.is_valid());
  10301. auto res = cli.Get("/");
  10302. ASSERT_FALSE(res);
  10303. EXPECT_EQ(Error::SSLConnection, res.error());
  10304. }
  10305. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10306. // Test for Issue #2251: SSL error not properly reported when client cert
  10307. // and key paths are swapped or mismatched
  10308. // This simulates the scenario where user accidentally swaps the cert and key
  10309. // files
  10310. // Using client cert file as private key and vice versa (completely wrong)
  10311. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10312. // Should fail validation due to cert/key mismatch
  10313. ASSERT_FALSE(cli.is_valid());
  10314. // Attempt to make a request should fail with proper error
  10315. auto res = cli.Get("/");
  10316. ASSERT_FALSE(res);
  10317. EXPECT_EQ(Error::SSLConnection, res.error());
  10318. // SSL error should be recorded in the Result object (this is the key fix for
  10319. // Issue #2251)
  10320. auto backend_error = res.ssl_backend_error();
  10321. EXPECT_NE(0u, backend_error);
  10322. }
  10323. // Tests cert/key mismatch detection at the TLS context level
  10324. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10325. // Test that using mismatched cert/key causes connection failure.
  10326. // We verify this at the SSLClient level rather than through internal
  10327. // TLS API functions.
  10328. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10329. cli.enable_server_certificate_verification(false);
  10330. cli.set_connection_timeout(2);
  10331. // The mismatch should cause a connection or handshake error
  10332. auto res = cli.Get("/test");
  10333. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10334. // Either way, the request should fail
  10335. EXPECT_FALSE(res);
  10336. }
  10337. #endif
  10338. #if 0
  10339. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10340. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10341. ASSERT_TRUE(cli != nullptr);
  10342. cli->set_address_family(AF_INET6);
  10343. cli->set_interface("en0");
  10344. auto res = cli->Get("/get");
  10345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10346. ASSERT_EQ(StatusCode::OK_200, res->status);
  10347. }
  10348. #endif
  10349. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10350. #ifdef CPPHTTPLIB_SSL_ENABLED
  10351. void ClientCertPresent(
  10352. const std::string &client_cert_file,
  10353. const std::string &client_private_key_file,
  10354. const std::string &client_encrypted_private_key_pass = std::string()) {
  10355. using namespace httplib::tls;
  10356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10357. CLIENT_CA_CERT_DIR);
  10358. ASSERT_TRUE(svr.is_valid());
  10359. svr.Get("/test", [&](const Request &req, Response &res) {
  10360. res.set_content("test", "text/plain");
  10361. auto cert = req.peer_cert();
  10362. ASSERT_TRUE(static_cast<bool>(cert));
  10363. std::string common_name = cert.subject_cn();
  10364. EXPECT_EQ("Common Name", common_name);
  10365. });
  10366. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10367. auto se = detail::scope_exit([&] {
  10368. svr.stop();
  10369. t.join();
  10370. ASSERT_FALSE(svr.is_running());
  10371. });
  10372. svr.wait_until_ready();
  10373. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10374. client_encrypted_private_key_pass);
  10375. cli.enable_server_certificate_verification(false);
  10376. cli.set_connection_timeout(30);
  10377. auto res = cli.Get("/test");
  10378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10379. ASSERT_EQ(StatusCode::OK_200, res->status);
  10380. }
  10381. TEST(SSLClientServerTest, ClientCertPresent) {
  10382. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10383. }
  10384. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10385. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10386. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10387. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10388. }
  10389. // PEM memory-based constructor tests (works with all TLS backends)
  10390. void PemMemoryClientCertPresent(
  10391. const std::string &client_cert_file,
  10392. const std::string &client_private_key_file,
  10393. const std::string &client_encrypted_private_key_pass = std::string()) {
  10394. // Read PEM files into memory
  10395. std::string server_cert_pem, server_key_pem;
  10396. std::string client_ca_pem;
  10397. std::string client_cert_pem, client_key_pem;
  10398. read_file(SERVER_CERT_FILE, server_cert_pem);
  10399. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10400. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10401. read_file(client_cert_file, client_cert_pem);
  10402. read_file(client_private_key_file, client_key_pem);
  10403. // Create server with PEM memory
  10404. SSLServer::PemMemory server_pem = {
  10405. server_cert_pem.c_str(),
  10406. server_cert_pem.size(),
  10407. server_key_pem.c_str(),
  10408. server_key_pem.size(),
  10409. client_ca_pem.c_str(),
  10410. client_ca_pem.size(),
  10411. nullptr // no password for server key
  10412. };
  10413. SSLServer svr(server_pem);
  10414. ASSERT_TRUE(svr.is_valid());
  10415. svr.Get("/test", [&](const Request &, Response &res) {
  10416. res.set_content("test", "text/plain");
  10417. });
  10418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. t.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. // Create client with PEM memory
  10426. const char *password = client_encrypted_private_key_pass.empty()
  10427. ? nullptr
  10428. : client_encrypted_private_key_pass.c_str();
  10429. SSLClient::PemMemory client_pem = {
  10430. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10431. client_key_pem.size(), password};
  10432. SSLClient cli(HOST, PORT, client_pem);
  10433. cli.enable_server_certificate_verification(false);
  10434. cli.set_connection_timeout(30);
  10435. auto res = cli.Get("/test");
  10436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10437. ASSERT_EQ(StatusCode::OK_200, res->status);
  10438. }
  10439. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10440. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10441. }
  10442. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10443. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10444. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10445. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10446. }
  10447. TEST(SSLClientServerTest, ClientCertMissing) {
  10448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10449. CLIENT_CA_CERT_DIR);
  10450. ASSERT_TRUE(svr.is_valid());
  10451. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10452. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10453. auto se = detail::scope_exit([&] {
  10454. svr.stop();
  10455. t.join();
  10456. ASSERT_FALSE(svr.is_running());
  10457. });
  10458. svr.wait_until_ready();
  10459. SSLClient cli(HOST, PORT);
  10460. cli.set_connection_timeout(30);
  10461. auto res = cli.Get("/test");
  10462. ASSERT_TRUE(!res);
  10463. // When client cert is missing and server requires it, connection fails
  10464. // Error type depends on backend implementation
  10465. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10466. res.error() == Error::SSLConnection);
  10467. // Verify backend error is captured
  10468. // Note: This test may have different error codes depending on the exact
  10469. // verification failure
  10470. EXPECT_NE(0UL, res.ssl_backend_error());
  10471. }
  10472. TEST(SSLClientServerTest, TrustDirOptional) {
  10473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10474. ASSERT_TRUE(svr.is_valid());
  10475. svr.Get("/test", [&](const Request &, Response &res) {
  10476. res.set_content("test", "text/plain");
  10477. });
  10478. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10479. auto se = detail::scope_exit([&] {
  10480. svr.stop();
  10481. t.join();
  10482. ASSERT_FALSE(svr.is_running());
  10483. });
  10484. svr.wait_until_ready();
  10485. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10486. cli.enable_server_certificate_verification(false);
  10487. cli.set_connection_timeout(30);
  10488. auto res = cli.Get("/test");
  10489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10490. ASSERT_EQ(StatusCode::OK_200, res->status);
  10491. }
  10492. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10493. class NoListenSSLServer : public SSLServer {
  10494. public:
  10495. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10496. const char *client_ca_cert_file_path,
  10497. const char *client_ca_cert_dir_path = nullptr)
  10498. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10499. client_ca_cert_dir_path),
  10500. stop_(false) {}
  10501. std::atomic_bool stop_;
  10502. private:
  10503. bool process_and_close_socket(socket_t /*sock*/) override {
  10504. // Don't create SSL context
  10505. while (!stop_.load()) {
  10506. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10507. }
  10508. return true;
  10509. }
  10510. };
  10511. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10512. CLIENT_CA_CERT_FILE);
  10513. ASSERT_TRUE(svr.is_valid());
  10514. svr.Get("/test", [&](const Request &, Response &res) {
  10515. res.set_content("test", "text/plain");
  10516. });
  10517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop_ = true;
  10520. svr.stop();
  10521. t.join();
  10522. ASSERT_FALSE(svr.is_running());
  10523. });
  10524. svr.wait_until_ready();
  10525. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10526. cli.enable_server_certificate_verification(false);
  10527. cli.set_connection_timeout(1);
  10528. auto res = cli.Get("/test");
  10529. ASSERT_TRUE(!res);
  10530. EXPECT_EQ(Error::SSLConnection, res.error());
  10531. // Timeout results in WantRead error code (maps to backend-specific value)
  10532. EXPECT_NE(0, res.ssl_error());
  10533. }
  10534. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10535. // Test SSLServer with client certificate verification using the standard
  10536. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10537. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10538. CLIENT_CA_CERT_DIR);
  10539. ASSERT_TRUE(svr.is_valid());
  10540. svr.Get("/test", [&](const Request &req, Response &res) {
  10541. res.set_content("test", "text/plain");
  10542. auto cert = req.peer_cert();
  10543. ASSERT_TRUE(static_cast<bool>(cert));
  10544. auto common_name = cert.subject_cn();
  10545. EXPECT_EQ("Common Name", common_name);
  10546. });
  10547. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10548. auto se = detail::scope_exit([&] {
  10549. svr.stop();
  10550. t.join();
  10551. ASSERT_FALSE(svr.is_running());
  10552. });
  10553. svr.wait_until_ready();
  10554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10555. cli.enable_server_certificate_verification(false);
  10556. cli.set_connection_timeout(30);
  10557. auto res = cli.Get("/test");
  10558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10559. ASSERT_EQ(StatusCode::OK_200, res->status);
  10560. }
  10561. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10562. // Verifies that wildcard matching and exact matching work consistently
  10563. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10564. using namespace httplib::tls;
  10565. // We need a running server to test against
  10566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10567. ASSERT_TRUE(svr.is_valid());
  10568. svr.Get("/test", [](const Request &, Response &res) {
  10569. res.set_content("ok", "text/plain");
  10570. });
  10571. thread t([&]() { svr.listen(HOST, PORT); });
  10572. auto se = detail::scope_exit([&] {
  10573. svr.stop();
  10574. t.join();
  10575. });
  10576. svr.wait_until_ready();
  10577. bool verify_callback_called = false;
  10578. bool verify_result_wrong = false;
  10579. SSLClient cli(HOST, PORT);
  10580. cli.enable_server_certificate_verification(true);
  10581. cli.set_ca_cert_path(CA_CERT_FILE);
  10582. cli.set_connection_timeout(5);
  10583. // Note: Test certificate has CN="Common Name", not "localhost"
  10584. bool verify_result_cn = false;
  10585. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10586. verify_callback_called = true;
  10587. if (!ctx.cert) return false;
  10588. // Test 1: "Common Name" should match (our test server cert CN)
  10589. verify_result_cn = ctx.check_hostname("Common Name");
  10590. // Test 2: wrong hostname should not match
  10591. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10592. return true; // Accept for the purpose of this test
  10593. });
  10594. auto res = cli.Get("/test");
  10595. // The request may succeed or fail depending on cert configuration
  10596. // but the callback should have been called
  10597. ASSERT_TRUE(verify_callback_called)
  10598. << "Verify callback should have been called";
  10599. // CN="Common Name" should match our test certificate
  10600. //
  10601. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10602. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10603. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10604. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10605. // <openssl/base.h>, which is included transitively when
  10606. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10607. #if defined(OPENSSL_IS_BORINGSSL)
  10608. EXPECT_FALSE(verify_result_cn)
  10609. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10610. #else
  10611. EXPECT_TRUE(verify_result_cn)
  10612. << "verify_hostname should match 'Common Name' (certificate CN)";
  10613. #endif
  10614. // Wrong hostname should not match
  10615. EXPECT_FALSE(verify_result_wrong)
  10616. << "verify_hostname should not match 'wronghost.example.com'";
  10617. }
  10618. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10619. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10620. // X509_check_ip behavior and must hold for every backend.
  10621. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10622. using namespace httplib::tls;
  10623. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10624. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10625. ASSERT_TRUE(svr.is_valid());
  10626. svr.Get("/test", [](const Request &, Response &res) {
  10627. res.set_content("ok", "text/plain");
  10628. });
  10629. thread t([&]() { svr.listen(HOST, PORT); });
  10630. auto se = detail::scope_exit([&] {
  10631. svr.stop();
  10632. t.join();
  10633. });
  10634. svr.wait_until_ready();
  10635. bool verify_callback_called = false;
  10636. bool ip_matched_via_cn = true;
  10637. SSLClient cli(HOST, PORT);
  10638. cli.enable_server_certificate_verification(true);
  10639. cli.set_ca_cert_path(CA_CERT_FILE);
  10640. cli.set_connection_timeout(5);
  10641. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10642. verify_callback_called = true;
  10643. if (!ctx.cert) return false;
  10644. // The IP appears only in the CN, so it must NOT be accepted.
  10645. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10646. return true; // Accept for the purpose of this test
  10647. });
  10648. cli.Get("/test");
  10649. ASSERT_TRUE(verify_callback_called)
  10650. << "Verify callback should have been called";
  10651. EXPECT_FALSE(ip_matched_via_cn)
  10652. << "An IP host must not be authenticated via the certificate CN";
  10653. }
  10654. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10655. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10656. using namespace httplib::tls;
  10657. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10658. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10659. ASSERT_TRUE(svr.is_valid());
  10660. svr.Get("/test", [](const Request &, Response &res) {
  10661. res.set_content("ok", "text/plain");
  10662. });
  10663. thread t([&]() { svr.listen(HOST, PORT); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. t.join();
  10667. });
  10668. svr.wait_until_ready();
  10669. bool verify_callback_called = false;
  10670. bool san_matched = false;
  10671. bool wrong_ipv6_matched = true;
  10672. bool cn_ipv6_matched = true;
  10673. SSLClient cli(HOST, PORT);
  10674. cli.enable_server_certificate_verification(true);
  10675. cli.set_ca_cert_path(CA_CERT_FILE);
  10676. cli.set_connection_timeout(5);
  10677. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10678. verify_callback_called = true;
  10679. if (!ctx.cert) return false;
  10680. // Matches the IPv6 iPAddress SAN.
  10681. san_matched = ctx.check_hostname("2001:db8::1");
  10682. // A different IPv6 address must not match.
  10683. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10684. // "::1" lives only in the CN, so it must not be accepted.
  10685. cn_ipv6_matched = ctx.check_hostname("::1");
  10686. return true; // Accept for the purpose of this test
  10687. });
  10688. cli.Get("/test");
  10689. ASSERT_TRUE(verify_callback_called)
  10690. << "Verify callback should have been called";
  10691. EXPECT_TRUE(san_matched)
  10692. << "verify_hostname should match an IPv6 iPAddress SAN";
  10693. EXPECT_FALSE(wrong_ipv6_matched)
  10694. << "verify_hostname should not match a non-matching IPv6 address";
  10695. EXPECT_FALSE(cn_ipv6_matched)
  10696. << "An IPv6 host must not be authenticated via the certificate CN";
  10697. }
  10698. #endif
  10699. // mbedTLS-specific callback constructor test
  10700. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10701. #ifdef CPPHTTPLIB_SSL_ENABLED
  10702. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10704. ASSERT_TRUE(svr.is_valid());
  10705. // Set up a handler to verify client certificate is present
  10706. bool client_cert_verified = false;
  10707. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10708. // Verify that client certificate was provided
  10709. client_cert_verified = true;
  10710. res.set_content("success", "text/plain");
  10711. });
  10712. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. // Client with certificate
  10720. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10721. cli.enable_server_certificate_verification(false);
  10722. cli.set_connection_timeout(30);
  10723. auto res = cli.Get("/test");
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. ASSERT_EQ(StatusCode::OK_200, res->status);
  10726. ASSERT_TRUE(client_cert_verified);
  10727. EXPECT_EQ("success", res->body);
  10728. }
  10729. #endif
  10730. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10731. // backends
  10732. #ifdef CPPHTTPLIB_SSL_ENABLED
  10733. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10734. using namespace httplib::tls;
  10735. // Test that when client CA cert file is provided,
  10736. // the server properly requests and validates client certificates
  10737. // Create a server with client authentication
  10738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10739. ASSERT_TRUE(svr.is_valid());
  10740. bool handler_called = false;
  10741. svr.Get("/test", [&](const Request &req, Response &res) {
  10742. handler_called = true;
  10743. // Verify that a client certificate was provided
  10744. auto cert = req.peer_cert();
  10745. ASSERT_TRUE(static_cast<bool>(cert));
  10746. // Get the issuer name
  10747. std::string issuer_str = cert.issuer_name();
  10748. ASSERT_FALSE(issuer_str.empty());
  10749. // The client certificate should be issued by our test CA
  10750. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10751. res.set_content("authenticated", "text/plain");
  10752. });
  10753. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10754. auto se = detail::scope_exit([&] {
  10755. svr.stop();
  10756. t.join();
  10757. ASSERT_FALSE(svr.is_running());
  10758. });
  10759. svr.wait_until_ready();
  10760. // Connect with a client certificate issued by the CA
  10761. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10762. cli.enable_server_certificate_verification(false);
  10763. cli.set_connection_timeout(30);
  10764. auto res = cli.Get("/test");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. ASSERT_EQ(StatusCode::OK_200, res->status);
  10767. ASSERT_TRUE(handler_called);
  10768. EXPECT_EQ("authenticated", res->body);
  10769. }
  10770. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10771. using namespace httplib::tls;
  10772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10773. ASSERT_TRUE(svr.is_valid());
  10774. svr.Get("/test", [](const Request &, Response &res) {
  10775. res.set_content("ok", "text/plain");
  10776. });
  10777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. t.join();
  10781. });
  10782. svr.wait_until_ready();
  10783. SSLClient cli(HOST, PORT);
  10784. cli.enable_server_certificate_verification(false);
  10785. cli.set_connection_timeout(30);
  10786. bool cert_checked = false;
  10787. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10788. if (ctx.cert) {
  10789. auto sans = ctx.sans();
  10790. // Test certificate may or may not have SANs - just verify the API
  10791. // works If SANs exist, verify the types are valid
  10792. for (const auto &san : sans) {
  10793. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10794. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10795. san.type == SanType::OTHER);
  10796. EXPECT_FALSE(san.value.empty());
  10797. }
  10798. cert_checked = true;
  10799. }
  10800. return true;
  10801. });
  10802. auto res = cli.Get("/test");
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_TRUE(cert_checked);
  10805. }
  10806. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10807. using namespace httplib::tls;
  10808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10809. ASSERT_TRUE(svr.is_valid());
  10810. svr.Get("/test", [](const Request &, Response &res) {
  10811. res.set_content("ok", "text/plain");
  10812. });
  10813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10814. auto se = detail::scope_exit([&] {
  10815. svr.stop();
  10816. t.join();
  10817. });
  10818. svr.wait_until_ready();
  10819. SSLClient cli(HOST, PORT);
  10820. cli.enable_server_certificate_verification(false);
  10821. cli.set_connection_timeout(30);
  10822. bool validity_checked = false;
  10823. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10824. if (ctx.cert) {
  10825. time_t not_before = 0, not_after = 0;
  10826. bool result = ctx.validity(not_before, not_after);
  10827. EXPECT_TRUE(result);
  10828. // Verify that not_before < now < not_after for a valid cert
  10829. time_t now = time(nullptr);
  10830. EXPECT_LT(not_before, now);
  10831. EXPECT_GT(not_after, now);
  10832. validity_checked = true;
  10833. }
  10834. return true;
  10835. });
  10836. auto res = cli.Get("/test");
  10837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10838. EXPECT_TRUE(validity_checked);
  10839. }
  10840. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10841. using namespace httplib::tls;
  10842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10843. ASSERT_TRUE(svr.is_valid());
  10844. svr.Get("/test", [](const Request &, Response &res) {
  10845. res.set_content("ok", "text/plain");
  10846. });
  10847. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10848. auto se = detail::scope_exit([&] {
  10849. svr.stop();
  10850. t.join();
  10851. });
  10852. svr.wait_until_ready();
  10853. SSLClient cli(HOST, PORT);
  10854. cli.enable_server_certificate_verification(false);
  10855. cli.set_connection_timeout(30);
  10856. bool serial_checked = false;
  10857. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10858. if (ctx.cert) {
  10859. std::string serial = ctx.serial();
  10860. EXPECT_FALSE(serial.empty());
  10861. // Serial should be a hex string
  10862. for (char c : serial) {
  10863. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10864. (c >= 'a' && c <= 'f'));
  10865. }
  10866. serial_checked = true;
  10867. }
  10868. return true;
  10869. });
  10870. auto res = cli.Get("/test");
  10871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10872. EXPECT_TRUE(serial_checked);
  10873. }
  10874. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10875. // Test 1: Valid CA file - no error should be recorded
  10876. {
  10877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10878. CLIENT_CA_CERT_FILE);
  10879. ASSERT_TRUE(svr.is_valid());
  10880. // With valid setup, last_ssl_error should be 0
  10881. EXPECT_EQ(0, svr.ssl_last_error());
  10882. }
  10883. // Test 2: Invalid CA file content
  10884. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10885. {
  10886. // Create a temporary file with completely invalid content
  10887. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10888. {
  10889. std::ofstream ofs(temp_invalid_ca);
  10890. ofs << "This is not a certificate file at all\n";
  10891. ofs << "Just plain text content\n";
  10892. }
  10893. // Create server with invalid CA file
  10894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10895. // Clean up temporary file
  10896. std::remove(temp_invalid_ca);
  10897. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10898. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10899. // Note: SSL_CTX_load_verify_locations typically fails first,
  10900. // but our error handling code path is still exercised
  10901. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10902. }
  10903. }
  10904. TEST(VerifyCallbackTest, VerifyContextFields) {
  10905. using namespace httplib::tls;
  10906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10907. ASSERT_TRUE(svr.is_valid());
  10908. svr.Get("/test", [](const Request &, Response &res) {
  10909. res.set_content("ok", "text/plain");
  10910. });
  10911. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. t.join();
  10915. });
  10916. svr.wait_until_ready();
  10917. SSLClient cli(HOST, PORT);
  10918. cli.enable_server_certificate_verification(false);
  10919. cli.set_connection_timeout(30);
  10920. int callback_count = 0;
  10921. bool saw_leaf_cert = false;
  10922. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10923. if (ctx.cert) {
  10924. callback_count++;
  10925. // We should see at least one certificate (the leaf)
  10926. std::string cn = ctx.subject_cn();
  10927. if (!cn.empty()) { saw_leaf_cert = true; }
  10928. // Verify context fields are populated
  10929. EXPECT_NE(ctx.session, nullptr);
  10930. EXPECT_GE(ctx.depth, 0);
  10931. }
  10932. return true;
  10933. });
  10934. auto res = cli.Get("/test");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_GT(callback_count, 0);
  10937. EXPECT_TRUE(saw_leaf_cert);
  10938. }
  10939. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10940. using httplib::tls::TlsError;
  10941. // Test that verify_error_to_string returns empty for success
  10942. std::string success_str = TlsError::verify_error_to_string(0);
  10943. EXPECT_TRUE(success_str.empty());
  10944. // Test that verify_error_to_string returns non-empty for error codes
  10945. // Using a common error code (certificate expired)
  10946. std::string error_str =
  10947. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10948. EXPECT_FALSE(error_str.empty());
  10949. }
  10950. TEST(SessionVerifierTest, CertificateAccepted) {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(svr.is_valid());
  10953. svr.Get("/test", [](const Request &, Response &res) {
  10954. res.set_content("ok", "text/plain");
  10955. });
  10956. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10957. auto se = detail::scope_exit([&] {
  10958. svr.stop();
  10959. t.join();
  10960. });
  10961. svr.wait_until_ready();
  10962. SSLClient cli(HOST, PORT);
  10963. cli.enable_server_certificate_verification(false);
  10964. cli.set_connection_timeout(30);
  10965. bool callback_called = false;
  10966. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10967. EXPECT_NE(session, nullptr);
  10968. callback_called = true;
  10969. return SSLVerifierResponse::CertificateAccepted;
  10970. });
  10971. auto res = cli.Get("/test");
  10972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10973. EXPECT_EQ(200, res->status);
  10974. EXPECT_TRUE(callback_called);
  10975. }
  10976. TEST(SessionVerifierTest, CertificateRejected) {
  10977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10978. ASSERT_TRUE(svr.is_valid());
  10979. svr.Get("/test", [](const Request &, Response &res) {
  10980. res.set_content("ok", "text/plain");
  10981. });
  10982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10983. auto se = detail::scope_exit([&] {
  10984. svr.stop();
  10985. t.join();
  10986. });
  10987. svr.wait_until_ready();
  10988. SSLClient cli(HOST, PORT);
  10989. cli.enable_server_certificate_verification(false);
  10990. cli.set_connection_timeout(30);
  10991. bool callback_called = false;
  10992. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10993. EXPECT_NE(session, nullptr);
  10994. callback_called = true;
  10995. return SSLVerifierResponse::CertificateRejected;
  10996. });
  10997. auto res = cli.Get("/test");
  10998. EXPECT_FALSE(res);
  10999. EXPECT_TRUE(callback_called);
  11000. }
  11001. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11003. ASSERT_TRUE(svr.is_valid());
  11004. svr.Get("/test", [](const Request &, Response &res) {
  11005. res.set_content("ok", "text/plain");
  11006. });
  11007. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11008. auto se = detail::scope_exit([&] {
  11009. svr.stop();
  11010. t.join();
  11011. });
  11012. svr.wait_until_ready();
  11013. // NoDecisionMade with verification disabled should succeed (no default check)
  11014. SSLClient cli(HOST, PORT);
  11015. cli.enable_server_certificate_verification(false);
  11016. cli.set_connection_timeout(30);
  11017. bool callback_called = false;
  11018. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11019. EXPECT_NE(session, nullptr);
  11020. callback_called = true;
  11021. return SSLVerifierResponse::NoDecisionMade;
  11022. });
  11023. auto res = cli.Get("/test");
  11024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11025. EXPECT_EQ(200, res->status);
  11026. EXPECT_TRUE(callback_called);
  11027. }
  11028. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11030. ASSERT_TRUE(svr.is_valid());
  11031. svr.Get("/test", [](const Request &, Response &res) {
  11032. res.set_content("ok", "text/plain");
  11033. });
  11034. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11035. auto se = detail::scope_exit([&] {
  11036. svr.stop();
  11037. t.join();
  11038. });
  11039. svr.wait_until_ready();
  11040. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11041. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11042. // so we only check that the request fails, not whether the callback was
  11043. // called.
  11044. SSLClient cli(HOST, PORT);
  11045. cli.enable_server_certificate_verification(true);
  11046. cli.set_connection_timeout(30);
  11047. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11048. EXPECT_NE(session, nullptr);
  11049. return SSLVerifierResponse::NoDecisionMade;
  11050. });
  11051. auto res = cli.Get("/test");
  11052. EXPECT_FALSE(res);
  11053. }
  11054. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11055. // Test SSL server using PemMemory constructor with client CA certificates
  11056. // Read PEM files
  11057. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11058. read_file(SERVER_CERT_FILE, server_cert_pem);
  11059. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11060. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11061. // Create SSLServer with PemMemory constructor including client CA
  11062. SSLServer::PemMemory server_pem = {
  11063. server_cert_pem.c_str(),
  11064. server_cert_pem.size(),
  11065. server_key_pem.c_str(),
  11066. server_key_pem.size(),
  11067. client_ca_pem.c_str(),
  11068. client_ca_pem.size(),
  11069. nullptr // no password for server key
  11070. };
  11071. SSLServer svr(server_pem);
  11072. ASSERT_TRUE(svr.is_valid());
  11073. // No SSL error should be recorded for valid setup
  11074. EXPECT_EQ(0, svr.ssl_last_error());
  11075. // Set up server endpoints
  11076. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11077. res.set_content("ok", "text/plain");
  11078. });
  11079. // Start server in a thread
  11080. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11081. svr.wait_until_ready();
  11082. // Connect with client certificate (using constructor with paths)
  11083. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11084. cli.enable_server_certificate_verification(false);
  11085. auto res = cli.Get("/test-pem-ca");
  11086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11087. EXPECT_EQ(200, res->status);
  11088. EXPECT_EQ("ok", res->body);
  11089. svr.stop();
  11090. server_thread.join();
  11091. }
  11092. #endif
  11093. #ifdef _WIN32
  11094. TEST(CleanupTest, WSACleanup) {
  11095. int ret = WSACleanup();
  11096. ASSERT_EQ(0, ret);
  11097. }
  11098. #endif
  11099. #ifndef CPPHTTPLIB_SSL_ENABLED
  11100. TEST(NoSSLSupport, SimpleInterface) {
  11101. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11102. }
  11103. #endif
  11104. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11105. TEST(InvalidScheme, SimpleInterface) {
  11106. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11107. }
  11108. #endif
  11109. TEST(NoScheme, SimpleInterface) {
  11110. Client cli("yahoo.com:80");
  11111. ASSERT_TRUE(cli.is_valid());
  11112. }
  11113. TEST(SendAPI, SimpleInterface_Online) {
  11114. Client cli("http://yahoo.com");
  11115. Request req;
  11116. req.method = "GET";
  11117. req.path = "/";
  11118. auto res = cli.send(req);
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11121. }
  11122. TEST(SendAPI, WithParamsInRequest) {
  11123. Server svr;
  11124. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11125. EXPECT_TRUE(req.has_param("test"));
  11126. EXPECT_EQ("test_value", req.get_param_value("test"));
  11127. });
  11128. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11129. auto se = detail::scope_exit([&] {
  11130. svr.stop();
  11131. t.join();
  11132. ASSERT_FALSE(svr.is_running());
  11133. });
  11134. svr.wait_until_ready();
  11135. Client cli(HOST, PORT);
  11136. {
  11137. Request req;
  11138. req.method = "GET";
  11139. req.path = "/";
  11140. req.params.emplace("test", "test_value");
  11141. auto res = cli.send(req);
  11142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11143. }
  11144. {
  11145. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11147. }
  11148. }
  11149. TEST(ClientImplMethods, GetSocketTest) {
  11150. httplib::Server svr;
  11151. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11152. res.status = StatusCode::OK_200;
  11153. });
  11154. auto port = svr.bind_to_any_port("127.0.0.1");
  11155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. thread.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. {
  11163. httplib::Client cli("127.0.0.1", port);
  11164. cli.set_keep_alive(true);
  11165. // Use the behavior of cpp-httplib of opening the connection
  11166. // only when the first request happens. If that changes,
  11167. // this test would be obsolete.
  11168. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11169. // This also implicitly tests the server. But other tests would fail much
  11170. // earlier than this one to be considered.
  11171. auto res = cli.Get("/");
  11172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11173. EXPECT_EQ(StatusCode::OK_200, res->status);
  11174. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11175. }
  11176. }
  11177. #ifdef CPPHTTPLIB_SSL_ENABLED
  11178. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11179. Client cli("http://yahoo.com");
  11180. auto res = cli.Get("/");
  11181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11182. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11183. cli.set_follow_location(true);
  11184. res = cli.Get("/");
  11185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11186. EXPECT_EQ(StatusCode::OK_200, res->status);
  11187. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11188. }
  11189. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11190. Client cli("https://yahoo.com");
  11191. auto res = cli.Get("/");
  11192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11193. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11194. cli.set_follow_location(true);
  11195. res = cli.Get("/");
  11196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11197. EXPECT_EQ(StatusCode::OK_200, res->status);
  11198. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11199. }
  11200. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11201. Client cli("https://yahoo.com");
  11202. auto res = cli.Get("/");
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. ASSERT_FALSE(!res);
  11205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11206. ASSERT_FALSE(res == nullptr);
  11207. ASSERT_TRUE(res != nullptr);
  11208. EXPECT_EQ(Error::Success, res.error());
  11209. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11210. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11211. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11212. cli.set_follow_location(true);
  11213. res = cli.Get("/");
  11214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11215. EXPECT_EQ(Error::Success, res.error());
  11216. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11217. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11218. EXPECT_EQ(StatusCode::OK_200, res->status);
  11219. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11220. }
  11221. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11222. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11223. Client cli("https://cdnjs.cloudflare.com");
  11224. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11225. Headers{{"Accept-Encoding", "br"}});
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::OK_200, res->status);
  11228. EXPECT_EQ(287630U, res->body.size());
  11229. EXPECT_EQ("application/javascript; charset=utf-8",
  11230. res->get_header_value("Content-Type"));
  11231. }
  11232. #endif
  11233. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11234. #undef REDIR_HOST // Silence compiler warning
  11235. #define REDIR_HOST "https://httpbingo.org"
  11236. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11237. Client cli(REDIR_HOST);
  11238. cli.set_follow_location(true);
  11239. auto res =
  11240. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11242. EXPECT_EQ(StatusCode::OK_200, res->status);
  11243. }
  11244. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11245. Client cli(REDIR_HOST);
  11246. cli.set_follow_location(true);
  11247. Params params;
  11248. params.emplace("url", "http://example.com");
  11249. params.emplace("status_code", "302");
  11250. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11252. EXPECT_EQ(StatusCode::OK_200, res->status);
  11253. }
  11254. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11255. Client cli(REDIR_HOST);
  11256. cli.set_follow_location(true);
  11257. Params params;
  11258. params.emplace("url", "http://example.com");
  11259. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11261. EXPECT_EQ(StatusCode::OK_200, res->status);
  11262. }
  11263. TEST(HttpToHttpsRedirectTest, CertFile) {
  11264. auto ssl_port = PORT + 1;
  11265. Server svr;
  11266. ASSERT_TRUE(svr.is_valid());
  11267. svr.Get("/index", [&](const Request &, Response &res) {
  11268. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11269. "/index");
  11270. svr.stop();
  11271. });
  11272. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11273. ASSERT_TRUE(ssl_svr.is_valid());
  11274. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11275. res.set_content("test", "text/plain");
  11276. ssl_svr.stop();
  11277. });
  11278. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11279. thread t2 =
  11280. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11281. auto se = detail::scope_exit([&] {
  11282. t2.join();
  11283. t.join();
  11284. ASSERT_FALSE(svr.is_running());
  11285. });
  11286. svr.wait_until_ready();
  11287. ssl_svr.wait_until_ready();
  11288. Client cli("127.0.0.1", PORT);
  11289. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11290. cli.enable_server_certificate_verification(true);
  11291. cli.set_follow_location(true);
  11292. cli.set_connection_timeout(30);
  11293. auto res = cli.Get("/index");
  11294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11295. ASSERT_EQ(StatusCode::OK_200, res->status);
  11296. }
  11297. TEST(SSLClientRedirectTest, CertFile) {
  11298. auto ssl_port = PORT + 1;
  11299. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11300. ASSERT_TRUE(ssl_svr1.is_valid());
  11301. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11302. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11303. "/index");
  11304. ssl_svr1.stop();
  11305. });
  11306. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11307. ASSERT_TRUE(ssl_svr2.is_valid());
  11308. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11309. res.set_content("test", "text/plain");
  11310. ssl_svr2.stop();
  11311. });
  11312. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11313. thread t2 =
  11314. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11315. auto se = detail::scope_exit([&] {
  11316. t2.join();
  11317. t.join();
  11318. ASSERT_FALSE(ssl_svr1.is_running());
  11319. });
  11320. ssl_svr1.wait_until_ready();
  11321. ssl_svr2.wait_until_ready();
  11322. SSLClient cli("127.0.0.1", PORT);
  11323. std::string cert;
  11324. read_file(SERVER_CERT2_FILE, cert);
  11325. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11326. cli.enable_server_certificate_verification(true);
  11327. cli.set_follow_location(true);
  11328. cli.set_connection_timeout(30);
  11329. auto res = cli.Get("/index");
  11330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11331. ASSERT_EQ(StatusCode::OK_200, res->status);
  11332. }
  11333. #endif
  11334. #ifdef CPPHTTPLIB_SSL_ENABLED
  11335. // Test that set_ca_cert_store() skips system certs (consistent with
  11336. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11337. // should be trusted - system certs should NOT be loaded.
  11338. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11339. // Load a specific cert that is NOT a system CA cert
  11340. std::string cert;
  11341. read_file(SERVER_CERT2_FILE, cert);
  11342. SSLClient cli("google.com");
  11343. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11344. cli.enable_server_certificate_verification(true);
  11345. // This should FAIL because:
  11346. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11347. // 2. System certs should NOT be loaded when custom store is set
  11348. // If system certs WERE loaded, this would succeed
  11349. auto res = cli.Get("/");
  11350. ASSERT_FALSE(res);
  11351. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11352. }
  11353. // Same as above, but through the native store handle path. Regression test:
  11354. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11355. // merged system certs into the user-provided store.
  11356. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11357. std::string cert;
  11358. read_file(SERVER_CERT2_FILE, cert);
  11359. SSLClient cli("google.com");
  11360. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11361. cli.enable_server_certificate_verification(true);
  11362. auto res = cli.Get("/");
  11363. ASSERT_FALSE(res);
  11364. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11365. }
  11366. // A custom store set via the native handle must still verify a server whose
  11367. // cert it does contain.
  11368. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11369. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11370. ASSERT_TRUE(svr.is_valid());
  11371. svr.Get("/test", [&](const Request &, Response &res) {
  11372. res.set_content("test", "text/plain");
  11373. });
  11374. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11375. auto se = detail::scope_exit([&] {
  11376. svr.stop();
  11377. t.join();
  11378. ASSERT_FALSE(svr.is_running());
  11379. });
  11380. svr.wait_until_ready();
  11381. SSLClient cli("127.0.0.1", PORT);
  11382. std::string cert;
  11383. read_file(SERVER_CERT2_FILE, cert);
  11384. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11385. cli.enable_server_certificate_verification(true);
  11386. cli.set_connection_timeout(30);
  11387. auto res = cli.Get("/test");
  11388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11389. ASSERT_EQ(StatusCode::OK_200, res->status);
  11390. }
  11391. // CA certs loaded through the universal Client must be transferred to the
  11392. // client created internally for following an HTTPS redirect. Regression test:
  11393. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11394. // the CA data for redirect transfer.
  11395. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11396. auto ssl_port = PORT + 1;
  11397. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11398. ASSERT_TRUE(ssl_svr1.is_valid());
  11399. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11400. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11401. "/index");
  11402. });
  11403. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11404. ASSERT_TRUE(ssl_svr2.is_valid());
  11405. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11406. res.set_content("test", "text/plain");
  11407. });
  11408. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11409. thread t2 =
  11410. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11411. auto se = detail::scope_exit([&] {
  11412. ssl_svr2.stop();
  11413. ssl_svr1.stop();
  11414. t2.join();
  11415. t.join();
  11416. ASSERT_FALSE(ssl_svr1.is_running());
  11417. });
  11418. ssl_svr1.wait_until_ready();
  11419. ssl_svr2.wait_until_ready();
  11420. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11421. std::string cert;
  11422. read_file(SERVER_CERT2_FILE, cert);
  11423. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11424. cli.enable_server_certificate_verification(true);
  11425. cli.set_follow_location(true);
  11426. cli.set_connection_timeout(30);
  11427. auto res = cli.Get("/index");
  11428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11429. ASSERT_EQ(StatusCode::OK_200, res->status);
  11430. }
  11431. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11432. // so a host signed by a system CA verifies even though a custom CA is set
  11433. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11434. std::string cert;
  11435. read_file(SERVER_CERT2_FILE, cert);
  11436. SSLClient cli("google.com");
  11437. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11438. cli.enable_system_ca(true);
  11439. cli.enable_server_certificate_verification(true);
  11440. auto res = cli.Get("/");
  11441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11442. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11443. }
  11444. // The custom CA remains effective when combined with the system CA
  11445. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11446. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11447. ASSERT_TRUE(svr.is_valid());
  11448. svr.Get("/test", [&](const Request &, Response &res) {
  11449. res.set_content("test", "text/plain");
  11450. });
  11451. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11452. auto se = detail::scope_exit([&] {
  11453. svr.stop();
  11454. t.join();
  11455. ASSERT_FALSE(svr.is_running());
  11456. });
  11457. svr.wait_until_ready();
  11458. SSLClient cli("127.0.0.1", PORT);
  11459. std::string cert;
  11460. read_file(SERVER_CERT2_FILE, cert);
  11461. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11462. cli.enable_system_ca(true);
  11463. cli.enable_server_certificate_verification(true);
  11464. cli.set_connection_timeout(30);
  11465. auto res = cli.Get("/test");
  11466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11467. ASSERT_EQ(StatusCode::OK_200, res->status);
  11468. }
  11469. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11470. // skip chain verification entirely (only the certificate identity was
  11471. // checked), so a server presenting an untrusted certificate with a matching
  11472. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11473. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11474. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11475. ASSERT_TRUE(svr.is_valid());
  11476. svr.Get("/test", [&](const Request &, Response &res) {
  11477. res.set_content("test", "text/plain");
  11478. });
  11479. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11480. auto se = detail::scope_exit([&] {
  11481. svr.stop();
  11482. t.join();
  11483. ASSERT_FALSE(svr.is_running());
  11484. });
  11485. svr.wait_until_ready();
  11486. SSLClient cli("127.0.0.1", PORT);
  11487. std::string cert;
  11488. // A trusted CA that did not sign the server certificate. The server cert
  11489. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11490. // this connection.
  11491. read_file(CLIENT_CA_CERT_FILE, cert);
  11492. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11493. cli.enable_server_certificate_verification(true);
  11494. cli.set_connection_timeout(30);
  11495. auto res = cli.Get("/test");
  11496. ASSERT_FALSE(res);
  11497. }
  11498. // enable_system_ca(false) prevents system CA loading entirely
  11499. TEST(SSLClientTest, DisableSystemCa_Online) {
  11500. SSLClient cli("google.com");
  11501. cli.enable_system_ca(false);
  11502. cli.enable_server_certificate_verification(true);
  11503. auto res = cli.Get("/");
  11504. ASSERT_FALSE(res);
  11505. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11506. // itself when the CA chain is empty
  11507. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11508. res.error() == Error::SSLConnection);
  11509. }
  11510. // The universal Client forwards enable_system_ca()
  11511. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11512. std::string cert;
  11513. read_file(SERVER_CERT2_FILE, cert);
  11514. Client cli("https://google.com");
  11515. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11516. cli.enable_system_ca(true);
  11517. cli.enable_server_certificate_verification(true);
  11518. auto res = cli.Get("/");
  11519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11521. }
  11522. // The system CA policy must carry over to the client created internally for
  11523. // following a cross-host HTTPS redirect
  11524. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11525. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11526. ASSERT_TRUE(svr.is_valid());
  11527. svr.Get("/index", [&](const Request &, Response &res) {
  11528. res.set_redirect("https://www.google.com/");
  11529. });
  11530. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11531. auto se = detail::scope_exit([&] {
  11532. svr.stop();
  11533. t.join();
  11534. ASSERT_FALSE(svr.is_running());
  11535. });
  11536. svr.wait_until_ready();
  11537. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11538. std::string cert;
  11539. read_file(SERVER_CERT2_FILE, cert);
  11540. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11541. cli.enable_system_ca(true);
  11542. cli.enable_server_certificate_verification(true);
  11543. cli.set_follow_location(true);
  11544. cli.set_connection_timeout(30);
  11545. // Receiving any response proves the redirect client completed the TLS
  11546. // handshake with a system-CA-signed host
  11547. auto res = cli.Get("/index");
  11548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11549. }
  11550. TEST(MultipartFormDataTest, LargeData) {
  11551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11552. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11553. const ContentReader &content_reader) {
  11554. if (req.is_multipart_form_data()) {
  11555. std::vector<FormData> items;
  11556. content_reader(
  11557. [&](const FormData &file) {
  11558. items.push_back(file);
  11559. return true;
  11560. },
  11561. [&](const char *data, size_t data_length) {
  11562. items.back().content.append(data, data_length);
  11563. return true;
  11564. });
  11565. EXPECT_TRUE(std::string(items[0].name) == "document");
  11566. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11567. EXPECT_TRUE(items[0].filename == "2MB_data");
  11568. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11569. EXPECT_TRUE(items[1].name == "hello");
  11570. EXPECT_TRUE(items[1].content == "world");
  11571. EXPECT_TRUE(items[1].filename == "");
  11572. EXPECT_TRUE(items[1].content_type == "");
  11573. } else {
  11574. std::string body;
  11575. content_reader([&](const char *data, size_t data_length) {
  11576. body.append(data, data_length);
  11577. return true;
  11578. });
  11579. }
  11580. });
  11581. auto port = svr.bind_to_any_port(HOST);
  11582. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11583. auto se = detail::scope_exit([&] {
  11584. svr.stop();
  11585. t.join();
  11586. ASSERT_FALSE(svr.is_running());
  11587. });
  11588. svr.wait_until_ready();
  11589. {
  11590. std::string data(1024 * 1024 * 2, '.');
  11591. std::stringstream buffer;
  11592. buffer << data;
  11593. SSLClient cli(HOST, port);
  11594. cli.enable_server_certificate_verification(false);
  11595. UploadFormDataItems items{
  11596. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11597. {"hello", "world", "", ""},
  11598. };
  11599. auto res = cli.Post("/post", items);
  11600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11601. ASSERT_EQ(StatusCode::OK_200, res->status);
  11602. }
  11603. }
  11604. TEST(MultipartFormDataTest, DataProviderItems) {
  11605. std::random_device seed_gen;
  11606. std::mt19937 random(seed_gen());
  11607. std::string rand1;
  11608. rand1.resize(1000);
  11609. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11610. std::string rand2;
  11611. rand2.resize(3000);
  11612. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11613. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11614. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11615. const ContentReader &content_reader) {
  11616. ASSERT_FALSE(req.is_multipart_form_data());
  11617. std::string body;
  11618. content_reader([&](const char *data, size_t data_length) {
  11619. body.append(data, data_length);
  11620. return true;
  11621. });
  11622. EXPECT_EQ(body, "");
  11623. });
  11624. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11625. const ContentReader &content_reader) {
  11626. ASSERT_TRUE(req.is_multipart_form_data());
  11627. std::vector<FormData> items;
  11628. content_reader(
  11629. [&](const FormData &file) {
  11630. items.push_back(file);
  11631. return true;
  11632. },
  11633. [&](const char *data, size_t data_length) {
  11634. items.back().content.append(data, data_length);
  11635. return true;
  11636. });
  11637. ASSERT_TRUE(items.size() == 2);
  11638. EXPECT_EQ(std::string(items[0].name), "name1");
  11639. EXPECT_EQ(items[0].content, "Testing123");
  11640. EXPECT_EQ(items[0].filename, "filename1");
  11641. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11642. EXPECT_EQ(items[1].name, "name2");
  11643. EXPECT_EQ(items[1].content, "Testing456");
  11644. EXPECT_EQ(items[1].filename, "");
  11645. EXPECT_EQ(items[1].content_type, "");
  11646. });
  11647. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11648. const ContentReader &content_reader) {
  11649. ASSERT_TRUE(req.is_multipart_form_data());
  11650. std::vector<FormData> items;
  11651. content_reader(
  11652. [&](const FormData &file) {
  11653. items.push_back(file);
  11654. return true;
  11655. },
  11656. [&](const char *data, size_t data_length) {
  11657. items.back().content.append(data, data_length);
  11658. return true;
  11659. });
  11660. ASSERT_TRUE(items.size() == 2);
  11661. EXPECT_EQ(items[0].name, "name3");
  11662. EXPECT_EQ(items[0].content, rand1);
  11663. EXPECT_EQ(items[0].filename, "filename3");
  11664. EXPECT_EQ(items[0].content_type, "");
  11665. EXPECT_EQ(items[1].name, "name4");
  11666. EXPECT_EQ(items[1].content, rand2);
  11667. EXPECT_EQ(items[1].filename, "filename4");
  11668. EXPECT_EQ(items[1].content_type, "");
  11669. });
  11670. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11671. const ContentReader &content_reader) {
  11672. ASSERT_TRUE(req.is_multipart_form_data());
  11673. std::vector<FormData> items;
  11674. content_reader(
  11675. [&](const FormData &file) {
  11676. items.push_back(file);
  11677. return true;
  11678. },
  11679. [&](const char *data, size_t data_length) {
  11680. items.back().content.append(data, data_length);
  11681. return true;
  11682. });
  11683. ASSERT_TRUE(items.size() == 4);
  11684. EXPECT_EQ(std::string(items[0].name), "name1");
  11685. EXPECT_EQ(items[0].content, "Testing123");
  11686. EXPECT_EQ(items[0].filename, "filename1");
  11687. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11688. EXPECT_EQ(items[1].name, "name2");
  11689. EXPECT_EQ(items[1].content, "Testing456");
  11690. EXPECT_EQ(items[1].filename, "");
  11691. EXPECT_EQ(items[1].content_type, "");
  11692. EXPECT_EQ(items[2].name, "name3");
  11693. EXPECT_EQ(items[2].content, rand1);
  11694. EXPECT_EQ(items[2].filename, "filename3");
  11695. EXPECT_EQ(items[2].content_type, "");
  11696. EXPECT_EQ(items[3].name, "name4");
  11697. EXPECT_EQ(items[3].content, rand2);
  11698. EXPECT_EQ(items[3].filename, "filename4");
  11699. EXPECT_EQ(items[3].content_type, "");
  11700. });
  11701. auto port = svr.bind_to_any_port("localhost");
  11702. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11703. auto se = detail::scope_exit([&] {
  11704. svr.stop();
  11705. t.join();
  11706. ASSERT_FALSE(svr.is_running());
  11707. });
  11708. svr.wait_until_ready();
  11709. {
  11710. SSLClient cli("localhost", port);
  11711. cli.enable_server_certificate_verification(false);
  11712. UploadFormDataItems items{
  11713. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11714. {"name2", "Testing456", "", ""}, // not a file
  11715. };
  11716. {
  11717. auto res = cli.Post("/post-none", {}, {}, {});
  11718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11719. ASSERT_EQ(StatusCode::OK_200, res->status);
  11720. }
  11721. FormDataProviderItems providers;
  11722. {
  11723. auto res =
  11724. cli.Post("/post-items", {}, items, providers); // empty providers
  11725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11726. ASSERT_EQ(StatusCode::OK_200, res->status);
  11727. }
  11728. providers.push_back({"name3",
  11729. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11730. // test the offset is given correctly at each step
  11731. if (!offset)
  11732. sink.os.write(rand1.data(), 30);
  11733. else if (offset == 30)
  11734. sink.os.write(rand1.data() + 30, 300);
  11735. else if (offset == 330)
  11736. sink.os.write(rand1.data() + 330, 670);
  11737. else if (offset == rand1.size())
  11738. sink.done();
  11739. return true;
  11740. },
  11741. "filename3",
  11742. {}});
  11743. providers.push_back({"name4",
  11744. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11745. // test the offset is given correctly at each step
  11746. if (!offset)
  11747. sink.os.write(rand2.data(), 2000);
  11748. else if (offset == 2000)
  11749. sink.os.write(rand2.data() + 2000, 1);
  11750. else if (offset == 2001)
  11751. sink.os.write(rand2.data() + 2001, 999);
  11752. else if (offset == rand2.size())
  11753. sink.done();
  11754. return true;
  11755. },
  11756. "filename4",
  11757. {}});
  11758. {
  11759. auto res = cli.Post("/post-providers", {}, {}, providers);
  11760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11761. ASSERT_EQ(StatusCode::OK_200, res->status);
  11762. }
  11763. {
  11764. auto res = cli.Post("/post-both", {}, items, providers);
  11765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11766. ASSERT_EQ(StatusCode::OK_200, res->status);
  11767. }
  11768. }
  11769. }
  11770. TEST(MultipartFormDataTest, BadHeader) {
  11771. Server svr;
  11772. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11773. res.set_content("ok", "text/plain");
  11774. });
  11775. thread t = thread([&] { svr.listen(HOST, PORT); });
  11776. auto se = detail::scope_exit([&] {
  11777. svr.stop();
  11778. t.join();
  11779. ASSERT_FALSE(svr.is_running());
  11780. });
  11781. svr.wait_until_ready();
  11782. const std::string body =
  11783. "This is the preamble. It is to be ignored, though it\r\n"
  11784. "is a handy place for composition agents to include an\r\n"
  11785. "explanatory note to non-MIME conformant readers.\r\n"
  11786. "\r\n"
  11787. "\r\n"
  11788. "--simple boundary\r\n"
  11789. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11790. ": BAD...\r\n"
  11791. "\r\n"
  11792. "value1\r\n"
  11793. "--simple boundary\r\n"
  11794. "Content-Disposition: form-data; name=\"field2\"; "
  11795. "filename=\"example.txt\"\r\n"
  11796. "\r\n"
  11797. "value2\r\n"
  11798. "--simple boundary--\r\n"
  11799. "This is the epilogue. It is also to be ignored.\r\n";
  11800. std::string content_type =
  11801. R"(multipart/form-data; boundary="simple boundary")";
  11802. Client cli(HOST, PORT);
  11803. auto res = cli.Post("/post", body, content_type.c_str());
  11804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11805. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11806. }
  11807. TEST(MultipartFormDataTest, WithPreamble) {
  11808. Server svr;
  11809. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11810. res.set_content("ok", "text/plain");
  11811. });
  11812. thread t = thread([&] { svr.listen(HOST, PORT); });
  11813. auto se = detail::scope_exit([&] {
  11814. svr.stop();
  11815. t.join();
  11816. ASSERT_FALSE(svr.is_running());
  11817. });
  11818. svr.wait_until_ready();
  11819. const std::string body =
  11820. "This is the preamble. It is to be ignored, though it\r\n"
  11821. "is a handy place for composition agents to include an\r\n"
  11822. "explanatory note to non-MIME conformant readers.\r\n"
  11823. "\r\n"
  11824. "\r\n"
  11825. "--simple boundary\r\n"
  11826. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11827. "\r\n"
  11828. "value1\r\n"
  11829. "--simple boundary\r\n"
  11830. "Content-Disposition: form-data; name=\"field2\"; "
  11831. "filename=\"example.txt\"\r\n"
  11832. "\r\n"
  11833. "value2\r\n"
  11834. "--simple boundary--\r\n"
  11835. "This is the epilogue. It is also to be ignored.\r\n";
  11836. std::string content_type =
  11837. R"(multipart/form-data; boundary="simple boundary")";
  11838. Client cli(HOST, PORT);
  11839. auto res = cli.Post("/post", body, content_type.c_str());
  11840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11841. EXPECT_EQ(StatusCode::OK_200, res->status);
  11842. }
  11843. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11845. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11846. const ContentReader &content_reader) {
  11847. if (req.is_multipart_form_data()) {
  11848. std::vector<FormData> items;
  11849. content_reader(
  11850. [&](const FormData &file) {
  11851. items.push_back(file);
  11852. return true;
  11853. },
  11854. [&](const char *data, size_t data_length) {
  11855. items.back().content.append(data, data_length);
  11856. return true;
  11857. });
  11858. EXPECT_TRUE(std::string(items[0].name) == "document");
  11859. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11860. EXPECT_TRUE(items[0].filename == "2MB_data");
  11861. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11862. EXPECT_TRUE(items[1].name == "hello");
  11863. EXPECT_TRUE(items[1].content == "world");
  11864. EXPECT_TRUE(items[1].filename == "");
  11865. EXPECT_TRUE(items[1].content_type == "");
  11866. } else {
  11867. std::string body;
  11868. content_reader([&](const char *data, size_t data_length) {
  11869. body.append(data, data_length);
  11870. return true;
  11871. });
  11872. }
  11873. });
  11874. auto port = svr.bind_to_any_port("localhost");
  11875. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11876. auto se = detail::scope_exit([&] {
  11877. svr.stop();
  11878. t.join();
  11879. ASSERT_FALSE(svr.is_running());
  11880. });
  11881. svr.wait_until_ready();
  11882. {
  11883. std::string data(1024 * 1024 * 2, '.');
  11884. std::stringstream buffer;
  11885. buffer << data;
  11886. SSLClient cli("localhost", port);
  11887. cli.enable_server_certificate_verification(false);
  11888. UploadFormDataItems items{
  11889. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11890. {"hello", "world", "", ""},
  11891. };
  11892. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11894. ASSERT_EQ(StatusCode::OK_200, res->status);
  11895. }
  11896. }
  11897. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11898. std::string data(1024 * 1024 * 2, '&');
  11899. std::stringstream buffer;
  11900. buffer << data;
  11901. Client cli("https://localhost:8080");
  11902. UploadFormDataItems items{
  11903. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11904. {"hello", "world", "", ""},
  11905. };
  11906. for (const char &c : " \t\r\n") {
  11907. auto res =
  11908. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11909. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11910. ASSERT_FALSE(res);
  11911. }
  11912. }
  11913. TEST(MultipartFormDataTest, PutFormData) {
  11914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11915. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11916. const ContentReader &content_reader) {
  11917. if (req.is_multipart_form_data()) {
  11918. std::vector<FormData> items;
  11919. content_reader(
  11920. [&](const FormData &file) {
  11921. items.push_back(file);
  11922. return true;
  11923. },
  11924. [&](const char *data, size_t data_length) {
  11925. items.back().content.append(data, data_length);
  11926. return true;
  11927. });
  11928. EXPECT_TRUE(std::string(items[0].name) == "document");
  11929. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11930. EXPECT_TRUE(items[0].filename == "2MB_data");
  11931. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11932. EXPECT_TRUE(items[1].name == "hello");
  11933. EXPECT_TRUE(items[1].content == "world");
  11934. EXPECT_TRUE(items[1].filename == "");
  11935. EXPECT_TRUE(items[1].content_type == "");
  11936. } else {
  11937. std::string body;
  11938. content_reader([&](const char *data, size_t data_length) {
  11939. body.append(data, data_length);
  11940. return true;
  11941. });
  11942. }
  11943. });
  11944. auto port = svr.bind_to_any_port("localhost");
  11945. auto t = std::thread([&]() { svr.listen_after_bind(); });
  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. {
  11953. std::string data(1024 * 1024 * 2, '&');
  11954. std::stringstream buffer;
  11955. buffer << data;
  11956. SSLClient cli("localhost", port);
  11957. cli.enable_server_certificate_verification(false);
  11958. UploadFormDataItems items{
  11959. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11960. {"hello", "world", "", ""},
  11961. };
  11962. auto res = cli.Put("/put", items);
  11963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11964. ASSERT_EQ(StatusCode::OK_200, res->status);
  11965. }
  11966. }
  11967. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11969. svr.Put("/put_customboundary",
  11970. [&](const Request &req, const Response & /*res*/,
  11971. const ContentReader &content_reader) {
  11972. if (req.is_multipart_form_data()) {
  11973. std::vector<FormData> items;
  11974. content_reader(
  11975. [&](const FormData &file) {
  11976. items.push_back(file);
  11977. return true;
  11978. },
  11979. [&](const char *data, size_t data_length) {
  11980. items.back().content.append(data, data_length);
  11981. return true;
  11982. });
  11983. EXPECT_TRUE(std::string(items[0].name) == "document");
  11984. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11985. EXPECT_TRUE(items[0].filename == "2MB_data");
  11986. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11987. EXPECT_TRUE(items[1].name == "hello");
  11988. EXPECT_TRUE(items[1].content == "world");
  11989. EXPECT_TRUE(items[1].filename == "");
  11990. EXPECT_TRUE(items[1].content_type == "");
  11991. } else {
  11992. std::string body;
  11993. content_reader([&](const char *data, size_t data_length) {
  11994. body.append(data, data_length);
  11995. return true;
  11996. });
  11997. }
  11998. });
  11999. auto port = svr.bind_to_any_port("localhost");
  12000. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12001. auto se = detail::scope_exit([&] {
  12002. svr.stop();
  12003. t.join();
  12004. ASSERT_FALSE(svr.is_running());
  12005. });
  12006. svr.wait_until_ready();
  12007. {
  12008. std::string data(1024 * 1024 * 2, '&');
  12009. std::stringstream buffer;
  12010. buffer << data;
  12011. SSLClient cli("localhost", port);
  12012. cli.enable_server_certificate_verification(false);
  12013. UploadFormDataItems items{
  12014. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12015. {"hello", "world", "", ""},
  12016. };
  12017. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. ASSERT_EQ(StatusCode::OK_200, res->status);
  12020. }
  12021. }
  12022. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12023. std::string data(1024 * 1024 * 2, '&');
  12024. std::stringstream buffer;
  12025. buffer << data;
  12026. Client cli("https://localhost:8080");
  12027. cli.enable_server_certificate_verification(false);
  12028. UploadFormDataItems items{
  12029. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12030. {"hello", "world", "", ""},
  12031. };
  12032. for (const char &c : " \t\r\n") {
  12033. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12034. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12035. ASSERT_FALSE(res);
  12036. }
  12037. }
  12038. TEST(MultipartFormDataTest, AlternateFilename) {
  12039. auto handled = false;
  12040. Server svr;
  12041. svr.Post("/test", [&](const Request &req, Response &res) {
  12042. ASSERT_EQ(2u, req.form.files.size());
  12043. ASSERT_EQ(1u, req.form.fields.size());
  12044. // Test files
  12045. const auto &file1 = req.form.get_file("file1");
  12046. ASSERT_EQ("file1", file1.name);
  12047. ASSERT_EQ("A.txt", file1.filename);
  12048. ASSERT_EQ("text/plain", file1.content_type);
  12049. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12050. const auto &file2 = req.form.get_file("file2");
  12051. ASSERT_EQ("file2", file2.name);
  12052. ASSERT_EQ("a.html", file2.filename);
  12053. ASSERT_EQ("text/html", file2.content_type);
  12054. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12055. file2.content);
  12056. // Test text field
  12057. const auto &text = req.form.get_field("text");
  12058. ASSERT_EQ("text default", text);
  12059. res.set_content("ok", "text/plain");
  12060. handled = true;
  12061. });
  12062. thread t = thread([&] { svr.listen(HOST, PORT); });
  12063. auto se = detail::scope_exit([&] {
  12064. svr.stop();
  12065. t.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. ASSERT_TRUE(handled);
  12068. });
  12069. svr.wait_until_ready();
  12070. auto req = "POST /test HTTP/1.1\r\n"
  12071. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12072. "Content-Length: 399\r\n"
  12073. "\r\n"
  12074. "----------\r\n"
  12075. "Content-Disposition: form-data; name=\"text\"\r\n"
  12076. "\r\n"
  12077. "text default\r\n"
  12078. "----------\r\n"
  12079. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12080. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12081. "Content-Type: text/plain\r\n"
  12082. "\r\n"
  12083. "Content of a.txt.\r\n"
  12084. "\r\n"
  12085. "----------\r\n"
  12086. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12087. "\"a.html\"\r\n"
  12088. "Content-Type: text/html\r\n"
  12089. "\r\n"
  12090. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12091. "\r\n"
  12092. "------------\r\n";
  12093. ASSERT_TRUE(send_request(1, req));
  12094. }
  12095. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12096. auto handled = false;
  12097. Server svr;
  12098. svr.Post("/test", [&](const Request &req, Response &res) {
  12099. // Case-insensitive "utf-8''" prefix with a long value
  12100. const auto &file = req.form.get_file("file1");
  12101. ASSERT_EQ("file1", file.name);
  12102. // 8000 chars exercises both the Content-Disposition parser and the
  12103. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12104. // Prior to the fix, std::regex_match on this header would cause O(N)
  12105. // stack recursion in libstdc++, leading to SIGSEGV.
  12106. std::string expected_filename(8000, 'A');
  12107. ASSERT_EQ(expected_filename, file.filename);
  12108. res.set_content("ok", "text/plain");
  12109. handled = true;
  12110. });
  12111. thread t = thread([&] { svr.listen(HOST, PORT); });
  12112. auto se = detail::scope_exit([&] {
  12113. svr.stop();
  12114. t.join();
  12115. ASSERT_FALSE(svr.is_running());
  12116. ASSERT_TRUE(handled);
  12117. });
  12118. svr.wait_until_ready();
  12119. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12120. // Regression test for GHSA-qq6v-r583-3h69
  12121. std::string long_filename(8000, 'A');
  12122. std::string body = "----------\r\n"
  12123. "Content-Disposition: form-data; name=\"file1\"; "
  12124. "filename*=\"Utf-8''" +
  12125. long_filename +
  12126. "\"\r\n"
  12127. "\r\n"
  12128. "hello\r\n"
  12129. "------------\r\n";
  12130. auto req = "POST /test HTTP/1.1\r\n"
  12131. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12132. "Content-Length: " +
  12133. std::to_string(body.size()) + "\r\n\r\n" + body;
  12134. ASSERT_TRUE(send_request(1, req));
  12135. }
  12136. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12137. auto handled = false;
  12138. Server svr;
  12139. svr.Post("/test", [&](const Request &req, Response &) {
  12140. ASSERT_EQ(2u, req.form.fields.size());
  12141. const auto &text1 = req.form.get_field("text1");
  12142. ASSERT_EQ("text1", text1);
  12143. const auto &text2 = req.form.get_field("text2");
  12144. ASSERT_EQ("text2", text2);
  12145. handled = true;
  12146. });
  12147. thread t = thread([&] { svr.listen(HOST, PORT); });
  12148. auto se = detail::scope_exit([&] {
  12149. svr.stop();
  12150. t.join();
  12151. ASSERT_FALSE(svr.is_running());
  12152. ASSERT_TRUE(handled);
  12153. });
  12154. svr.wait_until_ready();
  12155. auto req = "POST /test HTTP/1.1\r\n"
  12156. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12157. "Content-Length: 146\r\n"
  12158. "\r\n----------\r\n"
  12159. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12160. "\r\n"
  12161. "text1"
  12162. "\r\n----------\r\n"
  12163. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12164. "\r\n"
  12165. "text2"
  12166. "\r\n------------";
  12167. std::string response;
  12168. ASSERT_TRUE(send_request(1, req, &response));
  12169. ASSERT_EQ("200", response.substr(9, 3));
  12170. }
  12171. TEST(MultipartFormDataTest, ContentLength) {
  12172. auto handled = false;
  12173. Server svr;
  12174. svr.Post("/test", [&](const Request &req, Response &) {
  12175. ASSERT_EQ(2u, req.form.fields.size());
  12176. const auto &text1 = req.form.get_field("text1");
  12177. ASSERT_EQ("text1", text1);
  12178. const auto &text2 = req.form.get_field("text2");
  12179. ASSERT_EQ("text2", text2);
  12180. handled = true;
  12181. });
  12182. thread t = thread([&] { svr.listen(HOST, PORT); });
  12183. auto se = detail::scope_exit([&] {
  12184. svr.stop();
  12185. t.join();
  12186. ASSERT_FALSE(svr.is_running());
  12187. ASSERT_TRUE(handled);
  12188. });
  12189. svr.wait_until_ready();
  12190. auto req = "POST /test HTTP/1.1\r\n"
  12191. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12192. "Content-Length: 167\r\n"
  12193. "\r\n----------\r\n"
  12194. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12195. "Content-Length: 5\r\n"
  12196. "\r\n"
  12197. "text1"
  12198. "\r\n----------\r\n"
  12199. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12200. "\r\n"
  12201. "text2"
  12202. "\r\n------------\r\n";
  12203. std::string response;
  12204. ASSERT_TRUE(send_request(1, req, &response));
  12205. ASSERT_EQ("200", response.substr(9, 3));
  12206. }
  12207. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12208. auto handled = false;
  12209. Server svr;
  12210. svr.Post("/test", [&](const Request &req, Response &) {
  12211. ASSERT_EQ(2u, req.form.fields.size());
  12212. const auto &text1 = req.form.get_field("text1");
  12213. ASSERT_EQ("text1", text1);
  12214. // TODO: Add header access for text fields if needed
  12215. const auto &text2 = req.form.get_field("text2");
  12216. ASSERT_EQ("text2", text2);
  12217. // TODO: Header access for text fields needs to be implemented
  12218. // auto &headers = it->second.headers;
  12219. // ASSERT_EQ(3U, headers.size());
  12220. // auto custom_header = headers.find("x-whatever");
  12221. // ASSERT_TRUE(custom_header != headers.end());
  12222. // ASSERT_NE("customvalue", custom_header->second);
  12223. // ASSERT_EQ("CustomValue", custom_header->second);
  12224. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12225. handled = true;
  12226. });
  12227. thread t = thread([&] { svr.listen(HOST, PORT); });
  12228. auto se = detail::scope_exit([&] {
  12229. svr.stop();
  12230. t.join();
  12231. ASSERT_FALSE(svr.is_running());
  12232. ASSERT_TRUE(handled);
  12233. });
  12234. svr.wait_until_ready();
  12235. auto req = "POST /test HTTP/1.1\r\n"
  12236. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12237. "Content-Length: 232\r\n"
  12238. "\r\n----------\r\n"
  12239. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12240. "Content-Length: 5\r\n"
  12241. "X-Test: 1\r\n"
  12242. "\r\n"
  12243. "text1"
  12244. "\r\n----------\r\n"
  12245. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12246. "Content-Type: text/plain\r\n"
  12247. "X-Whatever: CustomValue\r\n"
  12248. "\r\n"
  12249. "text2"
  12250. "\r\n------------\r\n"
  12251. "That should be disregarded. Not even read";
  12252. std::string response;
  12253. ASSERT_TRUE(send_request(1, req, &response));
  12254. ASSERT_EQ("200", response.substr(9, 3));
  12255. }
  12256. TEST(MultipartFormDataTest, LargeHeader) {
  12257. auto handled = false;
  12258. Server svr;
  12259. svr.Post("/test", [&](const Request &req, Response &) {
  12260. ASSERT_EQ(1u, req.form.fields.size());
  12261. const auto &text = req.form.get_field("name1");
  12262. ASSERT_EQ("text1", text);
  12263. handled = true;
  12264. });
  12265. thread t = thread([&] { svr.listen(HOST, PORT); });
  12266. auto se = detail::scope_exit([&] {
  12267. svr.stop();
  12268. t.join();
  12269. ASSERT_FALSE(svr.is_running());
  12270. ASSERT_TRUE(handled);
  12271. });
  12272. svr.wait_until_ready();
  12273. auto boundary = std::string("cpp-httplib-multipart-data");
  12274. std::string content = "--" + boundary +
  12275. "\r\n"
  12276. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12277. "\r\n"
  12278. "text1\r\n"
  12279. "--" +
  12280. boundary + "--\r\n";
  12281. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12282. "Content-Type: multipart/form-data;boundary=" +
  12283. boundary +
  12284. "\r\n"
  12285. "Content-Length: " +
  12286. std::to_string(content.size()) +
  12287. "\r\n"
  12288. "Dummy-Header: ";
  12289. std::string header_suffix = "\r\n"
  12290. "\r\n";
  12291. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12292. size_t header_dummy_size =
  12293. read_buff_size -
  12294. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12295. auto header_dummy = std::string(header_dummy_size, '@');
  12296. auto req = header_prefix + header_dummy + header_suffix + content;
  12297. std::string response;
  12298. ASSERT_TRUE(send_request(1, req, &response));
  12299. ASSERT_EQ("200", response.substr(9, 3));
  12300. }
  12301. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12302. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12303. // (not chunked Transfer-Encoding) after the streaming refactor.
  12304. auto handled = false;
  12305. Server svr;
  12306. svr.Post("/upload", [&](const Request &req, Response &res) {
  12307. auto cl_it = req.headers.find("Content-Length");
  12308. EXPECT_TRUE(cl_it != req.headers.end());
  12309. auto te_it = req.headers.find("Transfer-Encoding");
  12310. EXPECT_TRUE(te_it == req.headers.end());
  12311. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12312. res.set_content("ok", "text/plain");
  12313. handled = true;
  12314. });
  12315. auto port = svr.bind_to_any_port(HOST);
  12316. auto t = thread([&] { svr.listen_after_bind(); });
  12317. auto se = detail::scope_exit([&] {
  12318. svr.stop();
  12319. t.join();
  12320. ASSERT_FALSE(svr.is_running());
  12321. ASSERT_TRUE(handled);
  12322. });
  12323. svr.wait_until_ready();
  12324. UploadFormDataItems items = {
  12325. {"field1", "hello", "", "text/plain"},
  12326. {"file1", "world", "test.txt", "application/octet-stream"},
  12327. };
  12328. Client cli(HOST, port);
  12329. auto res = cli.Post("/upload", {}, items);
  12330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12331. EXPECT_EQ(StatusCode::OK_200, res->status);
  12332. }
  12333. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12334. // Verify that make_multipart_content_provider coalesces many small segments
  12335. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12336. constexpr size_t kItemCount = 1000;
  12337. UploadFormDataItems items;
  12338. items.reserve(kItemCount);
  12339. for (size_t i = 0; i < kItemCount; i++) {
  12340. items.push_back(
  12341. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12342. }
  12343. const std::string boundary = "----test-boundary";
  12344. auto content_length = detail::get_multipart_content_length(items, boundary);
  12345. auto provider = detail::make_multipart_content_provider(items, boundary);
  12346. // Drive the provider the same way write_content_with_progress does
  12347. size_t write_count = 0;
  12348. size_t total_bytes = 0;
  12349. DataSink sink;
  12350. size_t offset = 0;
  12351. sink.write = [&](const char *d, size_t l) -> bool {
  12352. (void)d;
  12353. write_count++;
  12354. total_bytes += l;
  12355. offset += l;
  12356. return true;
  12357. };
  12358. sink.is_writable = []() -> bool { return true; };
  12359. while (offset < content_length) {
  12360. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12361. }
  12362. EXPECT_EQ(content_length, total_bytes);
  12363. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12364. // With buffering into 64KB blocks, write_count should be much smaller.
  12365. auto segment_count = 3 * kItemCount + 1;
  12366. EXPECT_LT(write_count, segment_count / 10);
  12367. }
  12368. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12369. // Integration test: send many UploadFormDataItems and verify the server
  12370. // receives all of them correctly (#2410).
  12371. constexpr size_t kItemCount = 500;
  12372. auto handled = false;
  12373. Server svr;
  12374. svr.Post("/upload", [&](const Request &req, Response &res) {
  12375. EXPECT_EQ(kItemCount, req.form.fields.size());
  12376. for (size_t i = 0; i < kItemCount; i++) {
  12377. auto key = "field" + std::to_string(i);
  12378. auto val = "value" + std::to_string(i);
  12379. auto it = req.form.fields.find(key);
  12380. if (it != req.form.fields.end()) {
  12381. EXPECT_EQ(val, it->second.content);
  12382. } else {
  12383. ADD_FAILURE() << "Missing field: " << key;
  12384. }
  12385. }
  12386. res.set_content("ok", "text/plain");
  12387. handled = true;
  12388. });
  12389. auto port = svr.bind_to_any_port(HOST);
  12390. auto t = thread([&] { svr.listen_after_bind(); });
  12391. auto se = detail::scope_exit([&] {
  12392. svr.stop();
  12393. t.join();
  12394. ASSERT_FALSE(svr.is_running());
  12395. ASSERT_TRUE(handled);
  12396. });
  12397. svr.wait_until_ready();
  12398. UploadFormDataItems items;
  12399. items.reserve(kItemCount);
  12400. for (size_t i = 0; i < kItemCount; i++) {
  12401. items.push_back(
  12402. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12403. }
  12404. Client cli(HOST, port);
  12405. auto res = cli.Post("/upload", items);
  12406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12407. EXPECT_EQ(StatusCode::OK_200, res->status);
  12408. }
  12409. TEST(MultipartFormDataTest, MakeFileProvider) {
  12410. // Verify make_file_provider sends a file's contents correctly.
  12411. const std::string file_content(4096, 'Z');
  12412. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12413. {
  12414. std::ofstream ofs(tmp_path, std::ios::binary);
  12415. ofs.write(file_content.data(),
  12416. static_cast<std::streamsize>(file_content.size()));
  12417. }
  12418. auto handled = false;
  12419. Server svr;
  12420. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12421. const ContentReader &content_reader) {
  12422. ASSERT_TRUE(req.is_multipart_form_data());
  12423. std::vector<FormData> items;
  12424. content_reader(
  12425. [&](const FormData &file) {
  12426. items.push_back(file);
  12427. return true;
  12428. },
  12429. [&](const char *data, size_t data_length) {
  12430. items.back().content.append(data, data_length);
  12431. return true;
  12432. });
  12433. ASSERT_EQ(1u, items.size());
  12434. EXPECT_EQ("myfile", items[0].name);
  12435. EXPECT_EQ("data.bin", items[0].filename);
  12436. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12437. EXPECT_EQ(file_content, items[0].content);
  12438. handled = true;
  12439. });
  12440. auto port = svr.bind_to_any_port(HOST);
  12441. auto t = thread([&] { svr.listen_after_bind(); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. ASSERT_TRUE(handled);
  12447. std::remove(tmp_path.c_str());
  12448. });
  12449. svr.wait_until_ready();
  12450. FormDataProviderItems providers;
  12451. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12452. "application/octet-stream"));
  12453. Client cli(HOST, port);
  12454. auto res = cli.Post("/upload", {}, {}, providers);
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12456. EXPECT_EQ(StatusCode::OK_200, res->status);
  12457. }
  12458. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12459. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12460. // (100) headers is rejected with a 400 Bad Request response.
  12461. Server svr;
  12462. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12463. res.set_content("ok", "text/plain");
  12464. });
  12465. thread t = thread([&] { svr.listen(HOST, PORT); });
  12466. auto se = detail::scope_exit([&] {
  12467. svr.stop();
  12468. t.join();
  12469. ASSERT_FALSE(svr.is_running());
  12470. });
  12471. svr.wait_until_ready();
  12472. // Build a multipart part with 101 custom headers (exceeding
  12473. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12474. std::stringstream body;
  12475. body << "--simpleboundary\r\n"
  12476. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12477. for (int i = 0; i < 101; i++) {
  12478. body << "X-Custom-Header-" << i << ": value\r\n";
  12479. }
  12480. body << "\r\n"
  12481. << "value1\r\n"
  12482. << "--simpleboundary--\r\n";
  12483. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12484. Client cli(HOST, PORT);
  12485. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12488. }
  12489. TEST(MakeFileBodyTest, Basic) {
  12490. const std::string file_content(4096, 'Z');
  12491. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12492. {
  12493. std::ofstream ofs(tmp_path, std::ios::binary);
  12494. ofs.write(file_content.data(),
  12495. static_cast<std::streamsize>(file_content.size()));
  12496. }
  12497. auto handled = false;
  12498. Server svr;
  12499. svr.Post("/upload", [&](const Request &req, Response &res) {
  12500. EXPECT_EQ(file_content, req.body);
  12501. handled = true;
  12502. res.status = StatusCode::OK_200;
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. auto t = thread([&] { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. ASSERT_TRUE(handled);
  12511. std::remove(tmp_path.c_str());
  12512. });
  12513. svr.wait_until_ready();
  12514. auto fb = make_file_body(tmp_path);
  12515. ASSERT_GT(fb.first, 0u);
  12516. Client cli(HOST, port);
  12517. auto res =
  12518. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12520. EXPECT_EQ(StatusCode::OK_200, res->status);
  12521. }
  12522. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12523. static constexpr unsigned int number_of_tasks{1000000};
  12524. std::atomic_uint count{0};
  12525. std::unique_ptr<TaskQueue> task_queue{
  12526. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12527. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12528. auto queued = task_queue->enqueue(
  12529. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12530. EXPECT_TRUE(queued);
  12531. }
  12532. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12533. task_queue->shutdown();
  12534. #else
  12535. EXPECT_NO_THROW(task_queue->shutdown());
  12536. #endif
  12537. EXPECT_EQ(number_of_tasks, count.load());
  12538. }
  12539. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12540. static constexpr unsigned int number_of_tasks{1000000};
  12541. static constexpr unsigned int qlimit{2};
  12542. unsigned int queued_count{0};
  12543. std::atomic_uint count{0};
  12544. std::unique_ptr<TaskQueue> task_queue{
  12545. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12546. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12547. if (task_queue->enqueue(
  12548. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12549. queued_count++;
  12550. }
  12551. }
  12552. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12553. task_queue->shutdown();
  12554. #else
  12555. EXPECT_NO_THROW(task_queue->shutdown());
  12556. #endif
  12557. EXPECT_EQ(queued_count, count.load());
  12558. EXPECT_TRUE(queued_count <= number_of_tasks);
  12559. EXPECT_TRUE(queued_count >= qlimit);
  12560. }
  12561. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12562. // Use a short idle timeout so a dynamic thread spawns, times out and
  12563. // exits during the test, and the pool keeps working afterwards.
  12564. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12565. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12566. /*idle_timeout_sec=*/1}};
  12567. std::atomic_uint count{0};
  12568. std::condition_variable cv;
  12569. std::mutex mtx;
  12570. bool release = false;
  12571. // Block the base thread so the second task spawns a dynamic thread.
  12572. EXPECT_TRUE(task_queue->enqueue([&] {
  12573. std::unique_lock<std::mutex> lock(mtx);
  12574. while (!release) {
  12575. cv.wait(lock);
  12576. }
  12577. count++;
  12578. }));
  12579. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12580. // Let the dynamic thread finish its task and exceed the idle timeout.
  12581. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12582. {
  12583. std::unique_lock<std::mutex> lock(mtx);
  12584. release = true;
  12585. }
  12586. cv.notify_all();
  12587. // The pool must still accept and run tasks after the dynamic thread exited.
  12588. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12589. task_queue->shutdown();
  12590. EXPECT_EQ(3u, count.load());
  12591. }
  12592. TEST(TaskQueueTest, MaxQueuedRequests) {
  12593. static constexpr unsigned int qlimit{3};
  12594. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12595. std::condition_variable sem_cv;
  12596. std::mutex sem_mtx;
  12597. int credits = 0;
  12598. bool queued;
  12599. /* Fill up the queue with tasks that will block until we give them credits to
  12600. * complete. */
  12601. for (unsigned int n = 0; n <= qlimit;) {
  12602. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12603. std::unique_lock<std::mutex> lock(sem_mtx);
  12604. while (credits <= 0) {
  12605. sem_cv.wait(lock);
  12606. }
  12607. /* Consume the credit and signal the test code if they are all gone. */
  12608. if (--credits == 0) { sem_cv.notify_one(); }
  12609. });
  12610. if (n < qlimit) {
  12611. /* The first qlimit enqueues must succeed. */
  12612. EXPECT_TRUE(queued);
  12613. } else {
  12614. /* The last one will succeed only when the worker thread
  12615. * starts and dequeues the first blocking task. Although
  12616. * not necessary for the correctness of this test, we sleep for
  12617. * a short while to avoid busy waiting. */
  12618. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12619. }
  12620. if (queued) { n++; }
  12621. }
  12622. /* Further enqueues must fail since the queue is full. */
  12623. for (auto i = 0; i < 4; i++) {
  12624. queued = task_queue->enqueue([] {});
  12625. EXPECT_FALSE(queued);
  12626. }
  12627. /* Give the credits to allow the previous tasks to complete. */
  12628. {
  12629. std::unique_lock<std::mutex> lock(sem_mtx);
  12630. credits += qlimit + 1;
  12631. }
  12632. sem_cv.notify_all();
  12633. /* Wait for all the credits to be consumed. */
  12634. {
  12635. std::unique_lock<std::mutex> lock(sem_mtx);
  12636. while (credits > 0) {
  12637. sem_cv.wait(lock);
  12638. }
  12639. }
  12640. /* Check that we are able again to enqueue at least qlimit tasks. */
  12641. for (unsigned int i = 0; i < qlimit; i++) {
  12642. queued = task_queue->enqueue([] {});
  12643. EXPECT_TRUE(queued);
  12644. }
  12645. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12646. task_queue->shutdown();
  12647. #else
  12648. EXPECT_NO_THROW(task_queue->shutdown());
  12649. #endif
  12650. }
  12651. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12652. Server svr;
  12653. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12654. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12655. });
  12656. svr.Get("/hello", [](const Request &req, Response &res) {
  12657. res.set_content(req.get_param_value("key"), "text/plain");
  12658. });
  12659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12660. auto se = detail::scope_exit([&] {
  12661. svr.stop();
  12662. thread.join();
  12663. ASSERT_FALSE(svr.is_running());
  12664. });
  12665. svr.wait_until_ready();
  12666. {
  12667. Client cli(HOST, PORT);
  12668. cli.set_follow_location(true);
  12669. auto res = cli.Get("/");
  12670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12671. EXPECT_EQ(StatusCode::OK_200, res->status);
  12672. EXPECT_EQ("val&key2=val2", res->body);
  12673. }
  12674. }
  12675. #endif
  12676. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12677. Server svr;
  12678. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12679. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12680. });
  12681. svr.Get("/hello", [](const Request &req, Response &res) {
  12682. res.set_content(req.get_param_value("key"), "text/plain");
  12683. });
  12684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12685. auto se = detail::scope_exit([&] {
  12686. svr.stop();
  12687. thread.join();
  12688. ASSERT_FALSE(svr.is_running());
  12689. });
  12690. svr.wait_until_ready();
  12691. {
  12692. Client cli(HOST, PORT);
  12693. cli.set_follow_location(true);
  12694. auto res = cli.Get("/");
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12698. }
  12699. }
  12700. TEST(RedirectTest, RedirectWithPlusInPath) {
  12701. Server svr;
  12702. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12703. res.set_redirect("/a+b");
  12704. });
  12705. // Route pattern uses regex; escape + as \\+
  12706. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12707. res.set_content(req.path, "text/plain");
  12708. });
  12709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12710. auto se = detail::scope_exit([&] {
  12711. svr.stop();
  12712. thread.join();
  12713. ASSERT_FALSE(svr.is_running());
  12714. });
  12715. svr.wait_until_ready();
  12716. {
  12717. Client cli(HOST, PORT);
  12718. cli.set_follow_location(true);
  12719. auto res = cli.Get("/");
  12720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12721. EXPECT_EQ(StatusCode::OK_200, res->status);
  12722. EXPECT_EQ("/a+b", res->body);
  12723. }
  12724. }
  12725. #ifdef CPPHTTPLIB_SSL_ENABLED
  12726. TEST(RedirectTest, Issue2185_Online) {
  12727. SSLClient client("github.com");
  12728. client.set_follow_location(true);
  12729. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12730. "Coollab-Windows.zip");
  12731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12732. EXPECT_EQ(StatusCode::OK_200, res->status);
  12733. EXPECT_EQ(9920427U, res->body.size());
  12734. }
  12735. #endif
  12736. TEST(VulnerabilityTest, CRLFInjection) {
  12737. Server svr;
  12738. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12739. res.set_content("Hello 1", "text/plain");
  12740. });
  12741. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12742. res.set_content("Hello 2", "text/plain");
  12743. });
  12744. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12745. res.set_content("Hello 3", "text/plain");
  12746. });
  12747. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12748. res.set_content("Hello 4", "text/plain");
  12749. });
  12750. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12751. for (const auto &x : req.headers) {
  12752. auto key = x.first;
  12753. EXPECT_STRNE("evil", key.c_str());
  12754. }
  12755. });
  12756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12757. auto se = detail::scope_exit([&] {
  12758. svr.stop();
  12759. thread.join();
  12760. ASSERT_FALSE(svr.is_running());
  12761. });
  12762. svr.wait_until_ready();
  12763. {
  12764. Client cli(HOST, PORT);
  12765. cli.Post("/test1", "A=B",
  12766. "application/x-www-form-urlencoded\r\nevil: hello1");
  12767. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12768. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12769. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12770. }
  12771. }
  12772. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12773. auto server_thread = std::thread([] {
  12774. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12775. default_socket_options(srv);
  12776. sockaddr_in addr{};
  12777. addr.sin_family = AF_INET;
  12778. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12779. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12780. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12781. ::listen(srv, 1);
  12782. sockaddr_in cli_addr{};
  12783. socklen_t cli_len = sizeof(cli_addr);
  12784. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12785. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12786. std::string buf_all;
  12787. char buf[2048];
  12788. ssize_t n;
  12789. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12790. buf_all.append(buf, static_cast<size_t>(n));
  12791. size_t pos;
  12792. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12793. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12794. auto e = request_block.find("\r\n");
  12795. if (e != std::string::npos) {
  12796. auto request_line = request_block.substr(0, e);
  12797. std::string msg =
  12798. "CRLF injection detected in request line: '" + request_line + "'";
  12799. EXPECT_FALSE(true) << msg;
  12800. }
  12801. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12802. ::send(cli,
  12803. #ifdef _WIN32
  12804. static_cast<const char *>(resp.c_str()),
  12805. static_cast<int>(resp.size()),
  12806. #else
  12807. resp.c_str(), resp.size(),
  12808. #endif
  12809. 0);
  12810. buf_all.erase(0, pos + 4);
  12811. }
  12812. }
  12813. detail::close_socket(cli);
  12814. detail::close_socket(srv);
  12815. });
  12816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12817. auto cli = Client("127.0.0.1", PORT + 1);
  12818. auto headers = Headers{
  12819. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12820. {"Connection", "keep-alive"}};
  12821. auto res = cli.Get("/hi", headers);
  12822. EXPECT_FALSE(res);
  12823. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12824. server_thread.join();
  12825. }
  12826. TEST(PathParamsTest, StaticMatch) {
  12827. const auto pattern = "/users/all";
  12828. detail::PathParamsMatcher matcher(pattern);
  12829. Request request;
  12830. request.path = "/users/all";
  12831. ASSERT_TRUE(matcher.match(request));
  12832. std::unordered_map<std::string, std::string> expected_params = {};
  12833. EXPECT_EQ(request.path_params, expected_params);
  12834. }
  12835. TEST(PathParamsTest, StaticMismatch) {
  12836. const auto pattern = "/users/all";
  12837. detail::PathParamsMatcher matcher(pattern);
  12838. Request request;
  12839. request.path = "/users/1";
  12840. ASSERT_FALSE(matcher.match(request));
  12841. }
  12842. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12843. const auto pattern = "/users/:id/subscriptions";
  12844. detail::PathParamsMatcher matcher(pattern);
  12845. Request request;
  12846. request.path = "/users/42/subscriptions";
  12847. ASSERT_TRUE(matcher.match(request));
  12848. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12849. EXPECT_EQ(request.path_params, expected_params);
  12850. }
  12851. TEST(PathParamsTest, SingleParamInTheEnd) {
  12852. const auto pattern = "/users/:id";
  12853. detail::PathParamsMatcher matcher(pattern);
  12854. Request request;
  12855. request.path = "/users/24";
  12856. ASSERT_TRUE(matcher.match(request));
  12857. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12858. EXPECT_EQ(request.path_params, expected_params);
  12859. }
  12860. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12861. const auto pattern = "/users/:id/";
  12862. detail::PathParamsMatcher matcher(pattern);
  12863. Request request;
  12864. request.path = "/users/42/";
  12865. ASSERT_TRUE(matcher.match(request));
  12866. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12867. EXPECT_EQ(request.path_params, expected_params);
  12868. }
  12869. TEST(PathParamsTest, EmptyParam) {
  12870. const auto pattern = "/users/:id/";
  12871. detail::PathParamsMatcher matcher(pattern);
  12872. Request request;
  12873. request.path = "/users//";
  12874. ASSERT_TRUE(matcher.match(request));
  12875. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12876. EXPECT_EQ(request.path_params, expected_params);
  12877. }
  12878. TEST(PathParamsTest, FragmentMismatch) {
  12879. const auto pattern = "/users/:id/";
  12880. detail::PathParamsMatcher matcher(pattern);
  12881. Request request;
  12882. request.path = "/admins/24/";
  12883. ASSERT_FALSE(matcher.match(request));
  12884. }
  12885. TEST(PathParamsTest, ExtraFragments) {
  12886. const auto pattern = "/users/:id";
  12887. detail::PathParamsMatcher matcher(pattern);
  12888. Request request;
  12889. request.path = "/users/42/subscriptions";
  12890. ASSERT_FALSE(matcher.match(request));
  12891. }
  12892. TEST(PathParamsTest, MissingTrailingParam) {
  12893. const auto pattern = "/users/:id";
  12894. detail::PathParamsMatcher matcher(pattern);
  12895. Request request;
  12896. request.path = "/users";
  12897. ASSERT_FALSE(matcher.match(request));
  12898. }
  12899. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12900. const auto pattern = "/users/:id/subscriptions";
  12901. detail::PathParamsMatcher matcher(pattern);
  12902. Request request;
  12903. request.path = "/users/subscriptions";
  12904. ASSERT_FALSE(matcher.match(request));
  12905. }
  12906. TEST(PathParamsTest, MultipleParams) {
  12907. const auto pattern = "/users/:userid/subscriptions/:subid";
  12908. detail::PathParamsMatcher matcher(pattern);
  12909. Request request;
  12910. request.path = "/users/42/subscriptions/2";
  12911. ASSERT_TRUE(matcher.match(request));
  12912. std::unordered_map<std::string, std::string> expected_params = {
  12913. {"userid", "42"}, {"subid", "2"}};
  12914. EXPECT_EQ(request.path_params, expected_params);
  12915. }
  12916. TEST(PathParamsTest, SequenceOfParams) {
  12917. const auto pattern = "/values/:x/:y/:z";
  12918. detail::PathParamsMatcher matcher(pattern);
  12919. Request request;
  12920. request.path = "/values/1/2/3";
  12921. ASSERT_TRUE(matcher.match(request));
  12922. std::unordered_map<std::string, std::string> expected_params = {
  12923. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12924. EXPECT_EQ(request.path_params, expected_params);
  12925. }
  12926. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12927. const auto pattern = "/prefix:suffix";
  12928. detail::PathParamsMatcher matcher(pattern);
  12929. Request request;
  12930. request.path = "/prefix:suffix";
  12931. ASSERT_TRUE(matcher.match(request));
  12932. const std::unordered_map<std::string, std::string> expected_params = {};
  12933. EXPECT_EQ(request.path_params, expected_params);
  12934. }
  12935. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  12936. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  12937. // calling thread's stack on a long enough path for a quantified pattern;
  12938. // RegexMatcher must refuse to run regex matching on paths beyond
  12939. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  12940. detail::RegexMatcher matcher("/files/(.*)");
  12941. Request within_limit;
  12942. within_limit.path = "/files/" + std::string(10, 'A');
  12943. EXPECT_TRUE(matcher.match(within_limit));
  12944. Request over_limit;
  12945. over_limit.path =
  12946. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  12947. EXPECT_FALSE(matcher.match(over_limit));
  12948. }
  12949. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  12950. Server svr;
  12951. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  12952. res.set_content("ok", "text/plain");
  12953. });
  12954. auto port = svr.bind_to_any_port(HOST);
  12955. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12956. auto se = detail::scope_exit([&] {
  12957. svr.stop();
  12958. thread.join();
  12959. ASSERT_FALSE(svr.is_running());
  12960. });
  12961. svr.wait_until_ready();
  12962. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  12963. // request URI limit; this used to be able to crash the process.
  12964. std::string path =
  12965. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  12966. std::string req = "GET " + path +
  12967. " HTTP/1.1\r\n"
  12968. "Host: " +
  12969. std::string(HOST) + ":" + std::to_string(port) +
  12970. "\r\n"
  12971. "Connection: close\r\n"
  12972. "\r\n";
  12973. std::string response;
  12974. ASSERT_TRUE(send_request(5, req, &response, port));
  12975. EXPECT_NE(std::string::npos, response.find("404"));
  12976. }
  12977. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  12978. Server svr;
  12979. auto handler = [](const Request & /*req*/, Response &res) {
  12980. res.set_content("hit", "text/plain");
  12981. };
  12982. // No regex metacharacter, so this one is compared literally
  12983. svr.Get("/literal/route", handler);
  12984. // '.' is a regex metacharacter, so this one must keep regex semantics
  12985. svr.Get("/a.c", handler);
  12986. auto port = svr.bind_to_any_port(HOST);
  12987. std::thread t([&]() { svr.listen_after_bind(); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. ASSERT_FALSE(svr.is_running());
  12992. });
  12993. svr.wait_until_ready();
  12994. Client cli(HOST, port);
  12995. struct {
  12996. const char *path;
  12997. int status;
  12998. } cases[] = {
  12999. {"/literal/route", StatusCode::OK_200},
  13000. {"/literal/routes", StatusCode::NotFound_404},
  13001. {"/literal/rout", StatusCode::NotFound_404},
  13002. {"/abc", StatusCode::OK_200},
  13003. {"/a.c", StatusCode::OK_200},
  13004. };
  13005. for (const auto &x : cases) {
  13006. auto res = cli.Get(x.path);
  13007. ASSERT_TRUE(res) << x.path;
  13008. EXPECT_EQ(x.status, res->status) << x.path;
  13009. }
  13010. }
  13011. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13012. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13013. // from exhausting the stack, so it must only constrain routes that actually
  13014. // run a regular expression. A literal route is matched by comparison and
  13015. // stays usable at any length.
  13016. Server svr;
  13017. const std::string pattern =
  13018. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13019. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13020. res.set_content("hit", "text/plain");
  13021. });
  13022. auto port = svr.bind_to_any_port(HOST);
  13023. std::thread t([&]() { svr.listen_after_bind(); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. ASSERT_FALSE(svr.is_running());
  13028. });
  13029. svr.wait_until_ready();
  13030. Client cli(HOST, port);
  13031. auto res = cli.Get(pattern);
  13032. ASSERT_TRUE(res);
  13033. EXPECT_EQ(StatusCode::OK_200, res->status);
  13034. }
  13035. TEST(ParseUrlTest, VariousPatterns) {
  13036. {
  13037. detail::UrlComponents uc;
  13038. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13039. EXPECT_EQ("http", uc.scheme);
  13040. EXPECT_EQ("example.com", uc.host);
  13041. EXPECT_EQ("8080", uc.port);
  13042. EXPECT_EQ("/path", uc.path);
  13043. EXPECT_EQ("?q=1", uc.query);
  13044. }
  13045. {
  13046. detail::UrlComponents uc;
  13047. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13048. EXPECT_EQ("https", uc.scheme);
  13049. EXPECT_EQ("example.com", uc.host);
  13050. EXPECT_TRUE(uc.port.empty());
  13051. EXPECT_EQ("/path", uc.path);
  13052. }
  13053. {
  13054. detail::UrlComponents uc;
  13055. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13056. EXPECT_EQ("::1", uc.host);
  13057. EXPECT_EQ("8080", uc.port);
  13058. EXPECT_EQ("/path", uc.path);
  13059. }
  13060. {
  13061. detail::UrlComponents uc;
  13062. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13063. }
  13064. {
  13065. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13066. // the path while the connection still targets the bracketed host.
  13067. detail::UrlComponents uc;
  13068. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13069. }
  13070. {
  13071. detail::UrlComponents uc;
  13072. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13073. }
  13074. {
  13075. detail::UrlComponents uc;
  13076. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13077. EXPECT_EQ("::1", uc.host);
  13078. EXPECT_TRUE(uc.port.empty());
  13079. EXPECT_EQ("/path", uc.path);
  13080. }
  13081. {
  13082. detail::UrlComponents uc;
  13083. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13084. EXPECT_TRUE(uc.scheme.empty());
  13085. EXPECT_EQ("example.com", uc.host);
  13086. EXPECT_EQ("/path", uc.path);
  13087. EXPECT_EQ("?q=1", uc.query);
  13088. }
  13089. {
  13090. detail::UrlComponents uc;
  13091. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13092. EXPECT_TRUE(uc.host.empty());
  13093. EXPECT_EQ("/path", uc.path);
  13094. EXPECT_EQ("?q=1", uc.query);
  13095. }
  13096. {
  13097. detail::UrlComponents uc;
  13098. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13099. EXPECT_EQ("example.com", uc.host);
  13100. EXPECT_EQ("8080", uc.port);
  13101. }
  13102. {
  13103. // Unix socket path — must not be parsed as host
  13104. detail::UrlComponents uc;
  13105. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13106. EXPECT_TRUE(uc.host.empty());
  13107. }
  13108. {
  13109. detail::UrlComponents uc;
  13110. ASSERT_TRUE(detail::parse_url("", uc));
  13111. EXPECT_TRUE(uc.host.empty());
  13112. EXPECT_TRUE(uc.path.empty());
  13113. }
  13114. {
  13115. detail::UrlComponents uc;
  13116. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13117. }
  13118. {
  13119. detail::UrlComponents uc;
  13120. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13121. }
  13122. {
  13123. // Accepted by parse_url; callers restrict to http/https
  13124. detail::UrlComponents uc;
  13125. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13126. EXPECT_EQ("ftp", uc.scheme);
  13127. }
  13128. {
  13129. detail::UrlComponents uc;
  13130. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13131. }
  13132. {
  13133. detail::UrlComponents uc;
  13134. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13135. }
  13136. }
  13137. TEST(ParseUrlTest, FragmentHandling) {
  13138. {
  13139. detail::UrlComponents uc;
  13140. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13141. EXPECT_EQ("/path", uc.path);
  13142. EXPECT_TRUE(uc.query.empty());
  13143. }
  13144. {
  13145. detail::UrlComponents uc;
  13146. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13147. EXPECT_TRUE(uc.path.empty());
  13148. EXPECT_TRUE(uc.query.empty());
  13149. }
  13150. }
  13151. TEST(ParseUrlTest, UserinfoHandling) {
  13152. // Userinfo with @ but no colon — host includes @
  13153. detail::UrlComponents uc;
  13154. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13155. EXPECT_EQ("user@host.com", uc.host);
  13156. EXPECT_EQ("/path", uc.path);
  13157. }
  13158. TEST(ParseUrlTest, IPv6EdgeCases) {
  13159. {
  13160. detail::UrlComponents uc;
  13161. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13162. EXPECT_TRUE(uc.scheme.empty());
  13163. EXPECT_EQ("::1", uc.host);
  13164. EXPECT_EQ("8080", uc.port);
  13165. }
  13166. {
  13167. // Zone ID '%25' is not in [a-fA-F0-9:]
  13168. detail::UrlComponents uc;
  13169. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13170. }
  13171. }
  13172. TEST(ParseUrlTest, SchemeEdgeCases) {
  13173. {
  13174. detail::UrlComponents uc;
  13175. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13176. }
  13177. {
  13178. detail::UrlComponents uc;
  13179. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13180. }
  13181. {
  13182. detail::UrlComponents uc;
  13183. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13184. }
  13185. }
  13186. TEST(ParseUrlTest, PortEdgeCases) {
  13187. {
  13188. detail::UrlComponents uc;
  13189. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13190. EXPECT_TRUE(uc.port.empty());
  13191. EXPECT_EQ("/path", uc.path);
  13192. }
  13193. {
  13194. // parse_url accepts any port string; validation is done by parse_port
  13195. detail::UrlComponents uc;
  13196. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13197. EXPECT_EQ("abc", uc.port);
  13198. }
  13199. }
  13200. TEST(ParseUrlTest, WebSocketPatterns) {
  13201. {
  13202. detail::UrlComponents uc;
  13203. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13204. EXPECT_EQ("ws", uc.scheme);
  13205. EXPECT_EQ("echo.example.com", uc.host);
  13206. EXPECT_EQ("8080", uc.port);
  13207. EXPECT_EQ("/ws", uc.path);
  13208. }
  13209. {
  13210. detail::UrlComponents uc;
  13211. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13212. EXPECT_EQ("wss", uc.scheme);
  13213. EXPECT_EQ("echo.example.com", uc.host);
  13214. EXPECT_TRUE(uc.port.empty());
  13215. EXPECT_EQ("/ws", uc.path);
  13216. }
  13217. }
  13218. TEST(ParseUrlTest, QueryOnly) {
  13219. detail::UrlComponents uc;
  13220. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13221. EXPECT_TRUE(uc.host.empty());
  13222. EXPECT_TRUE(uc.path.empty());
  13223. EXPECT_EQ("?q=1&r=2", uc.query);
  13224. }
  13225. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13226. detail::UrlComponents uc;
  13227. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13228. EXPECT_TRUE(uc.scheme.empty());
  13229. EXPECT_EQ("example.com", uc.host);
  13230. EXPECT_EQ("443", uc.port);
  13231. EXPECT_EQ("/path", uc.path);
  13232. }
  13233. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13234. // If ipv6 regex working, regex match codepath is taken.
  13235. // else port will default to 80 in Client impl
  13236. int clientImplMagicPort = 80;
  13237. int port = 4321;
  13238. // above ports must be different to avoid false negative
  13239. EXPECT_NE(clientImplMagicPort, port);
  13240. std::string ipV6TestURL = "http://[ff06::c3]";
  13241. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13242. CLIENT_PRIVATE_KEY_FILE);
  13243. EXPECT_EQ(cli.port(), port);
  13244. }
  13245. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13246. auto file_path = "./www/dir/index.html";
  13247. auto dir_path = "./www/dir";
  13248. detail::FileStat stat_file(file_path);
  13249. EXPECT_TRUE(stat_file.is_file());
  13250. EXPECT_FALSE(stat_file.is_dir());
  13251. detail::FileStat stat_dir(dir_path);
  13252. EXPECT_FALSE(stat_dir.is_file());
  13253. EXPECT_TRUE(stat_dir.is_dir());
  13254. }
  13255. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13256. // IPv4 with default HTTP port (80)
  13257. EXPECT_EQ("example.com",
  13258. detail::make_host_and_port_string("example.com", 80, false));
  13259. // IPv4 with default HTTPS port (443)
  13260. EXPECT_EQ("example.com",
  13261. detail::make_host_and_port_string("example.com", 443, true));
  13262. // IPv4 with non-default HTTP port
  13263. EXPECT_EQ("example.com:8080",
  13264. detail::make_host_and_port_string("example.com", 8080, false));
  13265. // IPv4 with non-default HTTPS port
  13266. EXPECT_EQ("example.com:8443",
  13267. detail::make_host_and_port_string("example.com", 8443, true));
  13268. // IPv6 with default HTTP port (80)
  13269. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13270. // IPv6 with default HTTPS port (443)
  13271. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13272. // IPv6 with non-default HTTP port
  13273. EXPECT_EQ("[::1]:8080",
  13274. detail::make_host_and_port_string("::1", 8080, false));
  13275. // IPv6 with non-default HTTPS port
  13276. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13277. // IPv6 full address with default port
  13278. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13279. detail::make_host_and_port_string(
  13280. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13281. // IPv6 full address with non-default port
  13282. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13283. detail::make_host_and_port_string(
  13284. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13285. // IPv6 localhost with non-default port
  13286. EXPECT_EQ("[::1]:3000",
  13287. detail::make_host_and_port_string("::1", 3000, false));
  13288. // IPv6 with zone ID (link-local address) with default port
  13289. EXPECT_EQ("[fe80::1%eth0]",
  13290. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13291. // IPv6 with zone ID (link-local address) with non-default port
  13292. EXPECT_EQ("[fe80::1%eth0]:8080",
  13293. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13294. // Edge case: Port 443 with is_ssl=false (should add port)
  13295. EXPECT_EQ("example.com:443",
  13296. detail::make_host_and_port_string("example.com", 443, false));
  13297. // Edge case: Port 80 with is_ssl=true (should add port)
  13298. EXPECT_EQ("example.com:80",
  13299. detail::make_host_and_port_string("example.com", 80, true));
  13300. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13301. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13302. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13303. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13304. // Security fix: Already bracketed IPv6 should not get double brackets
  13305. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13306. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13307. EXPECT_EQ("[::1]:8080",
  13308. detail::make_host_and_port_string("[::1]", 8080, false));
  13309. EXPECT_EQ("[2001:db8::1]:8080",
  13310. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13311. EXPECT_EQ("[fe80::1%eth0]",
  13312. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13313. EXPECT_EQ("[fe80::1%eth0]:8080",
  13314. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13315. // Edge case: Empty host (should return as-is)
  13316. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13317. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13318. // This is a known limitation but shouldn't crash
  13319. EXPECT_EQ("[host:name]",
  13320. detail::make_host_and_port_string("host:name", 80, false));
  13321. // Port number edge cases (no validation, but should not crash)
  13322. EXPECT_EQ("example.com:0",
  13323. detail::make_host_and_port_string("example.com", 0, false));
  13324. EXPECT_EQ("example.com:-1",
  13325. detail::make_host_and_port_string("example.com", -1, false));
  13326. EXPECT_EQ("example.com:65535",
  13327. detail::make_host_and_port_string("example.com", 65535, false));
  13328. EXPECT_EQ("example.com:65536",
  13329. detail::make_host_and_port_string("example.com", 65536, false));
  13330. }
  13331. #ifdef CPPHTTPLIB_SSL_ENABLED
  13332. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13333. httplib::SSLClient cli("roblox.com", 443);
  13334. cli.set_follow_location(true);
  13335. auto res = cli.Get("/");
  13336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13337. EXPECT_EQ(StatusCode::OK_200, res->status);
  13338. }
  13339. #endif
  13340. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13341. Server svr;
  13342. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13343. EXPECT_EQ(res.status, 400);
  13344. });
  13345. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13346. auto se = detail::scope_exit([&] {
  13347. svr.stop();
  13348. thread.join();
  13349. ASSERT_FALSE(svr.is_running());
  13350. });
  13351. svr.wait_until_ready();
  13352. Client cli(HOST, PORT);
  13353. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13354. }
  13355. TEST(InvalidHeaderCharsTest, is_field_name) {
  13356. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13357. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13358. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13359. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13360. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13361. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13362. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13363. EXPECT_FALSE(detail::fields::is_field_name(""));
  13364. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13365. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13366. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13367. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13368. }
  13369. TEST(InvalidHeaderCharsTest, is_field_value) {
  13370. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13371. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13372. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13373. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13374. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13375. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13376. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13377. EXPECT_TRUE(detail::fields::is_field_value(""));
  13378. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13379. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13380. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13381. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13382. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13383. }
  13384. TEST(InvalidHeaderCharsTest, OnServer) {
  13385. Server svr;
  13386. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13387. std::string header = "Not Set";
  13388. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13389. res.set_header(header, "value");
  13390. res.set_content("Page Content Page Content", "text/plain");
  13391. });
  13392. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13393. std::string header = "Not Set";
  13394. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13395. res.set_header("X-Test", header);
  13396. res.set_content("Page Content Page Content", "text/plain");
  13397. });
  13398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13399. auto se = detail::scope_exit([&] {
  13400. svr.stop();
  13401. thread.join();
  13402. ASSERT_FALSE(svr.is_running());
  13403. });
  13404. svr.wait_until_ready();
  13405. Client cli(HOST, PORT);
  13406. {
  13407. auto res = cli.Get(
  13408. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13410. EXPECT_EQ("Page Content Page Content", res->body);
  13411. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13412. }
  13413. {
  13414. auto res = cli.Get(
  13415. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13417. EXPECT_EQ("Page Content Page Content", res->body);
  13418. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13419. }
  13420. }
  13421. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13422. auto handled = false;
  13423. Server svr;
  13424. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13425. thread t = thread([&] { svr.listen(HOST, PORT); });
  13426. auto se = detail::scope_exit([&] {
  13427. svr.stop();
  13428. t.join();
  13429. ASSERT_FALSE(svr.is_running());
  13430. ASSERT_FALSE(handled);
  13431. });
  13432. svr.wait_until_ready();
  13433. auto req = "POST /test HTTP/1.1\r\n"
  13434. "Content-Length: x\r\n"
  13435. "\r\n";
  13436. std::string response;
  13437. ASSERT_TRUE(send_request(1, req, &response));
  13438. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13439. response.substr(0, response.find("\r\n")));
  13440. }
  13441. #ifndef _WIN32
  13442. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13443. static constexpr char reject[] = "Unauthorized";
  13444. static constexpr char accept[] = "Upload accepted";
  13445. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13446. Server svr;
  13447. svr.set_expect_100_continue_handler(
  13448. [](const Request & /*req*/, Response &res) {
  13449. res.status = StatusCode::Unauthorized_401;
  13450. res.set_content(reject, "text/plain");
  13451. return res.status;
  13452. });
  13453. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13454. res.set_content(accept, "text/plain");
  13455. });
  13456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13457. auto se = detail::scope_exit([&] {
  13458. svr.stop();
  13459. thread.join();
  13460. ASSERT_FALSE(svr.is_running());
  13461. });
  13462. svr.wait_until_ready();
  13463. {
  13464. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13465. curl_easy_init(), &curl_easy_cleanup};
  13466. ASSERT_NE(curl, nullptr);
  13467. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13468. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13469. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13470. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13471. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13472. &curl_slist_free_all};
  13473. ASSERT_NE(list, nullptr);
  13474. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13475. struct read_data {
  13476. size_t read_size;
  13477. size_t total_size;
  13478. } data = {0, total_size};
  13479. using read_callback_t =
  13480. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13481. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13482. void *userdata) -> size_t {
  13483. read_data *d = (read_data *)userdata;
  13484. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13485. std::fill_n(ptr, size * nmemb, 'A');
  13486. d->read_size += size * nmemb;
  13487. return size * nmemb;
  13488. };
  13489. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13490. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13491. std::vector<char> buffer;
  13492. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13493. using write_callback_t =
  13494. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13495. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13496. void *userdata) -> size_t {
  13497. std::vector<char> *buf = (std::vector<char> *)userdata;
  13498. buf->reserve(buf->size() + size * nmemb + 1);
  13499. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13500. return size * nmemb;
  13501. };
  13502. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13503. {
  13504. const auto res = curl_easy_perform(curl.get());
  13505. ASSERT_EQ(res, CURLE_OK);
  13506. }
  13507. {
  13508. auto response_code = long{};
  13509. const auto res =
  13510. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13511. ASSERT_EQ(res, CURLE_OK);
  13512. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13513. }
  13514. {
  13515. auto dl = curl_off_t{};
  13516. const auto res =
  13517. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13518. ASSERT_EQ(res, CURLE_OK);
  13519. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13520. }
  13521. {
  13522. buffer.push_back('\0');
  13523. ASSERT_STRCASEEQ(buffer.data(), reject);
  13524. }
  13525. }
  13526. }
  13527. #endif
  13528. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13529. // Regression test for #2458.
  13530. //
  13531. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13532. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13533. // ticket can make the client socket spuriously readable during the
  13534. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13535. // the client withholds the body and then blocks reading a response that never
  13536. // comes, failing with `Failed to read connection`.
  13537. //
  13538. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13539. // within the timeout. This raw OpenSSL server deliberately never sends
  13540. // `100 Continue`; the client must still deliver the body and receive 200.
  13541. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13542. signal(SIGPIPE, SIG_IGN);
  13543. const auto port = PORT + 4;
  13544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13545. ASSERT_NE(srv, INVALID_SOCKET);
  13546. int opt = 1;
  13547. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13548. sockaddr_in addr{};
  13549. addr.sin_family = AF_INET;
  13550. addr.sin_port = htons(static_cast<uint16_t>(port));
  13551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13552. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13553. ASSERT_EQ(0, ::listen(srv, 1));
  13554. std::atomic<size_t> server_body_bytes{0};
  13555. auto server_thread = std::thread([&] {
  13556. sockaddr_in cli_addr{};
  13557. socklen_t cli_len = sizeof(cli_addr);
  13558. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13559. if (cli == INVALID_SOCKET) { return; }
  13560. // Bound the lifetime of the server side so a buggy client (which never
  13561. // sends the body) cannot make this thread block forever on join.
  13562. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13563. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13564. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13565. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13566. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13567. SSL *ssl = SSL_new(ctx);
  13568. SSL_set_fd(ssl, static_cast<int>(cli));
  13569. if (SSL_accept(ssl) > 0) {
  13570. // Read the request headers. Reading here also flushes the TLS 1.3
  13571. // session tickets to the client. Deliberately do NOT send
  13572. // `100 Continue`.
  13573. std::string buf;
  13574. char tmp[1024];
  13575. while (buf.find("\r\n\r\n") == std::string::npos) {
  13576. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13577. if (n <= 0) { break; }
  13578. buf.append(tmp, static_cast<size_t>(n));
  13579. }
  13580. // A correct client sends the body now; count what arrives.
  13581. auto pos = buf.find("\r\n\r\n");
  13582. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13583. while (body < 4096) {
  13584. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13585. if (n <= 0) { break; }
  13586. body += static_cast<size_t>(n);
  13587. }
  13588. server_body_bytes = body;
  13589. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13590. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13591. SSL_shutdown(ssl);
  13592. }
  13593. SSL_free(ssl);
  13594. detail::close_socket(cli);
  13595. SSL_CTX_free(ctx);
  13596. });
  13597. auto se = detail::scope_exit([&] {
  13598. server_thread.join();
  13599. detail::close_socket(srv);
  13600. });
  13601. SSLClient cli("127.0.0.1", port);
  13602. cli.enable_server_certificate_verification(false);
  13603. cli.set_connection_timeout(5, 0);
  13604. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13605. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13606. std::string body(4096, 'A');
  13607. auto res = cli.Put("/api/test", body, "application/json");
  13608. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13609. EXPECT_EQ(StatusCode::OK_200, res->status);
  13610. EXPECT_EQ(body.size(), server_body_bytes.load());
  13611. }
  13612. #endif
  13613. template <typename S, typename C>
  13614. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13615. svr.Get("/stream", [&](const Request &, Response &res) {
  13616. auto data = new std::string("01234567890123456789");
  13617. res.set_content_provider(
  13618. data->size(), "text/plain",
  13619. [&, data](size_t offset, size_t length, DataSink &sink) {
  13620. const size_t DATA_CHUNK_SIZE = 4;
  13621. const auto &d = *data;
  13622. std::this_thread::sleep_for(std::chrono::seconds(1));
  13623. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13624. return true;
  13625. },
  13626. [data](bool success) {
  13627. EXPECT_FALSE(success);
  13628. delete data;
  13629. });
  13630. });
  13631. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13632. auto i = new size_t(0);
  13633. res.set_content_provider(
  13634. "text/plain",
  13635. [i](size_t, DataSink &sink) {
  13636. if (*i < 5) {
  13637. std::this_thread::sleep_for(std::chrono::seconds(1));
  13638. sink.write("abcd", 4);
  13639. (*i)++;
  13640. } else {
  13641. sink.done();
  13642. }
  13643. return true;
  13644. },
  13645. [i](bool success) {
  13646. EXPECT_FALSE(success);
  13647. delete i;
  13648. });
  13649. });
  13650. svr.Get("/chunked", [&](const Request &, Response &res) {
  13651. auto i = new size_t(0);
  13652. res.set_chunked_content_provider(
  13653. "text/plain",
  13654. [i](size_t, DataSink &sink) {
  13655. if (*i < 5) {
  13656. std::this_thread::sleep_for(std::chrono::seconds(1));
  13657. sink.os << "abcd";
  13658. (*i)++;
  13659. } else {
  13660. sink.done();
  13661. }
  13662. return true;
  13663. },
  13664. [i](bool success) {
  13665. EXPECT_FALSE(success);
  13666. delete i;
  13667. });
  13668. });
  13669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13670. auto se = detail::scope_exit([&] {
  13671. svr.stop();
  13672. listen_thread.join();
  13673. ASSERT_FALSE(svr.is_running());
  13674. });
  13675. svr.wait_until_ready();
  13676. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13677. {
  13678. auto start = std::chrono::steady_clock::now();
  13679. auto res = cli.Get("/stream");
  13680. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13681. std::chrono::steady_clock::now() - start)
  13682. .count();
  13683. ASSERT_FALSE(res);
  13684. EXPECT_EQ(Error::Read, res.error());
  13685. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13686. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13687. }
  13688. {
  13689. auto start = std::chrono::steady_clock::now();
  13690. auto res = cli.Get("/stream_without_length");
  13691. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13692. std::chrono::steady_clock::now() - start)
  13693. .count();
  13694. ASSERT_FALSE(res);
  13695. EXPECT_EQ(Error::Read, res.error());
  13696. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13697. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13698. }
  13699. {
  13700. auto start = std::chrono::steady_clock::now();
  13701. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13702. EXPECT_EQ("abcd", string(data, data_length));
  13703. return true;
  13704. });
  13705. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13706. std::chrono::steady_clock::now() - start)
  13707. .count();
  13708. ASSERT_FALSE(res);
  13709. EXPECT_EQ(Error::Read, res.error());
  13710. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13711. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13712. }
  13713. }
  13714. TEST(MaxTimeoutTest, ContentStream) {
  13715. time_t timeout = 2000;
  13716. time_t threshold = 200;
  13717. Server svr;
  13718. Client cli("localhost", PORT);
  13719. max_timeout_test(svr, cli, timeout, threshold);
  13720. }
  13721. #ifdef CPPHTTPLIB_SSL_ENABLED
  13722. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13723. time_t timeout = 2000;
  13724. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13726. SSLClient cli("localhost", PORT);
  13727. cli.enable_server_certificate_verification(false);
  13728. max_timeout_test(svr, cli, timeout, threshold);
  13729. }
  13730. #endif
  13731. class EventDispatcher {
  13732. public:
  13733. EventDispatcher() {}
  13734. bool wait_event(DataSink *sink) {
  13735. unique_lock<mutex> lk(m_);
  13736. int id = id_;
  13737. // Wait with timeout to prevent hanging if client disconnects
  13738. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13739. [&] { return cid_ == id; })) {
  13740. return false; // Timeout occurred
  13741. }
  13742. sink->write(message_.data(), message_.size());
  13743. return true;
  13744. }
  13745. void send_event(const string &message) {
  13746. lock_guard<mutex> lk(m_);
  13747. cid_ = id_++;
  13748. message_ = message;
  13749. cv_.notify_all();
  13750. }
  13751. private:
  13752. mutex m_;
  13753. condition_variable cv_;
  13754. atomic_int id_{0};
  13755. atomic_int cid_{-1};
  13756. string message_;
  13757. };
  13758. TEST(ClientInThreadTest, Issue2068) {
  13759. EventDispatcher ed;
  13760. Server svr;
  13761. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13762. res.set_chunked_content_provider("text/event-stream",
  13763. [&](size_t /*offset*/, DataSink &sink) {
  13764. return ed.wait_event(&sink);
  13765. });
  13766. });
  13767. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13768. svr.wait_until_ready();
  13769. thread event_thread([&] {
  13770. int id = 0;
  13771. while (svr.is_running()) {
  13772. this_thread::sleep_for(chrono::milliseconds(500));
  13773. std::stringstream ss;
  13774. ss << "data: " << id << "\n\n";
  13775. ed.send_event(ss.str());
  13776. id++;
  13777. }
  13778. });
  13779. auto se = detail::scope_exit([&] {
  13780. svr.stop();
  13781. listen_thread.join();
  13782. event_thread.join();
  13783. ASSERT_FALSE(svr.is_running());
  13784. });
  13785. {
  13786. auto client = detail::make_unique<Client>(HOST, PORT);
  13787. client->set_read_timeout(std::chrono::minutes(10));
  13788. std::atomic<bool> stop{false};
  13789. std::thread t([&] {
  13790. client->Get("/event1",
  13791. [&](const char *, size_t) -> bool { return !stop; });
  13792. });
  13793. std::this_thread::sleep_for(std::chrono::seconds(2));
  13794. stop = true;
  13795. client->stop();
  13796. t.join();
  13797. // Reset client after thread has finished
  13798. client.reset();
  13799. }
  13800. }
  13801. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13802. auto handled = false;
  13803. Server svr;
  13804. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13806. auto se = detail::scope_exit([&] {
  13807. svr.stop();
  13808. t.join();
  13809. ASSERT_FALSE(svr.is_running());
  13810. ASSERT_FALSE(handled);
  13811. });
  13812. svr.wait_until_ready();
  13813. // Two Content-Length headers with different values — must be rejected
  13814. auto req = "POST /test HTTP/1.1\r\n"
  13815. "Content-Length: 5\r\n"
  13816. "Content-Length: 10\r\n"
  13817. "\r\n"
  13818. "hello";
  13819. std::string response;
  13820. ASSERT_TRUE(send_request(1, req, &response));
  13821. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13822. response.substr(0, response.find("\r\n")));
  13823. }
  13824. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13825. auto handled = false;
  13826. Server svr;
  13827. svr.Post("/test", [&](const Request &, Response &res) {
  13828. handled = true;
  13829. res.set_content("ok", "text/plain");
  13830. });
  13831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13832. auto se = detail::scope_exit([&] {
  13833. svr.stop();
  13834. t.join();
  13835. ASSERT_FALSE(svr.is_running());
  13836. ASSERT_TRUE(handled);
  13837. });
  13838. svr.wait_until_ready();
  13839. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13840. auto req = "POST /test HTTP/1.1\r\n"
  13841. "Content-Length: 5\r\n"
  13842. "Content-Length: 5\r\n"
  13843. "\r\n"
  13844. "hello";
  13845. std::string response;
  13846. ASSERT_TRUE(send_request(1, req, &response));
  13847. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13848. }
  13849. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13850. Server svr;
  13851. svr.Get("/", [](const Request &req, Response &res) {
  13852. EXPECT_EQ(2U, req.trailers.size());
  13853. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13854. // Denied
  13855. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13856. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13857. // Accepted
  13858. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13859. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13860. EXPECT_TRUE(req.has_trailer("X-World"));
  13861. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13862. res.set_content("ok", "text/plain");
  13863. });
  13864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13865. auto se = detail::scope_exit([&] {
  13866. svr.stop();
  13867. t.join();
  13868. ASSERT_FALSE(svr.is_running());
  13869. });
  13870. svr.wait_until_ready();
  13871. const std::string req = "GET / HTTP/1.1\r\n"
  13872. "Transfer-Encoding: chunked\r\n"
  13873. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13874. "\r\n"
  13875. "0\r\n"
  13876. "Content-Length: 10\r\n"
  13877. "Host: internal.local\r\n"
  13878. "Content-Type: malicious/content\r\n"
  13879. "Cookie: any\r\n"
  13880. "Set-Cookie: any\r\n"
  13881. "X-Forwarded-For: attacker.com\r\n"
  13882. "X-Real-Ip: 1.1.1.1\r\n"
  13883. "X-Hello: hello\r\n"
  13884. "X-World: world\r\n"
  13885. "\r\n";
  13886. std::string res;
  13887. ASSERT_TRUE(send_request(1, req, &res));
  13888. }
  13889. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  13890. // several field lines, and the combined value is what has to be parsed. A
  13891. // Trailer field split across lines therefore declares every name it lists;
  13892. // reading only the first line silently drops the trailers the later lines
  13893. // declare. The prohibited-trailer filter still applies to every line.
  13894. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  13895. Server svr;
  13896. size_t observed_trailer_count = 0;
  13897. std::string observed_hello;
  13898. std::string observed_world;
  13899. bool observed_content_length = true;
  13900. svr.Get("/", [&](const Request &req, Response &res) {
  13901. observed_trailer_count = req.trailers.size();
  13902. observed_hello = req.get_trailer_value("X-Hello");
  13903. observed_world = req.get_trailer_value("X-World");
  13904. observed_content_length = req.has_trailer("Content-Length");
  13905. res.set_content("ok", "text/plain");
  13906. });
  13907. auto port = svr.bind_to_any_port(HOST);
  13908. thread t = thread([&]() { svr.listen_after_bind(); });
  13909. auto se = detail::scope_exit([&] {
  13910. svr.stop();
  13911. t.join();
  13912. ASSERT_FALSE(svr.is_running());
  13913. });
  13914. svr.wait_until_ready();
  13915. const std::string req = "GET / HTTP/1.1\r\n"
  13916. "Transfer-Encoding: chunked\r\n"
  13917. "Trailer: X-Hello\r\n"
  13918. "Trailer: X-World, Content-Length\r\n"
  13919. "\r\n"
  13920. "0\r\n"
  13921. "X-Hello: hello\r\n"
  13922. "X-World: world\r\n"
  13923. "Content-Length: 10\r\n"
  13924. "\r\n";
  13925. std::string res;
  13926. ASSERT_TRUE(send_request(1, req, &res, port));
  13927. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  13928. // Accepted: both field lines contribute to the declared set
  13929. EXPECT_EQ(2U, observed_trailer_count);
  13930. EXPECT_EQ(observed_hello, "hello");
  13931. EXPECT_EQ(observed_world, "world");
  13932. // Denied: a prohibited name stays prohibited on a later field line
  13933. EXPECT_FALSE(observed_content_length);
  13934. }
  13935. // A direct client that is not listed in trusted_proxies must not be able to
  13936. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13937. // the peer address on the actual TCP connection determines whether the
  13938. // header is honored.
  13939. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13940. Server svr;
  13941. // Deliberately does NOT include the loopback address the test client
  13942. // actually connects from, so the direct connection is not a trusted proxy.
  13943. svr.set_trusted_proxies({"203.0.113.66"});
  13944. std::string observed_remote_addr;
  13945. svr.Get("/ip", [&](const Request &req, Response &res) {
  13946. observed_remote_addr = req.remote_addr;
  13947. res.set_content("ok", "text/plain");
  13948. });
  13949. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13950. auto se = detail::scope_exit([&] {
  13951. svr.stop();
  13952. t.join();
  13953. ASSERT_FALSE(svr.is_running());
  13954. });
  13955. svr.wait_until_ready();
  13956. Client cli(HOST, PORT);
  13957. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13959. EXPECT_EQ(StatusCode::OK_200, res->status);
  13960. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13961. // ignored entirely and the real connection-level address retained.
  13962. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13963. observed_remote_addr == "127.0.0.1");
  13964. }
  13965. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13966. Server svr;
  13967. std::string observed_remote_addr;
  13968. std::string observed_xff;
  13969. svr.Get("/ip", [&](const Request &req, Response &res) {
  13970. observed_remote_addr = req.remote_addr;
  13971. observed_xff = req.get_header_value("X-Forwarded-For");
  13972. res.set_content("ok", "text/plain");
  13973. });
  13974. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13975. auto se = detail::scope_exit([&] {
  13976. svr.stop();
  13977. t.join();
  13978. ASSERT_FALSE(svr.is_running());
  13979. });
  13980. svr.wait_until_ready();
  13981. Client cli(HOST, PORT);
  13982. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13984. EXPECT_EQ(StatusCode::OK_200, res->status);
  13985. EXPECT_EQ(observed_xff, "203.0.113.66");
  13986. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13987. observed_remote_addr == "127.0.0.1");
  13988. }
  13989. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13990. Server svr;
  13991. svr.set_trusted_proxies({"203.0.113.66"});
  13992. std::string observed_remote_addr;
  13993. std::string observed_xff;
  13994. svr.Get("/ip", [&](const Request &req, Response &res) {
  13995. observed_remote_addr = req.remote_addr;
  13996. observed_xff = req.get_header_value("X-Forwarded-For");
  13997. res.set_content("ok", "text/plain");
  13998. });
  13999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14000. auto se = detail::scope_exit([&] {
  14001. svr.stop();
  14002. t.join();
  14003. ASSERT_FALSE(svr.is_running());
  14004. });
  14005. svr.wait_until_ready();
  14006. Client cli(HOST, PORT);
  14007. auto res = cli.Get("/ip");
  14008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14009. EXPECT_EQ(StatusCode::OK_200, res->status);
  14010. EXPECT_EQ(observed_xff, "");
  14011. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14012. observed_remote_addr == "127.0.0.1");
  14013. }
  14014. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14015. Server svr;
  14016. // Include the loopback address the test client actually connects from, so
  14017. // the direct connection itself is recognized as the trusted proxy hop.
  14018. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14019. std::string observed_remote_addr;
  14020. std::string observed_xff;
  14021. svr.Get("/ip", [&](const Request &req, Response &res) {
  14022. observed_remote_addr = req.remote_addr;
  14023. observed_xff = req.get_header_value("X-Forwarded-For");
  14024. res.set_content("ok", "text/plain");
  14025. });
  14026. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14027. auto se = detail::scope_exit([&] {
  14028. svr.stop();
  14029. t.join();
  14030. ASSERT_FALSE(svr.is_running());
  14031. });
  14032. svr.wait_until_ready();
  14033. Client cli(HOST, PORT);
  14034. auto res = cli.Get(
  14035. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. EXPECT_EQ(StatusCode::OK_200, res->status);
  14038. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14039. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14040. }
  14041. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14042. Server svr;
  14043. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14044. std::string observed_remote_addr;
  14045. std::string observed_xff;
  14046. svr.Get("/ip", [&](const Request &req, Response &res) {
  14047. observed_remote_addr = req.remote_addr;
  14048. observed_xff = req.get_header_value("X-Forwarded-For");
  14049. res.set_content("ok", "text/plain");
  14050. });
  14051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14052. auto se = detail::scope_exit([&] {
  14053. svr.stop();
  14054. t.join();
  14055. ASSERT_FALSE(svr.is_running());
  14056. });
  14057. svr.wait_until_ready();
  14058. Client cli(HOST, PORT);
  14059. auto res = cli.Get(
  14060. "/ip",
  14061. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14063. EXPECT_EQ(StatusCode::OK_200, res->status);
  14064. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14065. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14066. }
  14067. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14068. Server svr;
  14069. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14070. std::string observed_remote_addr;
  14071. std::string observed_xff;
  14072. svr.Get("/ip", [&](const Request &req, Response &res) {
  14073. observed_remote_addr = req.remote_addr;
  14074. observed_xff = req.get_header_value("X-Forwarded-For");
  14075. res.set_content("ok", "text/plain");
  14076. });
  14077. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14078. auto se = detail::scope_exit([&] {
  14079. svr.stop();
  14080. t.join();
  14081. ASSERT_FALSE(svr.is_running());
  14082. });
  14083. svr.wait_until_ready();
  14084. Client cli(HOST, PORT);
  14085. auto res = cli.Get(
  14086. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14088. EXPECT_EQ(StatusCode::OK_200, res->status);
  14089. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14090. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14091. // and must not be selected.
  14092. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14093. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14094. }
  14095. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14096. Server svr;
  14097. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14098. std::string observed_remote_addr;
  14099. svr.Get("/ip", [&](const Request &req, Response &res) {
  14100. observed_remote_addr = req.remote_addr;
  14101. res.set_content("ok", "text/plain");
  14102. });
  14103. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. ASSERT_FALSE(svr.is_running());
  14108. });
  14109. svr.wait_until_ready();
  14110. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14111. // a forged address and the trusted proxy's own address; the forged value must
  14112. // not win over the address the trusted proxy actually recorded.
  14113. Client cli(HOST, PORT);
  14114. auto res = cli.Get(
  14115. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14117. EXPECT_EQ(StatusCode::OK_200, res->status);
  14118. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14119. }
  14120. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14121. Server svr;
  14122. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14123. std::string observed_remote_addr;
  14124. std::string observed_xff;
  14125. svr.Get("/ip", [&](const Request &req, Response &res) {
  14126. observed_remote_addr = req.remote_addr;
  14127. observed_xff = req.get_header_value("X-Forwarded-For");
  14128. res.set_content("ok", "text/plain");
  14129. });
  14130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14131. auto se = detail::scope_exit([&] {
  14132. svr.stop();
  14133. t.join();
  14134. ASSERT_FALSE(svr.is_running());
  14135. });
  14136. svr.wait_until_ready();
  14137. Client cli(HOST, PORT);
  14138. auto res = cli.Get(
  14139. "/ip",
  14140. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14142. EXPECT_EQ(StatusCode::OK_200, res->status);
  14143. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14144. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14145. }
  14146. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14147. Server svr;
  14148. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14149. std::string observed_remote_addr;
  14150. std::string observed_xff;
  14151. svr.Get("/ip", [&](const Request &req, Response &res) {
  14152. observed_remote_addr = req.remote_addr;
  14153. observed_xff = req.get_header_value("X-Forwarded-For");
  14154. res.set_content("ok", "text/plain");
  14155. });
  14156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14157. auto se = detail::scope_exit([&] {
  14158. svr.stop();
  14159. t.join();
  14160. ASSERT_FALSE(svr.is_running());
  14161. });
  14162. svr.wait_until_ready();
  14163. std::string raw_req =
  14164. "GET /ip HTTP/1.1\r\n"
  14165. "Host: localhost\r\n"
  14166. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14167. "Connection: close\r\n"
  14168. "\r\n";
  14169. std::string out;
  14170. ASSERT_TRUE(send_request(5, raw_req, &out));
  14171. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14172. // Header parser trims surrounding whitespace of the header value
  14173. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14174. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14175. }
  14176. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14177. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14178. // their own X-Forwarded-For as a separate field line rather than extending the
  14179. // one the client sent, so every occurrence has to be taken into account.
  14180. // Reading only the first one hands back the address the client chose.
  14181. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14182. Server svr;
  14183. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14184. std::string observed_remote_addr;
  14185. size_t observed_xff_count = 0;
  14186. svr.Get("/ip", [&](const Request &req, Response &res) {
  14187. observed_remote_addr = req.remote_addr;
  14188. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14189. res.set_content("ok", "text/plain");
  14190. });
  14191. auto port = svr.bind_to_any_port(HOST);
  14192. thread t = thread([&]() { svr.listen_after_bind(); });
  14193. auto se = detail::scope_exit([&] {
  14194. svr.stop();
  14195. t.join();
  14196. ASSERT_FALSE(svr.is_running());
  14197. });
  14198. svr.wait_until_ready();
  14199. // The client supplies the first field line; the trusted proxy appends the
  14200. // address it observed as a second one.
  14201. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14202. "Host: localhost\r\n"
  14203. "X-Forwarded-For: 1.2.3.4\r\n"
  14204. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14205. "Connection: close\r\n"
  14206. "\r\n";
  14207. std::string out;
  14208. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14209. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14210. EXPECT_EQ(observed_xff_count, 2U);
  14211. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14212. // The same chain spread over one field line per hop derives the same client
  14213. // address, i.e. the split and the comma-joined representations agree.
  14214. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14215. "Host: localhost\r\n"
  14216. "X-Forwarded-For: 1.2.3.4\r\n"
  14217. "X-Forwarded-For: 198.51.100.23\r\n"
  14218. "X-Forwarded-For: 192.0.2.45\r\n"
  14219. "Connection: close\r\n"
  14220. "\r\n";
  14221. out.clear();
  14222. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14223. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14224. EXPECT_EQ(observed_xff_count, 3U);
  14225. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14226. }
  14227. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14228. // crash the server (it used to call front() on an empty vector inside
  14229. // get_client_ip). The connection-level remote address must be retained instead.
  14230. static void run_malformed_xff_test(const std::string &xff_value) {
  14231. Server svr;
  14232. svr.set_trusted_proxies({"192.0.2.45"});
  14233. std::string observed_remote_addr;
  14234. svr.Get("/ip", [&](const Request &req, Response &res) {
  14235. observed_remote_addr = req.remote_addr;
  14236. res.set_content("ok", "text/plain");
  14237. });
  14238. int port = 0;
  14239. thread t = thread([&]() {
  14240. port = svr.bind_to_any_port(HOST);
  14241. svr.listen_after_bind();
  14242. });
  14243. auto se = detail::scope_exit([&] {
  14244. svr.stop();
  14245. t.join();
  14246. ASSERT_FALSE(svr.is_running());
  14247. });
  14248. svr.wait_until_ready();
  14249. Client cli(HOST, port);
  14250. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14252. EXPECT_EQ(StatusCode::OK_200, res->status);
  14253. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14254. observed_remote_addr == "127.0.0.1");
  14255. }
  14256. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14257. run_malformed_xff_test("");
  14258. }
  14259. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14260. run_malformed_xff_test(",");
  14261. }
  14262. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14263. run_malformed_xff_test(", , ,");
  14264. }
  14265. // The same rule applies to Accept: a request whose acceptable types are spread
  14266. // over several field lines must be negotiated against all of them.
  14267. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14268. // case-insensitive connection options. Comparing the whole field value against
  14269. // one option misses a client that sends several of them, and misses every
  14270. // casing but the one written in the comparison.
  14271. //
  14272. // Sends req, reads the response, then reuses the same socket for a second
  14273. // request to find out whether the server kept the connection.
  14274. static void probe_connection_reuse(int port, const std::string &req,
  14275. bool *announced_close, bool *reusable) {
  14276. auto error = Error::Success;
  14277. auto sock = detail::create_client_socket(
  14278. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14279. /*connection_timeout_sec=*/5, 0,
  14280. /*read_timeout_sec=*/1, 0,
  14281. /*write_timeout_sec=*/5, 0, std::string(), error);
  14282. ASSERT_NE(sock, INVALID_SOCKET);
  14283. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14284. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14285. "Host: localhost\r\n"
  14286. "Connection: close\r\n"
  14287. "\r\n";
  14288. std::string first_response;
  14289. std::string second_response;
  14290. detail::process_client_socket(
  14291. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14292. [&](Stream &strm) {
  14293. if (strm.write(req.data(), req.size()) !=
  14294. static_cast<ssize_t>(req.size())) {
  14295. return false;
  14296. }
  14297. char buf[512];
  14298. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14299. // Headers plus the two-byte body of the handler below
  14300. while (reader.getline()) {
  14301. first_response += reader.ptr();
  14302. if (first_response.find("ok") != std::string::npos) { break; }
  14303. }
  14304. if (strm.write(second.data(), second.size()) !=
  14305. static_cast<ssize_t>(second.size())) {
  14306. return true;
  14307. }
  14308. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14309. while (reader2.getline()) {
  14310. second_response += reader2.ptr();
  14311. if (second_response.find("ok") != std::string::npos) { break; }
  14312. }
  14313. return true;
  14314. });
  14315. *announced_close =
  14316. first_response.find("Connection: close") != std::string::npos;
  14317. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14318. }
  14319. class ConnectionTokenTest : public ::testing::Test {
  14320. protected:
  14321. void SetUp() override {
  14322. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14323. res.set_content("ok", "text/plain");
  14324. });
  14325. port_ = svr_.bind_to_any_port(HOST);
  14326. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14327. svr_.wait_until_ready();
  14328. }
  14329. void TearDown() override {
  14330. svr_.stop();
  14331. if (thread_.joinable()) { thread_.join(); }
  14332. }
  14333. Server svr_;
  14334. int port_ = 0;
  14335. thread thread_;
  14336. };
  14337. // "close" alongside another option still closes the connection, and the
  14338. // response says so rather than leaving the peer to discover it.
  14339. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14340. bool announced_close = false;
  14341. bool reusable = true;
  14342. probe_connection_reuse(port_,
  14343. "GET /keepalive HTTP/1.1\r\n"
  14344. "Host: localhost\r\n"
  14345. "Connection: keep-alive, close\r\n"
  14346. "\r\n",
  14347. &announced_close, &reusable);
  14348. EXPECT_TRUE(announced_close);
  14349. EXPECT_FALSE(reusable);
  14350. }
  14351. // "close" split over two field lines is the same list, so it is honored too.
  14352. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14353. bool announced_close = false;
  14354. bool reusable = true;
  14355. probe_connection_reuse(port_,
  14356. "GET /keepalive HTTP/1.1\r\n"
  14357. "Host: localhost\r\n"
  14358. "Connection: keep-alive\r\n"
  14359. "Connection: close\r\n"
  14360. "\r\n",
  14361. &announced_close, &reusable);
  14362. EXPECT_TRUE(announced_close);
  14363. EXPECT_FALSE(reusable);
  14364. }
  14365. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14366. // keep-alive in the spelling everyone actually sends keeps its connection.
  14367. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14368. bool announced_close = false;
  14369. bool reusable = false;
  14370. probe_connection_reuse(port_,
  14371. "GET /keepalive HTTP/1.0\r\n"
  14372. "Host: localhost\r\n"
  14373. "Connection: keep-alive\r\n"
  14374. "\r\n",
  14375. &announced_close, &reusable);
  14376. EXPECT_FALSE(announced_close);
  14377. EXPECT_TRUE(reusable);
  14378. }
  14379. // A token the value merely contains is not the token itself.
  14380. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14381. bool announced_close = false;
  14382. bool reusable = false;
  14383. probe_connection_reuse(port_,
  14384. "GET /keepalive HTTP/1.1\r\n"
  14385. "Host: localhost\r\n"
  14386. "Connection: notclose\r\n"
  14387. "\r\n",
  14388. &announced_close, &reusable);
  14389. EXPECT_FALSE(announced_close);
  14390. EXPECT_TRUE(reusable);
  14391. }
  14392. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14393. Server svr;
  14394. std::vector<std::string> observed_types;
  14395. svr.Get("/", [&](const Request &req, Response &res) {
  14396. observed_types = req.accept_content_types;
  14397. res.set_content("ok", "text/plain");
  14398. });
  14399. auto port = svr.bind_to_any_port(HOST);
  14400. thread t = thread([&]() { svr.listen_after_bind(); });
  14401. auto se = detail::scope_exit([&] {
  14402. svr.stop();
  14403. t.join();
  14404. ASSERT_FALSE(svr.is_running());
  14405. });
  14406. svr.wait_until_ready();
  14407. Client cli(HOST, port);
  14408. Headers headers;
  14409. headers.emplace("Accept", "text/plain;q=0.5");
  14410. headers.emplace("Accept", "application/json");
  14411. auto res = cli.Get("/", headers);
  14412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14413. EXPECT_EQ(StatusCode::OK_200, res->status);
  14414. // Sorted by q-value, so the second field line's type comes first
  14415. ASSERT_EQ(2U, observed_types.size());
  14416. EXPECT_EQ("application/json", observed_types[0]);
  14417. EXPECT_EQ("text/plain", observed_types[1]);
  14418. }
  14419. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14420. // empty field line must not contribute a bare comma to the combined value.
  14421. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14422. // turn a legal request into 400 Bad Request.
  14423. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14424. Server svr;
  14425. std::vector<std::string> observed_types;
  14426. svr.Get("/", [&](const Request &req, Response &res) {
  14427. observed_types = req.accept_content_types;
  14428. res.set_content("ok", "text/plain");
  14429. });
  14430. auto port = svr.bind_to_any_port(HOST);
  14431. thread t = thread([&]() { svr.listen_after_bind(); });
  14432. auto se = detail::scope_exit([&] {
  14433. svr.stop();
  14434. t.join();
  14435. ASSERT_FALSE(svr.is_running());
  14436. });
  14437. svr.wait_until_ready();
  14438. // Empty first field line, then a real one
  14439. std::string raw_req = "GET / HTTP/1.1\r\n"
  14440. "Host: localhost\r\n"
  14441. "Accept:\r\n"
  14442. "Accept: application/json\r\n"
  14443. "Connection: close\r\n"
  14444. "\r\n";
  14445. std::string out;
  14446. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14447. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14448. ASSERT_EQ(1U, observed_types.size());
  14449. EXPECT_EQ("application/json", observed_types[0]);
  14450. }
  14451. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14452. // An encoding offered on a later Accept-Encoding field line is still offered.
  14453. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14454. Server svr;
  14455. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14456. res.set_content(std::string(1024, 'x'), "text/plain");
  14457. });
  14458. auto port = svr.bind_to_any_port(HOST);
  14459. thread t = thread([&]() { svr.listen_after_bind(); });
  14460. auto se = detail::scope_exit([&] {
  14461. svr.stop();
  14462. t.join();
  14463. ASSERT_FALSE(svr.is_running());
  14464. });
  14465. svr.wait_until_ready();
  14466. Client cli(HOST, port);
  14467. cli.set_decompress(false);
  14468. Headers headers;
  14469. headers.emplace("Accept-Encoding", "identity");
  14470. headers.emplace("Accept-Encoding", "gzip");
  14471. auto res = cli.Get("/", headers);
  14472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14473. EXPECT_EQ(StatusCode::OK_200, res->status);
  14474. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14475. }
  14476. #endif
  14477. #ifndef _WIN32
  14478. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14479. Server svr;
  14480. svr.Post("/post", [&](const Request &req, Response &res) {
  14481. res.set_content(req.body, "text/plain");
  14482. });
  14483. svr.Put("/put", [&](const Request &req, Response &res) {
  14484. res.set_content(req.body, "text/plain");
  14485. });
  14486. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14487. res.set_content(req.body, "text/plain");
  14488. });
  14489. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14490. res.set_content(req.body, "text/plain");
  14491. });
  14492. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14493. auto se = detail::scope_exit([&] {
  14494. svr.stop();
  14495. t.join();
  14496. ASSERT_FALSE(svr.is_running());
  14497. });
  14498. svr.wait_until_ready();
  14499. std::string resp;
  14500. // POST without Content-Length
  14501. ASSERT_TRUE(send_request(5,
  14502. "POST /post HTTP/1.1\r\n"
  14503. "Host: localhost\r\n"
  14504. "Connection: close\r\n"
  14505. "\r\n",
  14506. &resp));
  14507. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14508. // PUT without Content-Length
  14509. resp.clear();
  14510. ASSERT_TRUE(send_request(5,
  14511. "PUT /put HTTP/1.1\r\n"
  14512. "Host: localhost\r\n"
  14513. "Connection: close\r\n"
  14514. "\r\n",
  14515. &resp));
  14516. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14517. // PATCH without Content-Length
  14518. resp.clear();
  14519. ASSERT_TRUE(send_request(5,
  14520. "PATCH /patch HTTP/1.1\r\n"
  14521. "Host: localhost\r\n"
  14522. "Connection: close\r\n"
  14523. "\r\n",
  14524. &resp));
  14525. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14526. // DELETE without Content-Length
  14527. resp.clear();
  14528. ASSERT_TRUE(send_request(5,
  14529. "DELETE /delete HTTP/1.1\r\n"
  14530. "Host: localhost\r\n"
  14531. "Connection: close\r\n"
  14532. "\r\n",
  14533. &resp));
  14534. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14535. }
  14536. #endif
  14537. //==============================================================================
  14538. // open_stream() Tests
  14539. //==============================================================================
  14540. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14541. std::string result;
  14542. char buf[8192];
  14543. ssize_t n;
  14544. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14545. result.append(buf, static_cast<size_t>(n));
  14546. }
  14547. return result;
  14548. }
  14549. // Mock stream for unit tests
  14550. class MockStream : public Stream {
  14551. public:
  14552. std::string data;
  14553. size_t pos = 0;
  14554. ssize_t error_after = -1; // -1 = no error
  14555. explicit MockStream(const std::string &d, ssize_t err = -1)
  14556. : data(d), error_after(err) {}
  14557. bool is_readable() const override { return true; }
  14558. bool wait_readable() const override { return true; }
  14559. bool wait_writable() const override { return true; }
  14560. ssize_t read(char *ptr, size_t size) override {
  14561. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14562. if (pos >= data.size()) return 0;
  14563. size_t limit =
  14564. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14565. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14566. std::memcpy(ptr, data.data() + pos, to_read);
  14567. pos += to_read;
  14568. return static_cast<ssize_t>(to_read);
  14569. }
  14570. ssize_t write(const char *, size_t) override { return -1; }
  14571. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14572. ip = "127.0.0.1";
  14573. port = 0;
  14574. }
  14575. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14576. ip = "127.0.0.1";
  14577. port = 0;
  14578. }
  14579. socket_t socket() const override { return INVALID_SOCKET; }
  14580. time_t duration() const override { return 0; }
  14581. };
  14582. TEST(StreamHandleTest, Basic) {
  14583. ClientImpl::StreamHandle handle;
  14584. EXPECT_FALSE(handle.is_valid());
  14585. handle.response = detail::make_unique<Response>();
  14586. handle.error = Error::Connection;
  14587. EXPECT_FALSE(handle.is_valid());
  14588. handle.error = Error::Success;
  14589. EXPECT_TRUE(handle.is_valid());
  14590. }
  14591. TEST(BodyReaderTest, Basic) {
  14592. MockStream stream("Hello, World!");
  14593. detail::BodyReader reader;
  14594. reader.stream = &stream;
  14595. reader.content_length = 13;
  14596. char buf[32];
  14597. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14598. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14599. EXPECT_TRUE(reader.eof);
  14600. }
  14601. TEST(BodyReaderTest, NoStream) {
  14602. detail::BodyReader reader;
  14603. char buf[32];
  14604. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14605. EXPECT_EQ(Error::Connection, reader.last_error);
  14606. }
  14607. TEST(BodyReaderTest, Error) {
  14608. MockStream stream("Hello, World!", 5);
  14609. detail::BodyReader reader;
  14610. reader.stream = &stream;
  14611. reader.content_length = 13;
  14612. char buf[32];
  14613. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14614. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14615. EXPECT_EQ(Error::Read, reader.last_error);
  14616. }
  14617. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14618. // Mock-based StreamHandle tests relying on private internals are removed.
  14619. class OpenStreamTest : public ::testing::Test {
  14620. protected:
  14621. void SetUp() override {
  14622. svr_.Get("/hello", [](const Request &, Response &res) {
  14623. res.set_content("Hello World!", "text/plain");
  14624. });
  14625. svr_.Get("/large", [](const Request &, Response &res) {
  14626. res.set_content(std::string(10000, 'X'), "text/plain");
  14627. });
  14628. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14629. res.set_content("Hello World!", "image/jpeg");
  14630. res.set_header("Content-Encoding", "UTF-8");
  14631. });
  14632. svr_.Get("/chunked", [](const Request &, Response &res) {
  14633. res.set_chunked_content_provider("text/plain",
  14634. [](size_t offset, DataSink &sink) {
  14635. if (offset < 15) {
  14636. sink.write("chunk", 5);
  14637. return true;
  14638. }
  14639. sink.done();
  14640. return true;
  14641. });
  14642. });
  14643. svr_.Get("/compressible", [](const Request &, Response &res) {
  14644. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14645. DataSink &sink) {
  14646. if (offset < 100 * 1024) {
  14647. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14648. sink.write(chunk.data(), chunk.size());
  14649. return true;
  14650. }
  14651. sink.done();
  14652. return true;
  14653. });
  14654. });
  14655. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14656. [](const Request & /*req*/, Response &res) {
  14657. auto i = new int(0);
  14658. res.set_header("Trailer", "Content-Length, X-Allowed");
  14659. res.set_chunked_content_provider(
  14660. "text/plain",
  14661. [i](size_t /*offset*/, DataSink &sink) {
  14662. switch (*i) {
  14663. case 0: sink.os << "123"; break;
  14664. case 1: sink.os << "456"; break;
  14665. case 2: sink.os << "789"; break;
  14666. case 3: {
  14667. sink.done_with_trailer(
  14668. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14669. } break;
  14670. }
  14671. (*i)++;
  14672. return true;
  14673. },
  14674. [i](bool success) {
  14675. EXPECT_TRUE(success);
  14676. delete i;
  14677. });
  14678. });
  14679. // Echo headers endpoint for header-related tests
  14680. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14681. std::string body;
  14682. for (const auto &h : req.headers) {
  14683. body.append(h.first);
  14684. body.push_back(':');
  14685. body.append(h.second);
  14686. body.push_back('\n');
  14687. }
  14688. res.set_content(body, "text/plain");
  14689. });
  14690. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14691. std::string body;
  14692. for (const auto &h : req.headers) {
  14693. body.append(h.first);
  14694. body.push_back(':');
  14695. body.append(h.second);
  14696. body.push_back('\n');
  14697. }
  14698. res.set_content(body, "text/plain");
  14699. });
  14700. port_ = svr_.bind_to_any_port("127.0.0.1");
  14701. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14702. svr_.wait_until_ready();
  14703. }
  14704. void TearDown() override {
  14705. svr_.stop();
  14706. if (thread_.joinable()) thread_.join();
  14707. }
  14708. Server svr_;
  14709. std::thread thread_;
  14710. int port_ = 0;
  14711. };
  14712. TEST_F(OpenStreamTest, Basic) {
  14713. Client cli("127.0.0.1", port_);
  14714. auto handle = cli.open_stream("GET", "/hello");
  14715. EXPECT_TRUE(handle.is_valid());
  14716. EXPECT_EQ("Hello World!", read_all(handle));
  14717. }
  14718. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14719. Client cli("127.0.0.1", port_);
  14720. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14721. ASSERT_TRUE(handle.is_valid());
  14722. EXPECT_EQ("Hello World!", read_all(handle));
  14723. }
  14724. TEST_F(OpenStreamTest, SmallBuffer) {
  14725. Client cli("127.0.0.1", port_);
  14726. auto handle = cli.open_stream("GET", "/hello");
  14727. std::string result;
  14728. char buf[4];
  14729. ssize_t n;
  14730. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14731. result.append(buf, static_cast<size_t>(n));
  14732. EXPECT_EQ("Hello World!", result);
  14733. }
  14734. TEST_F(OpenStreamTest, DefaultHeaders) {
  14735. Client cli("127.0.0.1", port_);
  14736. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14737. {
  14738. auto handle = cli.open_stream("GET", "/echo-headers");
  14739. ASSERT_TRUE(handle.is_valid());
  14740. auto body = read_all(handle);
  14741. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14742. std::string::npos);
  14743. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14744. std::string::npos);
  14745. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14746. }
  14747. // open_stream POST with body and no explicit content_type should NOT add
  14748. // text/plain Content-Type (behavior differs from non-streaming path), but
  14749. // should include Content-Length
  14750. {
  14751. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14752. ASSERT_TRUE(handle.is_valid());
  14753. auto body = read_all(handle);
  14754. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14755. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14756. }
  14757. // open_stream POST with explicit Content-Type should preserve it
  14758. {
  14759. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14760. {{"Content-Type", "application/custom"}},
  14761. "{}", "application/custom");
  14762. ASSERT_TRUE(handle.is_valid());
  14763. auto body = read_all(handle);
  14764. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14765. }
  14766. // User-specified User-Agent must not be overwritten for stream API
  14767. {
  14768. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14769. {{"User-Agent", "MyAgent/1.2"}});
  14770. ASSERT_TRUE(handle.is_valid());
  14771. auto body = read_all(handle);
  14772. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14773. }
  14774. }
  14775. TEST_F(OpenStreamTest, Large) {
  14776. Client cli("127.0.0.1", port_);
  14777. auto handle = cli.open_stream("GET", "/large");
  14778. EXPECT_EQ(10000u, read_all(handle).size());
  14779. }
  14780. TEST_F(OpenStreamTest, ConnectionError) {
  14781. Client cli("127.0.0.1", 9999);
  14782. auto handle = cli.open_stream("GET", "/hello");
  14783. EXPECT_FALSE(handle.is_valid());
  14784. }
  14785. TEST_F(OpenStreamTest, Chunked) {
  14786. Client cli("127.0.0.1", port_);
  14787. auto handle = cli.open_stream("GET", "/chunked");
  14788. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14789. "Transfer-Encoding") == "chunked");
  14790. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14791. }
  14792. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14793. Client cli("127.0.0.1", port_);
  14794. auto handle =
  14795. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14796. ASSERT_TRUE(handle.is_valid());
  14797. // Consume body to allow trailers to be received/parsed
  14798. auto body = read_all(handle);
  14799. // Explicitly parse trailers (ensure trailers are available for assertion)
  14800. handle.parse_trailers_if_needed();
  14801. EXPECT_EQ(std::string("123456789"), body);
  14802. // The response should include a Trailer header declaring both names
  14803. ASSERT_TRUE(handle.response);
  14804. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14805. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14806. handle.response->get_header_value("Trailer"));
  14807. // Prohibited trailer must not be present
  14808. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14809. // Allowed trailer should be present
  14810. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14811. EXPECT_EQ(std::string("yes"),
  14812. handle.response->get_trailer_value("X-Allowed"));
  14813. // Verify trailers are NOT present as regular headers
  14814. EXPECT_EQ(std::string(""),
  14815. handle.response->get_header_value("Content-Length"));
  14816. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14817. }
  14818. static std::thread serve_single_response(std::promise<int> &port_promise,
  14819. const std::string &response) {
  14820. return std::thread([&port_promise, response] {
  14821. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14822. default_socket_options(srv);
  14823. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14825. sockaddr_in addr{};
  14826. addr.sin_family = AF_INET;
  14827. addr.sin_port = htons(0); // Let OS assign a free port
  14828. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14829. int opt = 1;
  14830. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14831. #ifdef _WIN32
  14832. reinterpret_cast<const char *>(&opt),
  14833. #else
  14834. &opt,
  14835. #endif
  14836. sizeof(opt));
  14837. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14838. ::listen(srv, 1) != 0) {
  14839. port_promise.set_value(-1);
  14840. detail::close_socket(srv);
  14841. return;
  14842. }
  14843. socklen_t addr_len = sizeof(addr);
  14844. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14845. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14846. sockaddr_in cli_addr{};
  14847. socklen_t cli_len = sizeof(cli_addr);
  14848. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14849. if (cli != INVALID_SOCKET) {
  14850. // Read the complete HTTP request (until the blank line that terminates
  14851. // headers) before sending the response. If the server closes the socket
  14852. // while the client's request data is still unread in the kernel receive
  14853. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14854. // connection on both sides: it discards the client's receive buffer
  14855. // (which already holds our response) and causes any in-progress write on
  14856. // the client to fail with ECONNRESET. Reading all request data first
  14857. // ensures close() emits a graceful FIN.
  14858. {
  14859. char rbuf[256];
  14860. std::string req;
  14861. while (req.find("\r\n\r\n") == std::string::npos) {
  14862. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14863. if (n <= 0) { break; }
  14864. req.append(rbuf, static_cast<size_t>(n));
  14865. }
  14866. }
  14867. ::send(cli,
  14868. #ifdef _WIN32
  14869. static_cast<const char *>(response.c_str()),
  14870. static_cast<int>(response.size()),
  14871. #else
  14872. response.c_str(), response.size(),
  14873. #endif
  14874. 0);
  14875. detail::close_socket(cli);
  14876. }
  14877. detail::close_socket(srv);
  14878. });
  14879. }
  14880. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14881. #ifndef _WIN32
  14882. signal(SIGPIPE, SIG_IGN);
  14883. #endif
  14884. std::promise<int> port_promise;
  14885. auto port_future = port_promise.get_future();
  14886. auto server_thread =
  14887. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14888. "Content-Type: text/plain\r\n"
  14889. "Content-Length: not-a-number\r\n"
  14890. "Connection: close\r\n"
  14891. "\r\n"
  14892. "hello");
  14893. auto port = port_future.get();
  14894. ASSERT_GT(port, 0);
  14895. Client cli("127.0.0.1", port);
  14896. auto handle = cli.open_stream("GET", "/");
  14897. EXPECT_FALSE(handle.is_valid());
  14898. server_thread.join();
  14899. }
  14900. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14901. #ifndef _WIN32
  14902. signal(SIGPIPE, SIG_IGN);
  14903. #endif
  14904. std::promise<int> port_promise;
  14905. auto port_future = port_promise.get_future();
  14906. auto server_thread = serve_single_response(
  14907. port_promise, "HTTP/1.1 200 OK\r\n"
  14908. "Content-Type: text/plain\r\n"
  14909. "Content-Length: 99999999999999999999999999\r\n"
  14910. "Connection: close\r\n"
  14911. "\r\n"
  14912. "hello");
  14913. auto port = port_future.get();
  14914. ASSERT_GT(port, 0);
  14915. // Historically std::stoull would throw std::out_of_range here and crash
  14916. // the process, then parsing silently clamped to a bogus framing length and
  14917. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14918. // so the stream fails to open, matching the not-a-number case above. The
  14919. // process still must NOT terminate.
  14920. Client cli("127.0.0.1", port);
  14921. auto handle = cli.open_stream("GET", "/");
  14922. EXPECT_FALSE(handle.is_valid());
  14923. server_thread.join();
  14924. }
  14925. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14926. TEST_F(OpenStreamTest, Gzip) {
  14927. Client cli("127.0.0.1", port_);
  14928. auto handle = cli.open_stream("GET", "/compressible", {},
  14929. {{"Accept-Encoding", "gzip"}});
  14930. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14931. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14932. }
  14933. #endif
  14934. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14935. TEST_F(OpenStreamTest, Brotli) {
  14936. Client cli("127.0.0.1", port_);
  14937. auto handle =
  14938. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14939. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14940. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14941. }
  14942. #endif
  14943. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14944. TEST_F(OpenStreamTest, Zstd) {
  14945. Client cli("127.0.0.1", port_);
  14946. auto handle = cli.open_stream("GET", "/compressible", {},
  14947. {{"Accept-Encoding", "zstd"}});
  14948. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14949. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14950. }
  14951. #endif
  14952. #ifdef CPPHTTPLIB_SSL_ENABLED
  14953. class SSLOpenStreamTest : public ::testing::Test {
  14954. protected:
  14955. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14956. void SetUp() override {
  14957. svr_.Get("/hello", [](const Request &, Response &res) {
  14958. res.set_content("Hello SSL World!", "text/plain");
  14959. });
  14960. svr_.Get("/chunked", [](const Request &, Response &res) {
  14961. res.set_chunked_content_provider("text/plain",
  14962. [](size_t offset, DataSink &sink) {
  14963. if (offset < 15) {
  14964. sink.write("chunk", 5);
  14965. return true;
  14966. }
  14967. sink.done();
  14968. return true;
  14969. });
  14970. });
  14971. svr_.Post("/echo", [](const Request &req, Response &res) {
  14972. res.set_content(req.body, req.get_header_value("Content-Type"));
  14973. });
  14974. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14975. std::string body = req.body;
  14976. res.set_chunked_content_provider(
  14977. "text/plain", [body](size_t offset, DataSink &sink) {
  14978. if (offset < body.size()) {
  14979. sink.write(body.data() + offset, body.size() - offset);
  14980. }
  14981. sink.done();
  14982. return true;
  14983. });
  14984. });
  14985. port_ = svr_.bind_to_any_port("127.0.0.1");
  14986. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14987. svr_.wait_until_ready();
  14988. }
  14989. void TearDown() override {
  14990. svr_.stop();
  14991. if (thread_.joinable()) thread_.join();
  14992. }
  14993. SSLServer svr_;
  14994. std::thread thread_;
  14995. int port_ = 0;
  14996. };
  14997. TEST_F(SSLOpenStreamTest, Basic) {
  14998. SSLClient cli("127.0.0.1", port_);
  14999. cli.enable_server_certificate_verification(false);
  15000. auto handle = cli.open_stream("GET", "/hello");
  15001. ASSERT_TRUE(handle.is_valid());
  15002. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15003. }
  15004. TEST_F(SSLOpenStreamTest, Chunked) {
  15005. SSLClient cli("127.0.0.1", port_);
  15006. cli.enable_server_certificate_verification(false);
  15007. auto handle = cli.open_stream("GET", "/chunked");
  15008. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15009. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15010. "Transfer-Encoding") == "chunked");
  15011. auto body = read_all(handle);
  15012. EXPECT_EQ("chunkchunkchunk", body);
  15013. }
  15014. TEST_F(SSLOpenStreamTest, Post) {
  15015. SSLClient cli("127.0.0.1", port_);
  15016. cli.enable_server_certificate_verification(false);
  15017. auto handle =
  15018. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15019. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15020. EXPECT_EQ(200, handle.response->status);
  15021. auto body = read_all(handle);
  15022. EXPECT_EQ("Hello SSL POST", body);
  15023. }
  15024. TEST_F(SSLOpenStreamTest, PostChunked) {
  15025. SSLClient cli("127.0.0.1", port_);
  15026. cli.enable_server_certificate_verification(false);
  15027. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15028. "Chunked SSL Data", "text/plain");
  15029. ASSERT_TRUE(handle.is_valid());
  15030. EXPECT_EQ(200, handle.response->status);
  15031. auto body = read_all(handle);
  15032. EXPECT_EQ("Chunked SSL Data", body);
  15033. }
  15034. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15035. // Content-Length is terminated by the server closing the connection. When the
  15036. // SSL peer sends a close_notify after the body, the client must treat it as a
  15037. // clean EOF and return a successful response rather than an error.
  15038. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15040. ASSERT_TRUE(svr.is_valid());
  15041. svr.set_keep_alive_max_count(1);
  15042. const std::string expected_body = "Hello from connection-close response!";
  15043. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15044. res.set_content_provider("text/plain",
  15045. [&](size_t offset, DataSink &sink) -> bool {
  15046. if (offset < expected_body.size()) {
  15047. sink.write(expected_body.data() + offset,
  15048. expected_body.size() - offset);
  15049. }
  15050. sink.done();
  15051. return true;
  15052. });
  15053. });
  15054. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15055. auto se = detail::scope_exit([&] {
  15056. svr.stop();
  15057. listen_thread.join();
  15058. ASSERT_FALSE(svr.is_running());
  15059. });
  15060. svr.wait_until_ready();
  15061. SSLClient cli(HOST, PORT);
  15062. cli.enable_server_certificate_verification(false);
  15063. auto res = cli.Get("/no-content-length");
  15064. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15065. EXPECT_EQ(StatusCode::OK_200, res->status);
  15066. EXPECT_EQ(expected_body, res->body);
  15067. }
  15068. #endif // CPPHTTPLIB_SSL_ENABLED
  15069. //==============================================================================
  15070. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15071. // results for various scenarios.
  15072. //==============================================================================
  15073. TEST(ParityTest, GetVsOpenStream) {
  15074. Server svr;
  15075. const std::string path = "/parity";
  15076. const std::string content = "Parity test content: hello world";
  15077. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15078. res.set_content(content, "text/plain");
  15079. });
  15080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15081. auto se = detail::scope_exit([&] {
  15082. svr.stop();
  15083. t.join();
  15084. ASSERT_FALSE(svr.is_running());
  15085. });
  15086. svr.wait_until_ready();
  15087. Client cli(HOST, PORT);
  15088. // Non-stream path
  15089. auto r1 = cli.Get(path);
  15090. ASSERT_TRUE(r1);
  15091. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15092. // Stream path
  15093. auto h = cli.open_stream("GET", path);
  15094. ASSERT_TRUE(h.is_valid());
  15095. EXPECT_EQ(r1->body, read_all(h));
  15096. }
  15097. // Helper to compress data with provided compressor type T
  15098. template <typename Compressor>
  15099. static std::string compress_payload_for_parity(const std::string &in) {
  15100. std::string out;
  15101. Compressor compressor;
  15102. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15103. [&](const char *data, size_t n) {
  15104. out.append(data, n);
  15105. return true;
  15106. });
  15107. EXPECT_TRUE(ok);
  15108. return out;
  15109. }
  15110. // Helper function for compression parity tests
  15111. template <typename Compressor>
  15112. static void test_compression_parity(const std::string &original,
  15113. const std::string &path,
  15114. const std::string &encoding) {
  15115. const std::string compressed =
  15116. compress_payload_for_parity<Compressor>(original);
  15117. Server svr;
  15118. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15119. res.set_content(compressed, "application/octet-stream");
  15120. res.set_header("Content-Encoding", encoding);
  15121. });
  15122. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15123. auto se = detail::scope_exit([&] {
  15124. svr.stop();
  15125. t.join();
  15126. ASSERT_FALSE(svr.is_running());
  15127. });
  15128. svr.wait_until_ready();
  15129. Client cli(HOST, PORT);
  15130. // Non-streaming
  15131. {
  15132. auto res = cli.Get(path);
  15133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15134. EXPECT_EQ(StatusCode::OK_200, res->status);
  15135. EXPECT_EQ(original, res->body);
  15136. }
  15137. // Streaming
  15138. {
  15139. auto h = cli.open_stream("GET", path);
  15140. ASSERT_TRUE(h.is_valid());
  15141. EXPECT_EQ(original, read_all(h));
  15142. }
  15143. }
  15144. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15145. TEST(ParityTest, Gzip) {
  15146. test_compression_parity<detail::gzip_compressor>(
  15147. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15148. }
  15149. #endif
  15150. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15151. TEST(ParityTest, Brotli) {
  15152. test_compression_parity<detail::brotli_compressor>(
  15153. "Hello, brotli parity test payload", "/parity-br", "br");
  15154. }
  15155. #endif
  15156. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15157. TEST(ParityTest, Zstd) {
  15158. test_compression_parity<detail::zstd_compressor>(
  15159. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15160. }
  15161. #endif
  15162. //==============================================================================
  15163. // New Stream API Tests
  15164. //==============================================================================
  15165. inline std::string read_body(httplib::stream::Result &result) {
  15166. std::string body;
  15167. while (result.next()) {
  15168. body.append(result.data(), result.size());
  15169. }
  15170. return body;
  15171. }
  15172. TEST(ClientConnectionTest, Basic) {
  15173. httplib::ClientConnection conn;
  15174. EXPECT_FALSE(conn.is_open());
  15175. conn.sock = 1;
  15176. EXPECT_TRUE(conn.is_open());
  15177. httplib::ClientConnection conn2(std::move(conn));
  15178. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15179. conn2.sock = INVALID_SOCKET;
  15180. }
  15181. // Unified test server for all stream::* tests
  15182. class StreamApiTest : public ::testing::Test {
  15183. protected:
  15184. void SetUp() override {
  15185. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15186. res.set_content("Hello World!", "text/plain");
  15187. });
  15188. svr_.Get("/echo-params",
  15189. [](const httplib::Request &req, httplib::Response &res) {
  15190. std::string r;
  15191. for (const auto &p : req.params) {
  15192. if (!r.empty()) r += "&";
  15193. r += p.first + "=" + p.second;
  15194. }
  15195. res.set_content(r, "text/plain");
  15196. });
  15197. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15198. res.set_content(req.body, req.get_header_value("Content-Type"));
  15199. });
  15200. svr_.Post("/echo-headers",
  15201. [](const httplib::Request &req, httplib::Response &res) {
  15202. std::string r;
  15203. for (const auto &h : req.headers)
  15204. r += h.first + ": " + h.second + "\n";
  15205. res.set_content(r, "text/plain");
  15206. });
  15207. svr_.Post("/echo-params",
  15208. [](const httplib::Request &req, httplib::Response &res) {
  15209. std::string r = "params:";
  15210. for (const auto &p : req.params)
  15211. r += p.first + "=" + p.second + ";";
  15212. res.set_content(r + " body:" + req.body, "text/plain");
  15213. });
  15214. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15215. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15216. });
  15217. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15218. res.set_content("PUT:" + req.body, "text/plain");
  15219. });
  15220. svr_.Patch("/echo",
  15221. [](const httplib::Request &req, httplib::Response &res) {
  15222. res.set_content("PATCH:" + req.body, "text/plain");
  15223. });
  15224. svr_.Delete(
  15225. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15226. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15227. "text/plain");
  15228. });
  15229. svr_.Get("/head-test",
  15230. [](const httplib::Request &, httplib::Response &res) {
  15231. res.set_content("body for HEAD", "text/plain");
  15232. });
  15233. svr_.Options("/options",
  15234. [](const httplib::Request &, httplib::Response &res) {
  15235. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15236. });
  15237. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15238. svr_.wait_until_ready();
  15239. }
  15240. void TearDown() override {
  15241. svr_.stop();
  15242. if (thread_.joinable()) thread_.join();
  15243. }
  15244. httplib::Server svr_;
  15245. std::thread thread_;
  15246. };
  15247. // stream::Get tests
  15248. TEST_F(StreamApiTest, GetBasic) {
  15249. httplib::Client cli(HOST, PORT);
  15250. auto result = httplib::stream::Get(cli, "/hello");
  15251. ASSERT_TRUE(result.is_valid());
  15252. EXPECT_EQ(200, result.status());
  15253. EXPECT_EQ("Hello World!", read_body(result));
  15254. }
  15255. TEST_F(StreamApiTest, GetWithParams) {
  15256. httplib::Client cli(HOST, PORT);
  15257. httplib::Params params{{"foo", "bar"}};
  15258. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15259. ASSERT_TRUE(result.is_valid());
  15260. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15261. }
  15262. TEST_F(StreamApiTest, GetConnectionError) {
  15263. httplib::Client cli(HOST, 9999);
  15264. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15265. }
  15266. TEST_F(StreamApiTest, Get404) {
  15267. httplib::Client cli(HOST, PORT);
  15268. auto result = httplib::stream::Get(cli, "/nonexistent");
  15269. EXPECT_TRUE(result.is_valid());
  15270. EXPECT_EQ(404, result.status());
  15271. }
  15272. // stream::Post tests
  15273. TEST_F(StreamApiTest, PostBasic) {
  15274. httplib::Client cli(HOST, PORT);
  15275. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15276. "application/json");
  15277. ASSERT_TRUE(result.is_valid());
  15278. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15279. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15280. }
  15281. TEST_F(StreamApiTest, PostWithHeaders) {
  15282. httplib::Client cli(HOST, PORT);
  15283. httplib::Headers headers{{"X-Custom", "value"}};
  15284. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15285. "text/plain");
  15286. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15287. }
  15288. TEST_F(StreamApiTest, PostWithParams) {
  15289. httplib::Client cli(HOST, PORT);
  15290. httplib::Params params{{"k", "v"}};
  15291. auto result =
  15292. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15293. auto body = read_body(result);
  15294. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15295. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15296. }
  15297. TEST_F(StreamApiTest, PostLarge) {
  15298. httplib::Client cli(HOST, PORT);
  15299. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15300. size_t total = 0;
  15301. while (result.next()) {
  15302. total += result.size();
  15303. }
  15304. EXPECT_EQ(100u * 1024u, total);
  15305. }
  15306. // stream::Put/Patch tests
  15307. TEST_F(StreamApiTest, PutAndPatch) {
  15308. httplib::Client cli(HOST, PORT);
  15309. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15310. EXPECT_EQ("PUT:test", read_body(put));
  15311. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15312. EXPECT_EQ("PATCH:test", read_body(patch));
  15313. }
  15314. // stream::Delete tests
  15315. TEST_F(StreamApiTest, Delete) {
  15316. httplib::Client cli(HOST, PORT);
  15317. auto del1 = httplib::stream::Delete(cli, "/resource");
  15318. EXPECT_EQ("Deleted", read_body(del1));
  15319. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15320. EXPECT_EQ("Deleted:data", read_body(del2));
  15321. }
  15322. // stream::Head/Options tests
  15323. TEST_F(StreamApiTest, HeadAndOptions) {
  15324. httplib::Client cli(HOST, PORT);
  15325. auto head = httplib::stream::Head(cli, "/head-test");
  15326. EXPECT_TRUE(head.is_valid());
  15327. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15328. auto opts = httplib::stream::Options(cli, "/options");
  15329. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15330. }
  15331. // SSL stream::* tests
  15332. #ifdef CPPHTTPLIB_SSL_ENABLED
  15333. class SSLStreamApiTest : public ::testing::Test {
  15334. protected:
  15335. void SetUp() override {
  15336. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15337. res.set_content("Hello SSL!", "text/plain");
  15338. });
  15339. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15340. res.set_content(req.body, "text/plain");
  15341. });
  15342. port_ = svr_.bind_to_any_port("127.0.0.1");
  15343. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15344. svr_.wait_until_ready();
  15345. }
  15346. void TearDown() override {
  15347. svr_.stop();
  15348. if (thread_.joinable()) thread_.join();
  15349. }
  15350. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15351. std::thread thread_;
  15352. int port_ = 0;
  15353. };
  15354. TEST_F(SSLStreamApiTest, GetAndPost) {
  15355. httplib::SSLClient cli("127.0.0.1", port_);
  15356. cli.enable_server_certificate_verification(false);
  15357. auto get = httplib::stream::Get(cli, "/hello");
  15358. EXPECT_EQ("Hello SSL!", read_body(get));
  15359. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15360. EXPECT_EQ("test", read_body(post));
  15361. }
  15362. #endif
  15363. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15364. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15365. // BodyReader
  15366. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15367. // Test that read timeout during streaming is detected
  15368. // Use a large content-length response where server delays mid-stream
  15369. Server svr;
  15370. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15371. // Send a large response with delay in the middle
  15372. res.set_content_provider(
  15373. 1000, // content_length
  15374. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15375. if (offset < 100) {
  15376. // Send first 100 bytes immediately
  15377. std::string data(100, 'A');
  15378. sink.write(data.c_str(), data.size());
  15379. return true;
  15380. }
  15381. // Then delay longer than client timeout
  15382. std::this_thread::sleep_for(std::chrono::seconds(3));
  15383. std::string data(900, 'B');
  15384. sink.write(data.c_str(), data.size());
  15385. return true;
  15386. });
  15387. });
  15388. auto port = 8091;
  15389. std::thread t([&]() { svr.listen("localhost", port); });
  15390. svr.wait_until_ready();
  15391. Client cli("localhost", port);
  15392. cli.set_read_timeout(1, 0); // 1 second timeout
  15393. auto handle = cli.open_stream("GET", "/slow-stream");
  15394. ASSERT_TRUE(handle.is_valid());
  15395. char buf[256];
  15396. ssize_t total = 0;
  15397. ssize_t n;
  15398. bool got_error = false;
  15399. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15400. total += n;
  15401. }
  15402. if (n < 0) {
  15403. got_error = true;
  15404. // Should be timeout or read error
  15405. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15406. handle.get_read_error() == Error::Read)
  15407. << "Actual error: " << to_string(handle.get_read_error());
  15408. }
  15409. // Either we got an error, or we got less data than expected
  15410. EXPECT_TRUE(got_error || total < 1000)
  15411. << "Expected timeout but got all " << total << " bytes";
  15412. svr.stop();
  15413. t.join();
  15414. }
  15415. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15416. // Test connection closed detection via BodyReader
  15417. Server svr;
  15418. std::atomic<bool> close_now{false};
  15419. svr.Get("/will-close", [&](const Request &, Response &res) {
  15420. res.set_content_provider(
  15421. 10000, // Large content_length that we won't fully send
  15422. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15423. if (offset < 100) {
  15424. std::string data(100, 'X');
  15425. sink.write(data.c_str(), data.size());
  15426. return true;
  15427. }
  15428. // Wait for signal then abort
  15429. while (!close_now) {
  15430. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15431. }
  15432. return false; // Abort - server will close connection
  15433. });
  15434. });
  15435. auto port = 8092;
  15436. std::thread t([&]() { svr.listen("localhost", port); });
  15437. svr.wait_until_ready();
  15438. Client cli("localhost", port);
  15439. auto handle = cli.open_stream("GET", "/will-close");
  15440. ASSERT_TRUE(handle.is_valid());
  15441. char buf[256];
  15442. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15443. EXPECT_GT(n, 0) << "First read should succeed";
  15444. // Signal server to close
  15445. close_now = true;
  15446. // Keep reading until error or EOF
  15447. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15448. // Keep reading
  15449. }
  15450. // Should get an error since content_length wasn't satisfied
  15451. if (n < 0) {
  15452. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15453. handle.get_read_error() == Error::Read)
  15454. << "Actual error: " << to_string(handle.get_read_error());
  15455. }
  15456. svr.stop();
  15457. t.join();
  15458. }
  15459. #ifdef CPPHTTPLIB_SSL_ENABLED
  15460. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15461. // Test that read timeout during SSL streaming is detected
  15462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15463. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15464. res.set_content_provider(
  15465. 1000, "text/plain",
  15466. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15467. if (offset < 100) {
  15468. std::string data(100, 'A');
  15469. sink.write(data.c_str(), data.size());
  15470. return true;
  15471. }
  15472. std::this_thread::sleep_for(std::chrono::seconds(3));
  15473. std::string data(900, 'B');
  15474. sink.write(data.c_str(), data.size());
  15475. return true;
  15476. });
  15477. });
  15478. auto port = 8093;
  15479. std::thread t([&]() { svr.listen("localhost", port); });
  15480. svr.wait_until_ready();
  15481. SSLClient cli("localhost", port);
  15482. cli.enable_server_certificate_verification(false);
  15483. cli.set_read_timeout(1, 0); // 1 second timeout
  15484. auto handle = cli.open_stream("GET", "/slow-stream");
  15485. ASSERT_TRUE(handle.is_valid());
  15486. char buf[256];
  15487. ssize_t total = 0;
  15488. ssize_t n;
  15489. bool got_error = false;
  15490. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15491. total += n;
  15492. }
  15493. if (n < 0) {
  15494. got_error = true;
  15495. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15496. handle.get_read_error() == Error::Read)
  15497. << "Actual error: " << to_string(handle.get_read_error());
  15498. }
  15499. EXPECT_TRUE(got_error || total < 1000)
  15500. << "Expected timeout but got all " << total << " bytes";
  15501. svr.stop();
  15502. t.join();
  15503. }
  15504. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15505. // Test SSL connection closed detection
  15506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15507. std::atomic<bool> close_now{false};
  15508. svr.Get("/will-close", [&](const Request &, Response &res) {
  15509. res.set_content_provider(
  15510. 10000, "text/plain",
  15511. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15512. if (offset < 100) {
  15513. std::string data(100, 'X');
  15514. sink.write(data.c_str(), data.size());
  15515. return true;
  15516. }
  15517. while (!close_now) {
  15518. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15519. }
  15520. return false;
  15521. });
  15522. });
  15523. auto port = 8094;
  15524. std::thread t([&]() { svr.listen("localhost", port); });
  15525. svr.wait_until_ready();
  15526. SSLClient cli("localhost", port);
  15527. cli.enable_server_certificate_verification(false);
  15528. auto handle = cli.open_stream("GET", "/will-close");
  15529. ASSERT_TRUE(handle.is_valid());
  15530. char buf[256];
  15531. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15532. EXPECT_GT(n, 0);
  15533. // Signal server to close
  15534. close_now = true;
  15535. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15536. // Keep reading
  15537. }
  15538. if (n < 0) {
  15539. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15540. handle.get_read_error() == Error::Read)
  15541. << "Actual error: " << to_string(handle.get_read_error());
  15542. }
  15543. svr.stop();
  15544. t.join();
  15545. }
  15546. #endif
  15547. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15548. using namespace httplib;
  15549. // Create a test file
  15550. const char *fname = "etag_testfile.txt";
  15551. const char *content = "etag-content";
  15552. {
  15553. std::ofstream ofs(fname);
  15554. ofs << content;
  15555. ASSERT_TRUE(ofs.good());
  15556. }
  15557. Server svr;
  15558. svr.set_mount_point("/static", ".");
  15559. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15560. svr.wait_until_ready();
  15561. Client cli(HOST, PORT);
  15562. // First request: should get 200 with ETag header
  15563. auto res1 = cli.Get("/static/etag_testfile.txt");
  15564. ASSERT_TRUE(res1);
  15565. ASSERT_EQ(200, res1->status);
  15566. ASSERT_TRUE(res1->has_header("ETag"));
  15567. std::string etag = res1->get_header_value("ETag");
  15568. EXPECT_FALSE(etag.empty());
  15569. // Verify ETag format: W/"hex-hex"
  15570. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15571. EXPECT_EQ('W', etag[0]);
  15572. EXPECT_EQ('/', etag[1]);
  15573. EXPECT_EQ('"', etag[2]);
  15574. EXPECT_EQ('"', etag.back());
  15575. // Exact match: expect 304 Not Modified
  15576. Headers h2 = {{"If-None-Match", etag}};
  15577. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15578. ASSERT_TRUE(res2);
  15579. EXPECT_EQ(304, res2->status);
  15580. // Wildcard match: expect 304 Not Modified
  15581. Headers h3 = {{"If-None-Match", "*"}};
  15582. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15583. ASSERT_TRUE(res3);
  15584. EXPECT_EQ(304, res3->status);
  15585. // Non-matching ETag: expect 200
  15586. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15587. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15588. ASSERT_TRUE(res4);
  15589. EXPECT_EQ(200, res4->status);
  15590. // Multiple ETags with one matching: expect 304
  15591. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15592. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15593. ASSERT_TRUE(res5);
  15594. EXPECT_EQ(304, res5->status);
  15595. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  15596. // that equivalent to the single comma-separated list above, so the match on
  15597. // the second line must still be found.
  15598. Headers h6;
  15599. h6.emplace("If-None-Match", "W/\"other\"");
  15600. h6.emplace("If-None-Match", etag);
  15601. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  15602. ASSERT_TRUE(res6);
  15603. EXPECT_EQ(304, res6->status);
  15604. svr.stop();
  15605. t.join();
  15606. std::remove(fname);
  15607. }
  15608. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15609. using namespace httplib;
  15610. Server svr;
  15611. svr.set_mount_point("/static", ".");
  15612. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15613. svr.wait_until_ready();
  15614. Client cli(HOST, PORT);
  15615. // Send If-None-Match: * to a non-existent file
  15616. Headers h = {{"If-None-Match", "*"}};
  15617. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15619. EXPECT_EQ(404, res->status);
  15620. svr.stop();
  15621. t.join();
  15622. }
  15623. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15624. using namespace httplib;
  15625. // Create a test file
  15626. const char *fname = "etag_boundary_testfile.txt";
  15627. const char *content = "boundary-test";
  15628. {
  15629. std::ofstream ofs(fname);
  15630. ofs << content;
  15631. ASSERT_TRUE(ofs.good());
  15632. }
  15633. Server svr;
  15634. svr.set_mount_point("/static", ".");
  15635. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15636. svr.wait_until_ready();
  15637. Client cli(HOST, PORT);
  15638. // Get the actual ETag
  15639. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15640. ASSERT_TRUE(res1);
  15641. ASSERT_EQ(200, res1->status);
  15642. ASSERT_TRUE(res1->has_header("ETag"));
  15643. std::string etag = res1->get_header_value("ETag");
  15644. // Test 1: Very long ETag value (longer than actual ETag)
  15645. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15646. Headers h1 = {{"If-None-Match", "W/"
  15647. "\"very-long-etag-value-that-is-much-longer-"
  15648. "than-the-actual-etag-value\""}};
  15649. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15650. ASSERT_TRUE(res2);
  15651. EXPECT_EQ(200, res2->status); // Should not match
  15652. // Test 2: Long string followed by wildcard
  15653. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15654. // string)
  15655. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15656. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15657. ASSERT_TRUE(res3);
  15658. EXPECT_EQ(304, res3->status); // Should match on "*"
  15659. // Test 3: Wildcard followed by long string
  15660. // Should match on "*" immediately and return 304
  15661. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15662. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15663. ASSERT_TRUE(res4);
  15664. EXPECT_EQ(304, res4->status); // Should match on "*"
  15665. // Test 4: Multiple long non-matching values
  15666. // Should NOT match and return 200 (test that all comparisons are safe)
  15667. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15668. "W/\"second-long-non-matching-value\", "
  15669. "W/\"third-long-non-matching-value\""}};
  15670. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15671. ASSERT_TRUE(res5);
  15672. EXPECT_EQ(200, res5->status); // Should not match
  15673. // Test 5: Single character that is not "*" (edge case)
  15674. Headers h5 = {{"If-None-Match", "X"}};
  15675. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15676. ASSERT_TRUE(res6);
  15677. EXPECT_EQ(200, res6->status); // Should not match
  15678. svr.stop();
  15679. t.join();
  15680. std::remove(fname);
  15681. }
  15682. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15683. using namespace httplib;
  15684. // Create a test file
  15685. const char *fname = "ims_testfile.txt";
  15686. const char *content = "if-modified-since-test";
  15687. {
  15688. std::ofstream ofs(fname);
  15689. ofs << content;
  15690. ASSERT_TRUE(ofs.good());
  15691. }
  15692. Server svr;
  15693. svr.set_mount_point("/static", ".");
  15694. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15695. svr.wait_until_ready();
  15696. Client cli(HOST, PORT);
  15697. // First request: should get 200 with Last-Modified header
  15698. auto res1 = cli.Get("/static/ims_testfile.txt");
  15699. ASSERT_TRUE(res1);
  15700. ASSERT_EQ(200, res1->status);
  15701. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15702. std::string last_modified = res1->get_header_value("Last-Modified");
  15703. EXPECT_FALSE(last_modified.empty());
  15704. // If-Modified-Since with same time: expect 304
  15705. Headers h2 = {{"If-Modified-Since", last_modified}};
  15706. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15707. ASSERT_TRUE(res2);
  15708. EXPECT_EQ(304, res2->status);
  15709. // If-Modified-Since with future time: expect 304
  15710. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15711. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15712. ASSERT_TRUE(res3);
  15713. EXPECT_EQ(304, res3->status);
  15714. // If-Modified-Since with past time: expect 200
  15715. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15716. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15717. ASSERT_TRUE(res4);
  15718. EXPECT_EQ(200, res4->status);
  15719. // If-None-Match takes precedence over If-Modified-Since
  15720. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15721. ASSERT_TRUE(res1->has_header("ETag"));
  15722. std::string etag = res1->get_header_value("ETag");
  15723. Headers h5 = {{"If-None-Match", etag},
  15724. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15725. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15726. ASSERT_TRUE(res5);
  15727. EXPECT_EQ(304, res5->status);
  15728. svr.stop();
  15729. t.join();
  15730. std::remove(fname);
  15731. }
  15732. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15733. using namespace httplib;
  15734. Server svr;
  15735. // Endpoint that returns compressible content
  15736. svr.Get("/compressible", [](const Request &, Response &res) {
  15737. // Return a large enough body to trigger compression
  15738. std::string body(1000, 'a');
  15739. res.set_content(body, "text/plain");
  15740. });
  15741. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15742. svr.wait_until_ready();
  15743. Client cli(HOST, PORT);
  15744. // Request with gzip support: should get Vary header when compressed
  15745. cli.set_compress(true);
  15746. auto res1 = cli.Get("/compressible");
  15747. ASSERT_TRUE(res1);
  15748. EXPECT_EQ(200, res1->status);
  15749. // If Content-Encoding is set, Vary should also be set
  15750. if (res1->has_header("Content-Encoding")) {
  15751. EXPECT_TRUE(res1->has_header("Vary"));
  15752. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15753. }
  15754. // Request without Accept-Encoding header: should not have compression
  15755. Headers h_no_compress;
  15756. auto res2 = cli.Get("/compressible", h_no_compress);
  15757. ASSERT_TRUE(res2);
  15758. EXPECT_EQ(200, res2->status);
  15759. // Verify Vary header is present when compression is applied
  15760. // (the exact behavior depends on server configuration)
  15761. svr.stop();
  15762. t.join();
  15763. }
  15764. TEST(ETagTest, IfRangeWithETag) {
  15765. using namespace httplib;
  15766. // Create a test file with known content
  15767. const char *fname = "if_range_testfile.txt";
  15768. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15769. {
  15770. std::ofstream ofs(fname);
  15771. ofs << content;
  15772. ASSERT_TRUE(ofs.good());
  15773. }
  15774. Server svr;
  15775. svr.set_mount_point("/static", ".");
  15776. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15777. svr.wait_until_ready();
  15778. Client cli(HOST, PORT);
  15779. // First request: get ETag
  15780. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15781. ASSERT_TRUE(res1);
  15782. ASSERT_EQ(200, res1->status);
  15783. ASSERT_TRUE(res1->has_header("ETag"));
  15784. std::string etag = res1->get_header_value("ETag");
  15785. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15786. // Since our server generates weak ETags (W/"..."), If-Range with our
  15787. // ETag should NOT result in partial content - it should return full content.
  15788. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15789. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15790. ASSERT_TRUE(res2);
  15791. // Weak ETag in If-Range -> full content (200), not partial (206)
  15792. EXPECT_EQ(200, res2->status);
  15793. EXPECT_EQ(content, res2->body);
  15794. EXPECT_FALSE(res2->has_header("Content-Range"));
  15795. // Range request with non-matching If-Range (ETag): should get 200 (full
  15796. // content)
  15797. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15798. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15799. ASSERT_TRUE(res3);
  15800. EXPECT_EQ(200, res3->status);
  15801. EXPECT_EQ(content, res3->body);
  15802. EXPECT_FALSE(res3->has_header("Content-Range"));
  15803. // Range request with strong ETag (hypothetical - our server doesn't generate
  15804. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15805. // should return full content)
  15806. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15807. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15808. ASSERT_TRUE(res4);
  15809. EXPECT_EQ(200, res4->status);
  15810. EXPECT_EQ(content, res4->body);
  15811. EXPECT_FALSE(res4->has_header("Content-Range"));
  15812. svr.stop();
  15813. t.join();
  15814. std::remove(fname);
  15815. }
  15816. TEST(ETagTest, IfRangeWithDate) {
  15817. using namespace httplib;
  15818. // Create a test file
  15819. const char *fname = "if_range_date_testfile.txt";
  15820. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15821. {
  15822. std::ofstream ofs(fname);
  15823. ofs << content;
  15824. ASSERT_TRUE(ofs.good());
  15825. }
  15826. Server svr;
  15827. svr.set_mount_point("/static", ".");
  15828. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15829. svr.wait_until_ready();
  15830. Client cli(HOST, PORT);
  15831. // First request: get Last-Modified
  15832. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15833. ASSERT_TRUE(res1);
  15834. ASSERT_EQ(200, res1->status);
  15835. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15836. std::string last_modified = res1->get_header_value("Last-Modified");
  15837. // Range request with matching If-Range (date): should get 206
  15838. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15839. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15840. ASSERT_TRUE(res2);
  15841. EXPECT_EQ(206, res2->status);
  15842. EXPECT_EQ("FGHIJ", res2->body);
  15843. // Range request with old If-Range date: should get 200 (full content)
  15844. Headers h3 = {{"Range", "bytes=5-9"},
  15845. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15846. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15847. ASSERT_TRUE(res3);
  15848. EXPECT_EQ(200, res3->status);
  15849. EXPECT_EQ(content, res3->body);
  15850. // Range request with future If-Range date: should get 206
  15851. Headers h4 = {{"Range", "bytes=0-4"},
  15852. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15853. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15854. ASSERT_TRUE(res4);
  15855. EXPECT_EQ(206, res4->status);
  15856. EXPECT_EQ("ABCDE", res4->body);
  15857. svr.stop();
  15858. t.join();
  15859. std::remove(fname);
  15860. }
  15861. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15862. using namespace httplib;
  15863. const char *fname = "etag_malformed.txt";
  15864. const char *content = "malformed-etag";
  15865. {
  15866. std::ofstream ofs(fname);
  15867. ofs << content;
  15868. ASSERT_TRUE(ofs.good());
  15869. }
  15870. Server svr;
  15871. svr.set_mount_point("/static", ".");
  15872. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15873. svr.wait_until_ready();
  15874. Client cli(HOST, PORT);
  15875. // baseline: should get 200 and an ETag
  15876. auto res1 = cli.Get("/static/etag_malformed.txt");
  15877. ASSERT_TRUE(res1);
  15878. ASSERT_EQ(200, res1->status);
  15879. ASSERT_TRUE(res1->has_header("ETag"));
  15880. // Malformed ETag value (missing quotes) should be treated as non-matching
  15881. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15882. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15883. ASSERT_TRUE(res_bad);
  15884. EXPECT_EQ(200, res_bad->status);
  15885. // Whitespace-only header value should be considered invalid / non-matching
  15886. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15887. "Host: localhost\r\n"
  15888. "If-None-Match: \r\n"
  15889. "Connection: close\r\n"
  15890. "\r\n";
  15891. std::string out;
  15892. ASSERT_TRUE(send_request(5, raw_req, &out));
  15893. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15894. svr.stop();
  15895. t.join();
  15896. std::remove(fname);
  15897. }
  15898. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15899. using namespace httplib;
  15900. const char *fname = "ims_invalid_format.txt";
  15901. const char *content = "ims-bad-format";
  15902. {
  15903. std::ofstream ofs(fname);
  15904. ofs << content;
  15905. ASSERT_TRUE(ofs.good());
  15906. }
  15907. Server svr;
  15908. svr.set_mount_point("/static", ".");
  15909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15910. svr.wait_until_ready();
  15911. Client cli(HOST, PORT);
  15912. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15913. ASSERT_TRUE(res1);
  15914. ASSERT_EQ(200, res1->status);
  15915. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15916. // If-Modified-Since with invalid format should not result in 304
  15917. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15918. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15919. ASSERT_TRUE(res_bad);
  15920. EXPECT_EQ(200, res_bad->status);
  15921. // If-Range with invalid date format should be treated as mismatch -> full
  15922. // content (200)
  15923. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15924. {"If-Range", "invalid-date"}};
  15925. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15926. ASSERT_TRUE(res_ifrange);
  15927. EXPECT_EQ(200, res_ifrange->status);
  15928. svr.stop();
  15929. t.join();
  15930. std::remove(fname);
  15931. }
  15932. TEST(ETagTest, IfRangeWithMalformedETag) {
  15933. using namespace httplib;
  15934. const char *fname = "ifrange_malformed.txt";
  15935. const std::string content = "0123456789";
  15936. {
  15937. std::ofstream ofs(fname);
  15938. ofs << content;
  15939. ASSERT_TRUE(ofs.good());
  15940. }
  15941. Server svr;
  15942. svr.set_mount_point("/static", ".");
  15943. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15944. svr.wait_until_ready();
  15945. Client cli(HOST, PORT);
  15946. // First request: get ETag
  15947. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15948. ASSERT_TRUE(res1);
  15949. ASSERT_EQ(200, res1->status);
  15950. ASSERT_TRUE(res1->has_header("ETag"));
  15951. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15952. // full content (200)
  15953. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15954. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15955. ASSERT_TRUE(res2);
  15956. EXPECT_EQ(200, res2->status);
  15957. EXPECT_EQ(content, res2->body);
  15958. svr.stop();
  15959. t.join();
  15960. std::remove(fname);
  15961. }
  15962. TEST(ETagTest, ExtremeLargeDateValues) {
  15963. using namespace httplib;
  15964. const char *fname = "ims_extreme_date.txt";
  15965. const char *content = "ims-extreme-date";
  15966. {
  15967. std::ofstream ofs(fname);
  15968. ofs << content;
  15969. ASSERT_TRUE(ofs.good());
  15970. }
  15971. Server svr;
  15972. svr.set_mount_point("/static", ".");
  15973. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15974. svr.wait_until_ready();
  15975. Client cli(HOST, PORT);
  15976. auto res1 = cli.Get(std::string("/static/") + fname);
  15977. ASSERT_TRUE(res1);
  15978. ASSERT_EQ(200, res1->status);
  15979. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15980. // Extremely large year that may overflow date parsing routines.
  15981. Headers h_large_date = {
  15982. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15983. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15984. ASSERT_TRUE(res_bad);
  15985. // Expect server to treat this as invalid/mismatch and return full content
  15986. EXPECT_EQ(200, res_bad->status);
  15987. // If-Range with extremely large date should be treated as mismatch -> full
  15988. // content (200)
  15989. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15990. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15991. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15992. ASSERT_TRUE(res_ifrange);
  15993. EXPECT_EQ(200, res_ifrange->status);
  15994. svr.stop();
  15995. t.join();
  15996. std::remove(fname);
  15997. }
  15998. TEST(ETagTest, NegativeFileModificationTime) {
  15999. using namespace httplib;
  16000. const char *fname = "ims_negative_mtime.txt";
  16001. const std::string content = "negative-mtime";
  16002. {
  16003. std::ofstream ofs(fname);
  16004. ofs << content;
  16005. ASSERT_TRUE(ofs.good());
  16006. }
  16007. // Try to set file mtime to a negative value. This may fail on some
  16008. // platforms/filesystems; if it fails, the test will still verify server
  16009. // behaves safely by performing a regular conditional request.
  16010. #if defined(__APPLE__) || defined(__linux__)
  16011. bool set_negative = false;
  16012. do {
  16013. struct timeval times[2];
  16014. // access time: now
  16015. times[0].tv_sec = time(nullptr);
  16016. times[0].tv_usec = 0;
  16017. // modification time: negative (e.g., -1)
  16018. times[1].tv_sec = -1;
  16019. times[1].tv_usec = 0;
  16020. if (utimes(fname, times) == 0) { set_negative = true; }
  16021. } while (0);
  16022. #else
  16023. bool set_negative = false;
  16024. #endif
  16025. Server svr;
  16026. svr.set_mount_point("/static", ".");
  16027. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16028. svr.wait_until_ready();
  16029. Client cli(HOST, PORT);
  16030. auto res1 = cli.Get(std::string("/static/") + fname);
  16031. ASSERT_TRUE(res1);
  16032. ASSERT_EQ(200, res1->status);
  16033. bool has_last_modified = res1->has_header("Last-Modified");
  16034. std::string last_modified;
  16035. if (has_last_modified) {
  16036. last_modified = res1->get_header_value("Last-Modified");
  16037. }
  16038. if (set_negative) {
  16039. // If we successfully set a negative mtime, ensure server returns a
  16040. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16041. // with an old date and ensure server handles it without crash.
  16042. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16043. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16044. ASSERT_TRUE(res2);
  16045. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16046. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16047. } else {
  16048. // Could not set negative mtime on this platform; fall back to verifying
  16049. // that normal invalid/malformed dates are treated safely (non-304).
  16050. Headers h_bad_date = {
  16051. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16052. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16053. ASSERT_TRUE(res_bad);
  16054. EXPECT_EQ(200, res_bad->status);
  16055. }
  16056. svr.stop();
  16057. t.join();
  16058. std::remove(fname);
  16059. }
  16060. //==============================================================================
  16061. // SSE Parsing Tests
  16062. //==============================================================================
  16063. class SSEParsingTest : public ::testing::Test {
  16064. protected:
  16065. // Test helper that mimics SSE parsing behavior
  16066. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16067. int &retry_ms) {
  16068. // Blank line signals end of event
  16069. if (line.empty() || line == "\r") { return true; }
  16070. // Lines starting with ':' are comments (ignored)
  16071. if (!line.empty() && line[0] == ':') { return false; }
  16072. // Find the colon separator
  16073. auto colon_pos = line.find(':');
  16074. if (colon_pos == std::string::npos) {
  16075. // Line with no colon is treated as field name with empty value
  16076. return false;
  16077. }
  16078. std::string field = line.substr(0, colon_pos);
  16079. std::string value;
  16080. // Value starts after colon, skip optional single space
  16081. if (colon_pos + 1 < line.size()) {
  16082. size_t value_start = colon_pos + 1;
  16083. if (line[value_start] == ' ') { value_start++; }
  16084. value = line.substr(value_start);
  16085. // Remove trailing \r if present
  16086. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16087. }
  16088. // Handle known fields
  16089. if (field == "event") {
  16090. msg.event = value;
  16091. } else if (field == "data") {
  16092. // Multiple data lines are concatenated with newlines
  16093. if (!msg.data.empty()) { msg.data += "\n"; }
  16094. msg.data += value;
  16095. } else if (field == "id") {
  16096. // Empty id is valid (clears the last event ID)
  16097. msg.id = value;
  16098. } else if (field == "retry") {
  16099. // Parse retry interval in milliseconds
  16100. {
  16101. int v = 0;
  16102. auto res =
  16103. detail::from_chars(value.data(), value.data() + value.size(), v);
  16104. if (res.ec == std::errc{}) { retry_ms = v; }
  16105. }
  16106. }
  16107. // Unknown fields are ignored per SSE spec
  16108. return false;
  16109. }
  16110. };
  16111. // Test: Single-line data
  16112. TEST_F(SSEParsingTest, SingleLineData) {
  16113. sse::SSEMessage msg;
  16114. int retry_ms = 3000;
  16115. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16116. EXPECT_EQ(msg.data, "hello");
  16117. EXPECT_EQ(msg.event, "message");
  16118. // Blank line ends event
  16119. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16120. }
  16121. // Test: Multi-line data
  16122. TEST_F(SSEParsingTest, MultiLineData) {
  16123. sse::SSEMessage msg;
  16124. int retry_ms = 3000;
  16125. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16126. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16127. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16128. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16129. }
  16130. // Test: Custom event types
  16131. TEST_F(SSEParsingTest, CustomEventType) {
  16132. sse::SSEMessage msg;
  16133. int retry_ms = 3000;
  16134. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16135. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16136. EXPECT_EQ(msg.event, "update");
  16137. EXPECT_EQ(msg.data, "payload");
  16138. }
  16139. // Test: Event ID handling
  16140. TEST_F(SSEParsingTest, EventIdHandling) {
  16141. sse::SSEMessage msg;
  16142. int retry_ms = 3000;
  16143. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16144. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16145. EXPECT_EQ(msg.id, "12345");
  16146. }
  16147. // Test: Empty event ID (clears last event ID)
  16148. TEST_F(SSEParsingTest, EmptyEventId) {
  16149. sse::SSEMessage msg;
  16150. msg.id = "previous";
  16151. int retry_ms = 3000;
  16152. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16153. EXPECT_EQ(msg.id, "");
  16154. }
  16155. // Test: Retry field parsing
  16156. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16157. sse::SSEMessage msg;
  16158. int retry_ms = 3000;
  16159. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16160. EXPECT_EQ(retry_ms, 5000);
  16161. }
  16162. // Test: Invalid retry value
  16163. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16164. sse::SSEMessage msg;
  16165. int retry_ms = 3000;
  16166. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16167. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16168. }
  16169. // Test: Comments (lines starting with :)
  16170. TEST_F(SSEParsingTest, CommentsIgnored) {
  16171. sse::SSEMessage msg;
  16172. int retry_ms = 3000;
  16173. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16174. EXPECT_EQ(msg.data, "");
  16175. EXPECT_EQ(msg.event, "message");
  16176. }
  16177. // Test: Colon in value
  16178. TEST_F(SSEParsingTest, ColonInValue) {
  16179. sse::SSEMessage msg;
  16180. int retry_ms = 3000;
  16181. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16182. EXPECT_EQ(msg.data, "hello:world:test");
  16183. }
  16184. // Test: Line with no colon (field name only)
  16185. TEST_F(SSEParsingTest, FieldNameOnly) {
  16186. sse::SSEMessage msg;
  16187. int retry_ms = 3000;
  16188. // According to SSE spec, this is treated as field name with empty value
  16189. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16190. // Since we don't recognize "data" without colon, data should be empty
  16191. EXPECT_EQ(msg.data, "");
  16192. }
  16193. // Test: Trailing \r handling
  16194. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16195. sse::SSEMessage msg;
  16196. int retry_ms = 3000;
  16197. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16198. EXPECT_EQ(msg.data, "hello");
  16199. }
  16200. // Test: Unknown fields ignored
  16201. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16202. sse::SSEMessage msg;
  16203. int retry_ms = 3000;
  16204. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16205. EXPECT_EQ(msg.data, "");
  16206. EXPECT_EQ(msg.event, "message");
  16207. }
  16208. // Test: Space after colon is optional
  16209. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16210. sse::SSEMessage msg1, msg2;
  16211. int retry_ms = 3000;
  16212. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16213. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16214. EXPECT_EQ(msg1.data, "hello");
  16215. EXPECT_EQ(msg2.data, "hello");
  16216. }
  16217. // Test: SSEMessage clear
  16218. TEST_F(SSEParsingTest, MessageClear) {
  16219. sse::SSEMessage msg;
  16220. msg.event = "custom";
  16221. msg.data = "some data";
  16222. msg.id = "123";
  16223. msg.clear();
  16224. EXPECT_EQ(msg.event, "message");
  16225. EXPECT_EQ(msg.data, "");
  16226. EXPECT_EQ(msg.id, "");
  16227. }
  16228. // Test: Complete event parsing
  16229. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16230. sse::SSEMessage msg;
  16231. int retry_ms = 3000;
  16232. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16233. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16234. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16235. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16236. // Blank line ends event
  16237. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16238. EXPECT_EQ(msg.event, "notification");
  16239. EXPECT_EQ(msg.id, "evt-42");
  16240. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16241. EXPECT_EQ(retry_ms, 1000);
  16242. }
  16243. //==============================================================================
  16244. // Integration Tests with Server
  16245. //==============================================================================
  16246. class SSEIntegrationTest : public ::testing::Test {
  16247. protected:
  16248. void SetUp() override {
  16249. stop_server_.store(false);
  16250. events_.clear();
  16251. server_ = httplib::detail::make_unique<Server>();
  16252. setup_server();
  16253. start_server();
  16254. }
  16255. void TearDown() override {
  16256. stop_server_.store(true);
  16257. event_cv_.notify_all();
  16258. server_->stop();
  16259. if (server_thread_.joinable()) { server_thread_.join(); }
  16260. }
  16261. void setup_server() {
  16262. // Simple SSE endpoint
  16263. server_->Get("/events", [this](const Request &req, Response &res) {
  16264. auto last_id = req.get_header_value("Last-Event-ID");
  16265. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16266. res.set_chunked_content_provider(
  16267. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16268. std::unique_lock<std::mutex> lock(event_mutex_);
  16269. if (event_cv_.wait_for(
  16270. lock, std::chrono::milliseconds(200), [this] {
  16271. return !events_.empty() || stop_server_.load();
  16272. })) {
  16273. if (stop_server_.load()) { return false; }
  16274. if (!events_.empty()) {
  16275. std::string event = events_.front();
  16276. events_.erase(events_.begin());
  16277. sink.write(event.data(), event.size());
  16278. return true;
  16279. }
  16280. }
  16281. return !stop_server_.load();
  16282. });
  16283. });
  16284. // Endpoint that returns error
  16285. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16286. res.status = 500;
  16287. res.set_content("Internal Server Error", "text/plain");
  16288. });
  16289. // Endpoint for custom event types
  16290. server_->Get("/custom-events", [](const Request &, Response &res) {
  16291. res.set_chunked_content_provider(
  16292. "text/event-stream", [](size_t offset, DataSink &sink) {
  16293. if (offset == 0) {
  16294. std::string event = "event: update\ndata: updated\n\n"
  16295. "event: delete\ndata: deleted\n\n";
  16296. sink.write(event.data(), event.size());
  16297. }
  16298. return false; // End stream after sending
  16299. });
  16300. });
  16301. }
  16302. void start_server() {
  16303. port_ = server_->bind_to_any_port(HOST);
  16304. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16305. // Wait for server to start
  16306. while (!server_->is_running()) {
  16307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16308. }
  16309. }
  16310. int get_port() const { return port_; }
  16311. void send_event(const std::string &event) {
  16312. std::lock_guard<std::mutex> lock(event_mutex_);
  16313. events_.push_back(event);
  16314. event_cv_.notify_all();
  16315. }
  16316. std::unique_ptr<Server> server_;
  16317. std::thread server_thread_;
  16318. std::mutex event_mutex_;
  16319. std::condition_variable event_cv_;
  16320. std::vector<std::string> events_;
  16321. std::atomic<bool> stop_server_{false};
  16322. std::string last_received_event_id_;
  16323. int port_ = 0;
  16324. };
  16325. // Test: Successful connection and on_open callback
  16326. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16327. // Add a simple endpoint that sends one event and closes
  16328. server_->Get("/simple-event", [](const Request &, Response &res) {
  16329. res.set_chunked_content_provider(
  16330. "text/event-stream", [](size_t offset, DataSink &sink) {
  16331. if (offset == 0) {
  16332. std::string event = "data: hello\n\n";
  16333. sink.write(event.data(), event.size());
  16334. }
  16335. return false; // Close stream after sending
  16336. });
  16337. });
  16338. Client client("localhost", get_port());
  16339. sse::SSEClient sse(client, "/simple-event");
  16340. std::atomic<bool> open_called{false};
  16341. std::atomic<bool> message_received{false};
  16342. sse.on_open([&open_called]() { open_called.store(true); });
  16343. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16344. if (msg.data == "hello") { message_received.store(true); }
  16345. });
  16346. sse.set_reconnect_interval(100);
  16347. sse.set_max_reconnect_attempts(1);
  16348. // Start async
  16349. sse.start_async();
  16350. // Wait for message to be processed
  16351. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16352. sse.stop();
  16353. EXPECT_TRUE(open_called.load());
  16354. EXPECT_TRUE(message_received.load());
  16355. }
  16356. // Test: on_message callback
  16357. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16358. // Endpoint that sends multiple events then closes
  16359. server_->Get("/multi-event", [](const Request &, Response &res) {
  16360. res.set_chunked_content_provider(
  16361. "text/event-stream", [](size_t offset, DataSink &sink) {
  16362. if (offset == 0) {
  16363. std::string events = "data: message1\n\ndata: message2\n\n";
  16364. sink.write(events.data(), events.size());
  16365. }
  16366. return false;
  16367. });
  16368. });
  16369. Client client("localhost", get_port());
  16370. sse::SSEClient sse(client, "/multi-event");
  16371. std::vector<std::string> received_messages;
  16372. std::mutex messages_mutex;
  16373. sse.on_message([&](const sse::SSEMessage &msg) {
  16374. std::lock_guard<std::mutex> lock(messages_mutex);
  16375. received_messages.push_back(msg.data);
  16376. });
  16377. sse.set_reconnect_interval(100);
  16378. sse.set_max_reconnect_attempts(1);
  16379. sse.start_async();
  16380. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16381. sse.stop();
  16382. std::lock_guard<std::mutex> lock(messages_mutex);
  16383. EXPECT_GE(received_messages.size(), 2u);
  16384. if (received_messages.size() >= 2) {
  16385. EXPECT_EQ(received_messages[0], "message1");
  16386. EXPECT_EQ(received_messages[1], "message2");
  16387. }
  16388. }
  16389. // Test: on_event for specific types
  16390. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16391. Client client("localhost", get_port());
  16392. sse::SSEClient sse(client, "/custom-events");
  16393. std::atomic<bool> update_received{false};
  16394. std::atomic<bool> delete_received{false};
  16395. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16396. if (msg.data == "updated") { update_received.store(true); }
  16397. });
  16398. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16399. if (msg.data == "deleted") { delete_received.store(true); }
  16400. });
  16401. sse.set_max_reconnect_attempts(1);
  16402. sse.start_async();
  16403. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16404. sse.stop();
  16405. EXPECT_TRUE(update_received.load());
  16406. EXPECT_TRUE(delete_received.load());
  16407. }
  16408. // Test: on_error callback on connection failure
  16409. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16410. // Connect to a non-existent port
  16411. Client client("localhost", 59999);
  16412. sse::SSEClient sse(client, "/events");
  16413. std::atomic<bool> error_called{false};
  16414. Error received_error = Error::Success;
  16415. sse.on_error([&](Error err) {
  16416. error_called.store(true);
  16417. received_error = err;
  16418. });
  16419. sse.set_reconnect_interval(50);
  16420. sse.set_max_reconnect_attempts(1);
  16421. sse.start_async();
  16422. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16423. sse.stop();
  16424. EXPECT_TRUE(error_called.load());
  16425. EXPECT_NE(received_error, Error::Success);
  16426. }
  16427. // Test: Last-Event-ID header sent on reconnect
  16428. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16429. // Endpoint that sends event with ID
  16430. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16431. res.set_chunked_content_provider(
  16432. "text/event-stream", [](size_t offset, DataSink &sink) {
  16433. if (offset == 0) {
  16434. std::string event = "id: evt-123\ndata: test\n\n";
  16435. sink.write(event.data(), event.size());
  16436. }
  16437. return false;
  16438. });
  16439. });
  16440. Client client("localhost", get_port());
  16441. sse::SSEClient sse(client, "/event-with-id");
  16442. std::atomic<bool> id_received{false};
  16443. sse.on_message([&](const sse::SSEMessage &msg) {
  16444. if (!msg.id.empty()) { id_received.store(true); }
  16445. });
  16446. sse.set_reconnect_interval(100);
  16447. sse.set_max_reconnect_attempts(1);
  16448. sse.start_async();
  16449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16450. sse.stop();
  16451. EXPECT_TRUE(id_received.load());
  16452. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16453. }
  16454. // Test: Manual stop
  16455. TEST_F(SSEIntegrationTest, ManualStop) {
  16456. // Endpoint that sends one event and stays open briefly
  16457. std::atomic<bool> handler_running{true};
  16458. server_->Get("/stay-open", [&handler_running](const Request &,
  16459. Response &res) {
  16460. res.set_chunked_content_provider(
  16461. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16462. if (offset == 0) {
  16463. std::string event = "data: connected\n\n";
  16464. sink.write(event.data(), event.size());
  16465. }
  16466. // Keep connection open while handler_running is true
  16467. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16468. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16469. }
  16470. return false;
  16471. });
  16472. });
  16473. Client client("localhost", get_port());
  16474. sse::SSEClient sse(client, "/stay-open");
  16475. std::atomic<bool> connected{false};
  16476. sse.on_open([&connected]() { connected.store(true); });
  16477. sse.set_reconnect_interval(100);
  16478. sse.set_max_reconnect_attempts(1);
  16479. sse.start_async();
  16480. // Wait for connection to establish
  16481. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16482. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16483. }
  16484. EXPECT_TRUE(connected.load());
  16485. EXPECT_TRUE(sse.is_connected());
  16486. // Signal handler to stop
  16487. handler_running.store(false);
  16488. // Stop SSE client
  16489. sse.stop();
  16490. EXPECT_FALSE(sse.is_connected());
  16491. }
  16492. // Test: SSEClient with custom headers
  16493. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16494. // Setup a server endpoint that checks for custom header
  16495. std::atomic<bool> header_received{false};
  16496. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16497. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16498. header_received.store(true);
  16499. }
  16500. res.set_chunked_content_provider("text/event-stream",
  16501. [](size_t, DataSink &) { return false; });
  16502. });
  16503. Client client("localhost", get_port());
  16504. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16505. sse::SSEClient sse(client, "/header-check", headers);
  16506. sse.set_max_reconnect_attempts(1);
  16507. sse.start_async();
  16508. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16509. sse.stop();
  16510. EXPECT_TRUE(header_received.load());
  16511. }
  16512. // Test: Reconnect interval configuration
  16513. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16514. Client client("localhost", get_port());
  16515. sse::SSEClient sse(client, "/events");
  16516. auto &result = sse.set_reconnect_interval(500);
  16517. // Builder pattern should return reference to self
  16518. EXPECT_EQ(&result, &sse);
  16519. }
  16520. // Test: Max reconnect attempts
  16521. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16522. // Connect to non-existent port to force reconnects
  16523. Client client("localhost", 59998);
  16524. sse::SSEClient sse(client, "/events");
  16525. std::atomic<int> error_count{0};
  16526. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16527. sse.set_reconnect_interval(50);
  16528. sse.set_max_reconnect_attempts(2);
  16529. auto start = std::chrono::steady_clock::now();
  16530. sse.start(); // Blocking call
  16531. auto end = std::chrono::steady_clock::now();
  16532. // Should have stopped after 2 failed attempts
  16533. EXPECT_GE(error_count.load(), 2);
  16534. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16535. auto duration =
  16536. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16537. #ifdef _WIN32
  16538. // Windows is much slower for socket connection failures
  16539. EXPECT_LT(duration.count(), 7000);
  16540. #else
  16541. EXPECT_LT(duration.count(), 1000);
  16542. #endif
  16543. }
  16544. // Test: Multi-line data in integration
  16545. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16546. // Endpoint with multi-line data
  16547. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16548. res.set_chunked_content_provider(
  16549. "text/event-stream", [](size_t offset, DataSink &sink) {
  16550. if (offset == 0) {
  16551. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16552. sink.write(event.data(), event.size());
  16553. }
  16554. return false;
  16555. });
  16556. });
  16557. Client client("localhost", get_port());
  16558. sse::SSEClient sse(client, "/multiline-data");
  16559. std::string received_data;
  16560. std::mutex data_mutex;
  16561. sse.on_message([&](const sse::SSEMessage &msg) {
  16562. std::lock_guard<std::mutex> lock(data_mutex);
  16563. received_data = msg.data;
  16564. });
  16565. sse.set_reconnect_interval(100);
  16566. sse.set_max_reconnect_attempts(1);
  16567. sse.start_async();
  16568. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16569. sse.stop();
  16570. std::lock_guard<std::mutex> lock(data_mutex);
  16571. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16572. }
  16573. // Test: Auto-reconnect after server disconnection
  16574. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16575. std::atomic<int> connection_count{0};
  16576. std::atomic<int> message_count{0};
  16577. // Endpoint that sends one event and closes, forcing reconnect
  16578. server_->Get("/reconnect-test",
  16579. [&connection_count](const Request &, Response &res) {
  16580. connection_count.fetch_add(1);
  16581. res.set_chunked_content_provider(
  16582. "text/event-stream", [](size_t offset, DataSink &sink) {
  16583. if (offset == 0) {
  16584. std::string event = "data: hello\n\n";
  16585. sink.write(event.data(), event.size());
  16586. }
  16587. return false; // Close connection after sending
  16588. });
  16589. });
  16590. Client client("localhost", get_port());
  16591. sse::SSEClient sse(client, "/reconnect-test");
  16592. sse.on_message([&message_count](const sse::SSEMessage &) {
  16593. message_count.fetch_add(1);
  16594. });
  16595. sse.set_reconnect_interval(100);
  16596. sse.set_max_reconnect_attempts(3);
  16597. sse.start_async();
  16598. // Wait long enough for multiple reconnects
  16599. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16600. sse.stop();
  16601. // Should have connected multiple times (initial + reconnects)
  16602. EXPECT_GE(connection_count.load(), 2);
  16603. // Should have received messages from multiple connections
  16604. EXPECT_GE(message_count.load(), 2);
  16605. }
  16606. // Test: Last-Event-ID sent on reconnect
  16607. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16608. std::atomic<int> connection_count{0};
  16609. std::vector<std::string> received_last_event_ids;
  16610. std::mutex id_mutex;
  16611. // Endpoint that checks Last-Event-ID header and sends event with ID
  16612. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16613. int conn = connection_count.fetch_add(1);
  16614. // Capture the Last-Event-ID header from each connection
  16615. {
  16616. std::lock_guard<std::mutex> lock(id_mutex);
  16617. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16618. }
  16619. res.set_chunked_content_provider(
  16620. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16621. if (offset == 0) {
  16622. std::string event =
  16623. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16624. sink.write(event.data(), event.size());
  16625. }
  16626. return false;
  16627. });
  16628. });
  16629. Client client("localhost", get_port());
  16630. sse::SSEClient sse(client, "/reconnect-with-id");
  16631. sse.set_reconnect_interval(100);
  16632. sse.set_max_reconnect_attempts(3);
  16633. sse.start_async();
  16634. // Wait for at least 2 connections
  16635. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16636. sse.stop();
  16637. // Verify behavior
  16638. std::lock_guard<std::mutex> lock(id_mutex);
  16639. EXPECT_GE(received_last_event_ids.size(), 2u);
  16640. // First connection should have no Last-Event-ID
  16641. if (!received_last_event_ids.empty()) {
  16642. EXPECT_EQ(received_last_event_ids[0], "");
  16643. }
  16644. // Second connection should have Last-Event-ID from first connection
  16645. if (received_last_event_ids.size() >= 2) {
  16646. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16647. }
  16648. }
  16649. // Test: set_headers updates headers used on reconnect
  16650. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16651. std::vector<std::string> received_tokens;
  16652. std::mutex token_mutex;
  16653. // Endpoint that captures Authorization header
  16654. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16655. {
  16656. std::lock_guard<std::mutex> lock(token_mutex);
  16657. received_tokens.push_back(req.get_header_value("Authorization"));
  16658. }
  16659. res.set_chunked_content_provider(
  16660. "text/event-stream", [](size_t offset, DataSink &sink) {
  16661. if (offset == 0) {
  16662. std::string event = "data: hello\n\n";
  16663. sink.write(event.data(), event.size());
  16664. }
  16665. return false; // Close connection to trigger reconnect
  16666. });
  16667. });
  16668. Client client("localhost", get_port());
  16669. Headers headers = {{"Authorization", "Bearer old-token"}};
  16670. sse::SSEClient sse(client, "/auth-check", headers);
  16671. // Update headers on each successful connection
  16672. sse.on_open(
  16673. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16674. sse.set_reconnect_interval(100);
  16675. sse.set_max_reconnect_attempts(3);
  16676. sse.start_async();
  16677. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16678. sse.stop();
  16679. std::lock_guard<std::mutex> lock(token_mutex);
  16680. ASSERT_GE(received_tokens.size(), 2u);
  16681. // First connection uses original header
  16682. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16683. // Second connection uses updated header from set_headers
  16684. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16685. }
  16686. // Test: 401 allows reconnection (so on_error can refresh headers)
  16687. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16688. std::atomic<int> connection_count{0};
  16689. // Endpoint: returns 401 on first attempt, 200 on second
  16690. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16691. int conn = connection_count.fetch_add(1);
  16692. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16693. res.status = StatusCode::Unauthorized_401;
  16694. res.set_content("Unauthorized", "text/plain");
  16695. return;
  16696. }
  16697. res.set_chunked_content_provider(
  16698. "text/event-stream", [](size_t offset, DataSink &sink) {
  16699. if (offset == 0) {
  16700. std::string event = "data: authenticated\n\n";
  16701. sink.write(event.data(), event.size());
  16702. }
  16703. return false;
  16704. });
  16705. });
  16706. Client client("localhost", get_port());
  16707. Headers headers = {{"Authorization", "Bearer expired"}};
  16708. sse::SSEClient sse(client, "/auth-retry", headers);
  16709. std::atomic<bool> message_received{false};
  16710. // Refresh token on error
  16711. sse.on_error(
  16712. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16713. sse.on_message([&](const sse::SSEMessage &msg) {
  16714. if (msg.data == "authenticated") { message_received.store(true); }
  16715. });
  16716. sse.set_reconnect_interval(100);
  16717. sse.set_max_reconnect_attempts(3);
  16718. sse.start_async();
  16719. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16720. sse.stop();
  16721. // Should have reconnected after 401 and succeeded with new token
  16722. EXPECT_GE(connection_count.load(), 2);
  16723. EXPECT_TRUE(message_received.load());
  16724. }
  16725. TEST(Issue2318Test, EmptyHostString) {
  16726. {
  16727. httplib::Client cli_empty("", PORT);
  16728. auto res = cli_empty.Get("/");
  16729. ASSERT_FALSE(res);
  16730. EXPECT_EQ(httplib::Error::Connection, res.error());
  16731. }
  16732. {
  16733. httplib::Client cli(" ", PORT);
  16734. auto res = cli.Get("/");
  16735. ASSERT_FALSE(res);
  16736. EXPECT_EQ(httplib::Error::Connection, res.error());
  16737. }
  16738. }
  16739. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16740. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16741. Server svr;
  16742. // Set a small payload limit (1KB)
  16743. svr.set_payload_max_length(1024);
  16744. svr.Post("/test", [&](const Request &req, Response &res) {
  16745. res.set_content("Body size: " + std::to_string(req.body.size()),
  16746. "text/plain");
  16747. });
  16748. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16749. auto se = detail::scope_exit([&] {
  16750. svr.stop();
  16751. listen_thread.join();
  16752. });
  16753. svr.wait_until_ready();
  16754. // Create data that compresses well but exceeds limit when decompressed
  16755. // 8KB of repeated null bytes compresses to a very small size
  16756. std::string original_data(8 * 1024, '\0');
  16757. // Compress the data using gzip
  16758. std::string compressed_data;
  16759. detail::gzip_compressor compressor;
  16760. compressor.compress(original_data.data(), original_data.size(), true,
  16761. [&](const char *data, size_t size) {
  16762. compressed_data.append(data, size);
  16763. return true;
  16764. });
  16765. // Verify compression worked (compressed should be much smaller)
  16766. ASSERT_LT(compressed_data.size(), original_data.size());
  16767. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16768. // Send compressed data with Content-Encoding: gzip
  16769. Client cli(HOST, PORT);
  16770. Headers headers = {{"Content-Encoding", "gzip"}};
  16771. auto res =
  16772. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16773. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16775. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16776. }
  16777. #endif
  16778. // ============================================================================
  16779. // OpenSSL-Specific Tests
  16780. // ============================================================================
  16781. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16782. X509 *readCertificate(const std::string &strFileName) {
  16783. std::ifstream inStream(strFileName);
  16784. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16785. std::istreambuf_iterator<char>());
  16786. if (strCertPEM.empty()) return (nullptr);
  16787. BIO *pbCert = BIO_new(BIO_s_mem());
  16788. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16789. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16790. BIO_free(pbCert);
  16791. return (pCert);
  16792. }
  16793. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16794. std::ifstream inStream(strFileName);
  16795. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16796. std::istreambuf_iterator<char>());
  16797. if (strPrivateKeyPEM.empty()) return (nullptr);
  16798. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16799. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16800. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16801. BIO_free(pbPrivKey);
  16802. return (pPrivateKey);
  16803. }
  16804. TEST(BindServerTest, UpdateCerts) {
  16805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16806. int port = svr.bind_to_any_port("0.0.0.0");
  16807. ASSERT_TRUE(svr.is_valid());
  16808. ASSERT_TRUE(port > 0);
  16809. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16810. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16811. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16812. ASSERT_TRUE(cert != nullptr);
  16813. ASSERT_TRUE(ca_cert != nullptr);
  16814. ASSERT_TRUE(key != nullptr);
  16815. X509_STORE *cert_store = X509_STORE_new();
  16816. X509_STORE_add_cert(cert_store, ca_cert);
  16817. // svr.update_certs(cert, key, cert_store); // deprecated
  16818. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16819. CLIENT_CA_CERT_FILE);
  16820. ASSERT_TRUE(svr.is_valid());
  16821. svr.stop();
  16822. X509_STORE_free(cert_store);
  16823. X509_free(cert);
  16824. X509_free(ca_cert);
  16825. EVP_PKEY_free(key);
  16826. }
  16827. // Test that update_certs() updates client CA list correctly
  16828. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16829. // Start with file-based constructor
  16830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16831. ASSERT_TRUE(svr.is_valid());
  16832. // Initially no client CA list should be set
  16833. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16834. ASSERT_TRUE(ssl_ctx != nullptr);
  16835. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16836. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16837. EXPECT_EQ(0, count_before);
  16838. // Now update with client CA (PEM string)
  16839. std::string cert_pem, key_pem, ca_pem;
  16840. read_file(SERVER_CERT_FILE, cert_pem);
  16841. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16842. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16843. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16844. ASSERT_TRUE(svr.is_valid());
  16845. // Now client CA list should be set
  16846. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16847. ASSERT_TRUE(ca_list_after != nullptr);
  16848. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16849. }
  16850. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16851. // Test that the file-path SSLServer constructor properly sets the client CA
  16852. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16854. ASSERT_TRUE(svr.is_valid());
  16855. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16856. ASSERT_TRUE(ssl_ctx != nullptr);
  16857. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16858. ASSERT_TRUE(ca_list != nullptr);
  16859. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16860. }
  16861. #endif
  16862. // ============================================================================
  16863. // MbedTLS-Specific Tests
  16864. // ============================================================================
  16865. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16866. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16867. using namespace httplib::tls;
  16868. // Track if callback was invoked
  16869. bool callback_invoked = false;
  16870. // The callback receives void* ctx which is actually MbedTlsContext*
  16871. // We can access the mbedtls_ssl_config via the context
  16872. auto setup_callback = [&callback_invoked](void *ctx) {
  16873. callback_invoked = true;
  16874. // Cast to MbedTlsContext* to access the ssl config
  16875. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16876. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16877. // Use static variables to hold certificate data (simplified for test)
  16878. static mbedtls_x509_crt own_cert;
  16879. static mbedtls_pk_context own_key;
  16880. static mbedtls_x509_crt ca_chain;
  16881. static bool initialized = false;
  16882. if (!initialized) {
  16883. mbedtls_x509_crt_init(&own_cert);
  16884. mbedtls_pk_init(&own_key);
  16885. mbedtls_x509_crt_init(&ca_chain);
  16886. // Load server certificate
  16887. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16888. return false;
  16889. }
  16890. // Load server private key.
  16891. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16892. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16893. #if MBEDTLS_VERSION_MAJOR == 3
  16894. ,
  16895. mbedtls_ctr_drbg_random, nullptr
  16896. #endif
  16897. ) != 0) {
  16898. return false;
  16899. }
  16900. // Load CA chain for client verification
  16901. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16902. return false;
  16903. }
  16904. initialized = true;
  16905. }
  16906. // Configure the SSL config
  16907. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16908. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16909. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16910. // Set minimum TLS version using mbedTLS native API
  16911. #if MBEDTLS_VERSION_MAJOR >= 3
  16912. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16913. #else
  16914. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16915. MBEDTLS_SSL_MINOR_VERSION_3);
  16916. #endif
  16917. return true;
  16918. };
  16919. SSLServer svr(setup_callback);
  16920. ASSERT_TRUE(svr.is_valid());
  16921. ASSERT_TRUE(callback_invoked);
  16922. svr.Get("/test", [&](const Request &req, Response &res) {
  16923. res.set_content("test", "text/plain");
  16924. auto cert = req.peer_cert();
  16925. ASSERT_TRUE(static_cast<bool>(cert));
  16926. auto common_name = cert.subject_cn();
  16927. EXPECT_EQ("Common Name", common_name);
  16928. });
  16929. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16930. auto se = detail::scope_exit([&] {
  16931. svr.stop();
  16932. t.join();
  16933. ASSERT_FALSE(svr.is_running());
  16934. });
  16935. svr.wait_until_ready();
  16936. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16937. cli.enable_server_certificate_verification(false);
  16938. cli.set_connection_timeout(30);
  16939. auto res = cli.Get("/test");
  16940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16941. ASSERT_EQ(StatusCode::OK_200, res->status);
  16942. }
  16943. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16944. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16945. // keep-alive SSL session, which reads through that config in
  16946. // mbedtls_ssl_close_notify.
  16947. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16949. ASSERT_TRUE(svr.is_valid());
  16950. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16951. res.set_content("test", "text/plain");
  16952. });
  16953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16954. auto se = detail::scope_exit([&] {
  16955. svr.stop();
  16956. t.join();
  16957. ASSERT_FALSE(svr.is_running());
  16958. });
  16959. svr.wait_until_ready();
  16960. {
  16961. SSLClient cli(HOST, PORT);
  16962. cli.enable_server_certificate_verification(false);
  16963. cli.set_keep_alive(true);
  16964. auto res = cli.Get("/test");
  16965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16966. ASSERT_EQ(StatusCode::OK_200, res->status);
  16967. // cli is destructed here with the keep-alive SSL session still open.
  16968. }
  16969. }
  16970. #endif
  16971. // WebSocket Tests
  16972. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16973. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16974. // defining the meaning of these bits has been negotiated.
  16975. auto make_frame = [](uint8_t first_byte) {
  16976. std::string frame;
  16977. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16978. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16979. frame += "Hello";
  16980. return frame;
  16981. };
  16982. // RSV1 set (0x40)
  16983. {
  16984. detail::BufferStream strm;
  16985. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16986. ws::Opcode opcode;
  16987. std::string payload;
  16988. bool fin;
  16989. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16990. false, 1024));
  16991. }
  16992. // RSV2 set (0x20)
  16993. {
  16994. detail::BufferStream strm;
  16995. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16996. ws::Opcode opcode;
  16997. std::string payload;
  16998. bool fin;
  16999. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17000. false, 1024));
  17001. }
  17002. // RSV3 set (0x10)
  17003. {
  17004. detail::BufferStream strm;
  17005. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17006. ws::Opcode opcode;
  17007. std::string payload;
  17008. bool fin;
  17009. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17010. false, 1024));
  17011. }
  17012. // No RSV bits set - should succeed
  17013. {
  17014. detail::BufferStream strm;
  17015. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17016. ws::Opcode opcode;
  17017. std::string payload;
  17018. bool fin;
  17019. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17020. false, 1024));
  17021. EXPECT_EQ(ws::Opcode::Text, opcode);
  17022. EXPECT_EQ("Hello", payload);
  17023. EXPECT_TRUE(fin);
  17024. }
  17025. }
  17026. TEST(WebSocketTest, ControlFrameValidation) {
  17027. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17028. // payload length <= 125.
  17029. // Ping with FIN=0 - must be rejected
  17030. {
  17031. detail::BufferStream strm;
  17032. std::string frame;
  17033. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17034. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17035. strm.write(frame.data(), frame.size());
  17036. ws::Opcode opcode;
  17037. std::string payload;
  17038. bool fin;
  17039. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17040. false, 1024));
  17041. }
  17042. // Close with FIN=0 - must be rejected
  17043. {
  17044. detail::BufferStream strm;
  17045. std::string frame;
  17046. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17047. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17048. strm.write(frame.data(), frame.size());
  17049. ws::Opcode opcode;
  17050. std::string payload;
  17051. bool fin;
  17052. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17053. false, 1024));
  17054. }
  17055. // Ping with payload_len=126 (extended length) - must be rejected
  17056. {
  17057. detail::BufferStream strm;
  17058. std::string frame;
  17059. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17060. frame += static_cast<char>(126); // payload_len=126 (>125)
  17061. frame += static_cast<char>(0x00); // extended length high byte
  17062. frame += static_cast<char>(126); // extended length low byte
  17063. frame += std::string(126, 'x');
  17064. strm.write(frame.data(), frame.size());
  17065. ws::Opcode opcode;
  17066. std::string payload;
  17067. bool fin;
  17068. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17069. false, 1024));
  17070. }
  17071. // Ping with FIN=1 and payload_len=125 - should succeed
  17072. {
  17073. detail::BufferStream strm;
  17074. std::string frame;
  17075. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17076. frame += static_cast<char>(125); // payload_len=125
  17077. frame += std::string(125, 'x');
  17078. strm.write(frame.data(), frame.size());
  17079. ws::Opcode opcode;
  17080. std::string payload;
  17081. bool fin;
  17082. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17083. false, 1024));
  17084. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17085. EXPECT_EQ(125u, payload.size());
  17086. EXPECT_TRUE(fin);
  17087. }
  17088. }
  17089. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17090. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17091. // length MUST be 0.
  17092. // MSB set - must be rejected
  17093. {
  17094. detail::BufferStream strm;
  17095. std::string frame;
  17096. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17097. frame += static_cast<char>(127); // 64-bit extended length
  17098. frame += static_cast<char>(0x80); // MSB set (invalid)
  17099. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17100. strm.write(frame.data(), frame.size());
  17101. ws::Opcode opcode;
  17102. std::string payload;
  17103. bool fin;
  17104. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17105. false, 1024));
  17106. }
  17107. // MSB clear - should pass length parsing (will be rejected by max_len,
  17108. // but that's a different check; use a small length to verify)
  17109. {
  17110. detail::BufferStream strm;
  17111. std::string frame;
  17112. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17113. frame += static_cast<char>(127); // 64-bit extended length
  17114. frame += std::string(7, '\0'); // high bytes = 0
  17115. frame += static_cast<char>(0x03); // length = 3
  17116. frame += "abc";
  17117. strm.write(frame.data(), frame.size());
  17118. ws::Opcode opcode;
  17119. std::string payload;
  17120. bool fin;
  17121. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17122. false, 1024));
  17123. EXPECT_EQ(ws::Opcode::Text, opcode);
  17124. EXPECT_EQ("abc", payload);
  17125. }
  17126. }
  17127. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17128. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17129. // Valid UTF-8
  17130. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17131. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17132. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17133. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17134. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17135. // Invalid UTF-8
  17136. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17137. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17138. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17139. EXPECT_FALSE(
  17140. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17141. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17142. }
  17143. TEST(WebSocketTest, ConnectAndDisconnect) {
  17144. Server svr;
  17145. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17146. std::string msg;
  17147. while (ws.read(msg)) {}
  17148. });
  17149. auto port = svr.bind_to_any_port(HOST);
  17150. std::thread t([&]() { svr.listen_after_bind(); });
  17151. svr.wait_until_ready();
  17152. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17153. auto res = client.connect();
  17154. ASSERT_TRUE(res);
  17155. EXPECT_EQ(Error::Success, res.error());
  17156. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17157. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17158. EXPECT_TRUE(client.is_open());
  17159. client.close();
  17160. EXPECT_FALSE(client.is_open());
  17161. svr.stop();
  17162. t.join();
  17163. }
  17164. TEST(WebSocketTest, ValidURL) {
  17165. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17166. EXPECT_TRUE(ws1.is_valid());
  17167. ws::WebSocketClient ws2("ws://example.com/path");
  17168. EXPECT_TRUE(ws2.is_valid());
  17169. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17170. EXPECT_TRUE(ws3.is_valid());
  17171. #ifdef CPPHTTPLIB_SSL_ENABLED
  17172. ws::WebSocketClient wss1("wss://example.com/path");
  17173. EXPECT_TRUE(wss1.is_valid());
  17174. ws::WebSocketClient wss2("wss://example.com:443/path");
  17175. EXPECT_TRUE(wss2.is_valid());
  17176. #endif
  17177. }
  17178. TEST(WebSocketTest, InvalidURL) {
  17179. // No scheme
  17180. ws::WebSocketClient ws1("localhost:8080/path");
  17181. EXPECT_FALSE(ws1.is_valid());
  17182. // No path
  17183. ws::WebSocketClient ws2("ws://localhost:8080");
  17184. EXPECT_FALSE(ws2.is_valid());
  17185. // Empty string
  17186. ws::WebSocketClient ws3("");
  17187. EXPECT_FALSE(ws3.is_valid());
  17188. // Missing host
  17189. ws::WebSocketClient ws4("ws://:8080/path");
  17190. EXPECT_FALSE(ws4.is_valid());
  17191. // Port number overflow — should not crash
  17192. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17193. EXPECT_FALSE(ws5.is_valid());
  17194. // Port out of range
  17195. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17196. EXPECT_FALSE(ws6.is_valid());
  17197. }
  17198. TEST(WebSocketTest, UnsupportedScheme) {
  17199. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17200. ws::WebSocketClient ws1("http://localhost:8080/path");
  17201. EXPECT_FALSE(ws1.is_valid());
  17202. ws::WebSocketClient ws2("https://localhost:8080/path");
  17203. EXPECT_FALSE(ws2.is_valid());
  17204. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17205. EXPECT_FALSE(ws3.is_valid());
  17206. #else
  17207. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17208. std::invalid_argument);
  17209. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17210. std::invalid_argument);
  17211. #endif
  17212. }
  17213. TEST(WebSocketTest, ConnectWhenInvalid) {
  17214. ws::WebSocketClient ws("not a valid url");
  17215. EXPECT_FALSE(ws.is_valid());
  17216. auto res = ws.connect();
  17217. EXPECT_FALSE(res);
  17218. EXPECT_EQ(Error::Connection, res.error());
  17219. EXPECT_EQ(-1, res.status());
  17220. }
  17221. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17222. // Grab a port that is free, then close it again so nothing listens there
  17223. Server svr;
  17224. auto port = svr.bind_to_any_port(HOST);
  17225. svr.stop();
  17226. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17227. auto res = client.connect();
  17228. ASSERT_FALSE(res);
  17229. EXPECT_EQ(Error::Connection, res.error());
  17230. EXPECT_EQ(-1, res.status());
  17231. }
  17232. TEST(WebSocketTest, DefaultPort) {
  17233. ws::WebSocketClient ws1("ws://example.com/path");
  17234. EXPECT_TRUE(ws1.is_valid());
  17235. // ws:// defaults to port 80 (verified by successful parse)
  17236. #ifdef CPPHTTPLIB_SSL_ENABLED
  17237. ws::WebSocketClient ws2("wss://example.com/path");
  17238. EXPECT_TRUE(ws2.is_valid());
  17239. // wss:// defaults to port 443 (verified by successful parse)
  17240. #endif
  17241. }
  17242. TEST(WebSocketTest, IPv6LiteralAddress) {
  17243. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17244. EXPECT_TRUE(ws1.is_valid());
  17245. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17246. EXPECT_TRUE(ws2.is_valid());
  17247. }
  17248. TEST(WebSocketTest, ComplexPath) {
  17249. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17250. EXPECT_TRUE(ws1.is_valid());
  17251. ws::WebSocketClient ws2("ws://localhost:8080/");
  17252. EXPECT_TRUE(ws2.is_valid());
  17253. }
  17254. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17255. Server svr;
  17256. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17257. std::string msg;
  17258. while (ws.read(msg)) {}
  17259. });
  17260. auto port = svr.bind_to_any_port(HOST);
  17261. std::thread t([&]() { svr.listen_after_bind(); });
  17262. svr.wait_until_ready();
  17263. auto another_host = "example.com";
  17264. auto wrong_ip = "192.0.2.1";
  17265. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17266. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17267. ASSERT_TRUE(client.connect());
  17268. EXPECT_TRUE(client.is_open());
  17269. client.close();
  17270. svr.stop();
  17271. t.join();
  17272. }
  17273. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17274. Server svr;
  17275. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17276. std::string msg;
  17277. while (ws.read(msg)) {}
  17278. });
  17279. auto port = svr.bind_to_any_port(HOST);
  17280. std::thread t([&]() { svr.listen_after_bind(); });
  17281. svr.wait_until_ready();
  17282. auto wrong_ip = "192.0.2.1";
  17283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17284. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17285. client.set_connection_timeout(1);
  17286. client.set_read_timeout(1);
  17287. client.set_write_timeout(1);
  17288. EXPECT_FALSE(client.connect());
  17289. EXPECT_FALSE(client.is_open());
  17290. svr.stop();
  17291. t.join();
  17292. }
  17293. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17294. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17295. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17296. // (RFC 6761) is only a map key and the Host header value.
  17297. auto host = "target.invalid";
  17298. Server svr;
  17299. std::string received_host;
  17300. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17301. received_host = req.get_header_value("Host");
  17302. std::string msg;
  17303. while (ws.read(msg)) {}
  17304. });
  17305. auto port = svr.bind_to_any_port(HOST);
  17306. std::thread t([&]() { svr.listen_after_bind(); });
  17307. // ASSERT_* below returns from the test body, which would leave t joinable
  17308. // and make ~thread call std::terminate.
  17309. auto se = detail::scope_exit([&] {
  17310. svr.stop();
  17311. if (t.joinable()) { t.join(); }
  17312. });
  17313. svr.wait_until_ready();
  17314. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17315. std::to_string(port) + "/ws");
  17316. client.set_hostname_addr_map({{host, HOST}});
  17317. ASSERT_TRUE(client.connect());
  17318. EXPECT_TRUE(client.is_open());
  17319. client.close();
  17320. svr.stop();
  17321. t.join();
  17322. // The mapping only redirects the connection; the identity stays host_.
  17323. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17324. }
  17325. class WebSocketIntegrationTest : public ::testing::Test {
  17326. protected:
  17327. void SetUp() override {
  17328. server_ = httplib::detail::make_unique<Server>();
  17329. setup_server();
  17330. start_server();
  17331. }
  17332. void TearDown() override {
  17333. server_->stop();
  17334. if (server_thread_.joinable()) { server_thread_.join(); }
  17335. }
  17336. void setup_server() {
  17337. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17338. std::string msg;
  17339. ws::ReadResult ret;
  17340. while ((ret = ws.read(msg))) {
  17341. if (ret == ws::Binary) {
  17342. ws.send(msg.data(), msg.size());
  17343. } else {
  17344. ws.send(msg);
  17345. }
  17346. }
  17347. });
  17348. server_->WebSocket("/ws-echo-string",
  17349. [](const Request &, ws::WebSocket &ws) {
  17350. std::string msg;
  17351. while (ws.read(msg)) {
  17352. ws.send("echo: " + msg);
  17353. }
  17354. });
  17355. server_->WebSocket(
  17356. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17357. // Echo back request metadata
  17358. ws.send("path:" + req.path);
  17359. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17360. std::string msg;
  17361. while (ws.read(msg)) {}
  17362. });
  17363. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17364. std::string msg;
  17365. ws.read(msg); // wait for a message
  17366. ws.close();
  17367. });
  17368. server_->WebSocket("/ws-close-status",
  17369. [](const Request &, ws::WebSocket &ws) {
  17370. std::string msg;
  17371. ws.read(msg); // wait for a message
  17372. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17373. });
  17374. server_->WebSocket(
  17375. "/ws-subprotocol",
  17376. [](const Request &, ws::WebSocket &ws) {
  17377. std::string msg;
  17378. while (ws.read(msg)) {
  17379. ws.send(msg);
  17380. }
  17381. },
  17382. [](const std::vector<std::string> &protocols) -> std::string {
  17383. for (const auto &p : protocols) {
  17384. if (p == "graphql-ws") { return p; }
  17385. }
  17386. return "";
  17387. });
  17388. }
  17389. void start_server() {
  17390. port_ = server_->bind_to_any_port(HOST);
  17391. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17392. server_->wait_until_ready();
  17393. }
  17394. std::unique_ptr<Server> server_;
  17395. std::thread server_thread_;
  17396. int port_ = 0;
  17397. };
  17398. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17400. "/ws-echo");
  17401. ASSERT_TRUE(client.connect());
  17402. ASSERT_TRUE(client.is_open());
  17403. ASSERT_TRUE(client.send("Hello WebSocket"));
  17404. std::string msg;
  17405. EXPECT_EQ(ws::Text, client.read(msg));
  17406. EXPECT_EQ("Hello WebSocket", msg);
  17407. client.close();
  17408. }
  17409. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17411. "/ws-echo");
  17412. ASSERT_TRUE(client.connect());
  17413. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17414. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17415. std::string msg;
  17416. EXPECT_EQ(ws::Binary, client.read(msg));
  17417. EXPECT_EQ(binary_data, msg);
  17418. client.close();
  17419. }
  17420. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17421. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17422. "/ws-echo");
  17423. ASSERT_TRUE(client.connect());
  17424. for (int i = 0; i < 10; i++) {
  17425. auto text = "message " + std::to_string(i);
  17426. ASSERT_TRUE(client.send(text));
  17427. std::string msg;
  17428. ASSERT_TRUE(client.read(msg));
  17429. EXPECT_EQ(text, msg);
  17430. }
  17431. client.close();
  17432. }
  17433. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17434. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17435. "/ws-close");
  17436. ASSERT_TRUE(client.connect());
  17437. // Send a message to trigger the server to close
  17438. ASSERT_TRUE(client.send("trigger close"));
  17439. // The server will close, so read should return false
  17440. std::string msg;
  17441. EXPECT_FALSE(client.read(msg));
  17442. EXPECT_FALSE(client.is_open());
  17443. }
  17444. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17445. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17446. "/ws-echo");
  17447. ASSERT_TRUE(client.connect());
  17448. // 128KB message
  17449. std::string large_data(128 * 1024, 'X');
  17450. ASSERT_TRUE(client.send(large_data));
  17451. std::string msg;
  17452. ASSERT_TRUE(client.read(msg));
  17453. EXPECT_EQ(large_data, msg);
  17454. client.close();
  17455. }
  17456. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17457. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17458. "/ws-echo");
  17459. ASSERT_TRUE(client.connect());
  17460. const int num_threads = 4;
  17461. std::vector<std::thread> threads;
  17462. std::atomic<int> send_count{0};
  17463. for (int t = 0; t < num_threads; t++) {
  17464. threads.emplace_back([&client, &send_count, t]() {
  17465. for (int i = 0; i < 5; i++) {
  17466. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17467. if (client.send(text)) { send_count++; }
  17468. }
  17469. });
  17470. }
  17471. for (auto &th : threads) {
  17472. th.join();
  17473. }
  17474. int received = 0;
  17475. std::string msg;
  17476. while (received < send_count.load()) {
  17477. if (!client.read(msg)) { break; }
  17478. received++;
  17479. }
  17480. EXPECT_EQ(send_count.load(), received);
  17481. client.close();
  17482. }
  17483. TEST_F(WebSocketIntegrationTest, ReadString) {
  17484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17485. "/ws-echo-string");
  17486. ASSERT_TRUE(client.connect());
  17487. ASSERT_TRUE(client.send("hello"));
  17488. std::string msg;
  17489. ASSERT_TRUE(client.read(msg));
  17490. EXPECT_EQ("echo: hello", msg);
  17491. ASSERT_TRUE(client.send("world"));
  17492. ASSERT_TRUE(client.read(msg));
  17493. EXPECT_EQ("echo: world", msg);
  17494. client.close();
  17495. }
  17496. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17497. Headers headers = {{"X-Test-Header", "test-value"}};
  17498. ws::WebSocketClient client(
  17499. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17500. ASSERT_TRUE(client.connect());
  17501. std::string msg;
  17502. ASSERT_TRUE(client.read(msg));
  17503. EXPECT_EQ("path:/ws-request-info", msg);
  17504. ASSERT_TRUE(client.read(msg));
  17505. EXPECT_EQ("header:test-value", msg);
  17506. client.close();
  17507. }
  17508. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17510. "/ws-echo");
  17511. client.set_read_timeout(1, 0); // 1 second
  17512. ASSERT_TRUE(client.connect());
  17513. // Don't send anything — server echo handler waits for a message,
  17514. // so read() should time out and return false.
  17515. std::string msg;
  17516. EXPECT_FALSE(client.read(msg));
  17517. }
  17518. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17519. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17520. "/ws-echo");
  17521. client.set_read_timeout(5, 0);
  17522. ASSERT_TRUE(client.connect());
  17523. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17524. // The server should reject it and close the connection.
  17525. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17526. client.send(oversized);
  17527. // The server's read() should have failed due to payload limit,
  17528. // so our read() should return false (connection closed).
  17529. std::string msg;
  17530. EXPECT_FALSE(client.read(msg));
  17531. }
  17532. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17534. "/ws-echo");
  17535. client.set_read_timeout(10, 0);
  17536. ASSERT_TRUE(client.connect());
  17537. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17538. // This should succeed.
  17539. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17540. ASSERT_TRUE(client.send(at_limit));
  17541. std::string msg;
  17542. ASSERT_TRUE(client.read(msg));
  17543. EXPECT_EQ(at_limit.size(), msg.size());
  17544. client.close();
  17545. }
  17546. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17548. "/nonexistent");
  17549. auto res = client.connect();
  17550. EXPECT_FALSE(res);
  17551. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17552. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17553. EXPECT_FALSE(client.is_open());
  17554. }
  17555. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17556. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17557. "/ws-echo");
  17558. ASSERT_TRUE(client.connect());
  17559. ASSERT_TRUE(client.send(""));
  17560. std::string msg;
  17561. EXPECT_EQ(ws::Text, client.read(msg));
  17562. EXPECT_EQ("", msg);
  17563. client.close();
  17564. }
  17565. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17566. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17567. "/ws-echo");
  17568. // First connection
  17569. ASSERT_TRUE(client.connect());
  17570. ASSERT_TRUE(client.send("first"));
  17571. std::string msg;
  17572. ASSERT_TRUE(client.read(msg));
  17573. EXPECT_EQ("first", msg);
  17574. client.close();
  17575. EXPECT_FALSE(client.is_open());
  17576. // Reconnect using the same client object
  17577. ASSERT_TRUE(client.connect());
  17578. ASSERT_TRUE(client.is_open());
  17579. ASSERT_TRUE(client.send("second"));
  17580. ASSERT_TRUE(client.read(msg));
  17581. EXPECT_EQ("second", msg);
  17582. client.close();
  17583. }
  17584. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17586. "/ws-close-status");
  17587. ASSERT_TRUE(client.connect());
  17588. // Trigger the server to close with GoingAway status
  17589. ASSERT_TRUE(client.send("trigger"));
  17590. // read() should return false after receiving the close frame
  17591. std::string msg;
  17592. EXPECT_FALSE(client.read(msg));
  17593. EXPECT_FALSE(client.is_open());
  17594. }
  17595. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17596. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17597. "/ws-echo");
  17598. ASSERT_TRUE(client.connect());
  17599. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17600. EXPECT_FALSE(client.is_open());
  17601. }
  17602. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17603. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17604. ws::WebSocketClient client(
  17605. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17606. ASSERT_TRUE(client.connect());
  17607. // Server should have selected graphql-ws
  17608. EXPECT_EQ("graphql-ws", client.subprotocol());
  17609. client.close();
  17610. }
  17611. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  17612. Headers headers;
  17613. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  17614. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  17615. ws::WebSocketClient client(
  17616. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17617. ASSERT_TRUE(client.connect());
  17618. // The offer on the second field line counts too, so graphql-ws is selected
  17619. EXPECT_EQ("graphql-ws", client.subprotocol());
  17620. client.close();
  17621. }
  17622. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17623. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17624. ws::WebSocketClient client(
  17625. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17626. ASSERT_TRUE(client.connect());
  17627. // Server should not have selected any subprotocol
  17628. EXPECT_TRUE(client.subprotocol().empty());
  17629. client.close();
  17630. }
  17631. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17632. // Connect without requesting any subprotocol
  17633. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17634. "/ws-subprotocol");
  17635. ASSERT_TRUE(client.connect());
  17636. EXPECT_TRUE(client.subprotocol().empty());
  17637. client.close();
  17638. }
  17639. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17640. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17641. "/ws-echo");
  17642. client.set_tcp_nodelay(true);
  17643. client.set_connection_timeout(3, 0);
  17644. bool socket_options_called = false;
  17645. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17646. ASSERT_TRUE(client.connect());
  17647. ASSERT_TRUE(client.is_open());
  17648. EXPECT_TRUE(socket_options_called);
  17649. ASSERT_TRUE(client.send("hello"));
  17650. std::string msg;
  17651. auto result = client.read(msg);
  17652. EXPECT_EQ(result, ws::ReadResult::Text);
  17653. EXPECT_EQ(msg, "hello");
  17654. client.close();
  17655. }
  17656. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17657. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17658. "/ws-echo");
  17659. client.set_connection_timeout(std::chrono::seconds(3));
  17660. client.set_write_timeout(std::chrono::seconds(3));
  17661. // A sub-second remainder exercises the seconds/microseconds split.
  17662. client.set_read_timeout(std::chrono::milliseconds(1500));
  17663. ASSERT_TRUE(client.connect());
  17664. auto start = std::chrono::steady_clock::now();
  17665. std::string msg;
  17666. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17667. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17668. std::chrono::steady_clock::now() - start)
  17669. .count();
  17670. // Above 1s so that dropping the microseconds half of the split fails here,
  17671. // and well under the 300s default so that ignoring the setter fails too.
  17672. EXPECT_GE(elapsed, 1400);
  17673. EXPECT_LT(elapsed, 30000);
  17674. }
  17675. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17676. Server svr;
  17677. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17678. if (!req.has_header("Authorization")) {
  17679. res.status = StatusCode::Unauthorized_401;
  17680. res.set_content("Unauthorized", "text/plain");
  17681. return Server::HandlerResponse::Handled;
  17682. }
  17683. return Server::HandlerResponse::Unhandled;
  17684. });
  17685. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17686. std::string msg;
  17687. while (ws.read(msg)) {
  17688. ws.send(msg);
  17689. }
  17690. });
  17691. auto port = svr.bind_to_any_port("localhost");
  17692. std::thread t([&]() { svr.listen_after_bind(); });
  17693. svr.wait_until_ready();
  17694. // Without Authorization header - should be rejected before upgrade
  17695. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17696. EXPECT_FALSE(client1.connect());
  17697. // With Authorization header - should succeed
  17698. Headers headers = {{"Authorization", "Bearer token123"}};
  17699. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17700. headers);
  17701. ASSERT_TRUE(client2.connect());
  17702. ASSERT_TRUE(client2.send("hello"));
  17703. std::string msg;
  17704. ASSERT_TRUE(client2.read(msg));
  17705. EXPECT_EQ("hello", msg);
  17706. client2.close();
  17707. svr.stop();
  17708. t.join();
  17709. }
  17710. TEST(WebSocketTest, QueryStringInHandshake) {
  17711. Server svr;
  17712. std::mutex mtx;
  17713. std::string received_target;
  17714. std::string received_token;
  17715. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17716. {
  17717. std::lock_guard<std::mutex> lock(mtx);
  17718. received_target = req.target;
  17719. if (req.has_param("token")) {
  17720. received_token = req.get_param_value("token");
  17721. }
  17722. }
  17723. std::string msg;
  17724. while (ws.read(msg)) {
  17725. ws.send(msg);
  17726. }
  17727. });
  17728. auto port = svr.bind_to_any_port("localhost");
  17729. std::thread t([&]() { svr.listen_after_bind(); });
  17730. svr.wait_until_ready();
  17731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17732. "/ws?token=ABC&session=123");
  17733. ASSERT_TRUE(client.connect());
  17734. // Round-trip ensures the handler has run and captured the request.
  17735. ASSERT_TRUE(client.send("hello"));
  17736. std::string msg;
  17737. ASSERT_TRUE(client.read(msg));
  17738. EXPECT_EQ("hello", msg);
  17739. client.close();
  17740. {
  17741. std::lock_guard<std::mutex> lock(mtx);
  17742. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17743. EXPECT_EQ("ABC", received_token);
  17744. }
  17745. svr.stop();
  17746. t.join();
  17747. }
  17748. // Run a handshake against a throwaway server and hand the request the server
  17749. // received back to the caller, so tests can assert on the headers the client
  17750. // actually put on the wire.
  17751. static void capture_websocket_handshake_request(
  17752. const Headers &client_headers,
  17753. std::function<void(const Request &, int port)> verify) {
  17754. Server svr;
  17755. std::mutex mtx;
  17756. Request received;
  17757. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17758. {
  17759. std::lock_guard<std::mutex> lock(mtx);
  17760. received = req;
  17761. }
  17762. std::string msg;
  17763. while (ws.read(msg)) {
  17764. ws.send(msg);
  17765. }
  17766. });
  17767. auto port = svr.bind_to_any_port("localhost");
  17768. std::thread t([&]() { svr.listen_after_bind(); });
  17769. auto se = detail::scope_exit([&] {
  17770. svr.stop();
  17771. t.join();
  17772. });
  17773. svr.wait_until_ready();
  17774. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17775. client_headers);
  17776. ASSERT_TRUE(client.connect());
  17777. ASSERT_TRUE(client.send("hello"));
  17778. std::string msg;
  17779. ASSERT_TRUE(client.read(msg));
  17780. client.close();
  17781. {
  17782. std::lock_guard<std::mutex> lock(mtx);
  17783. verify(received, port);
  17784. }
  17785. }
  17786. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17787. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17788. // Non-default port must be present in the Host header. Default ports
  17789. // (80/443) are omitted; that logic is covered by
  17790. // MakeHostAndPortStringTest.
  17791. EXPECT_EQ("localhost:" + std::to_string(port),
  17792. req.get_header_value("Host"));
  17793. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17794. req.get_header_value("User-Agent"));
  17795. EXPECT_FALSE(req.has_header("Accept"));
  17796. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17797. EXPECT_FALSE(req.has_header("Content-Length"));
  17798. });
  17799. }
  17800. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17801. capture_websocket_handshake_request(
  17802. {{"Host", "example.com"},
  17803. {"User-Agent", "custom-agent"},
  17804. {"X-Custom", "value"}},
  17805. [](const Request &req, int) {
  17806. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17807. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17808. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17809. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17810. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17811. });
  17812. }
  17813. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17814. capture_websocket_handshake_request(
  17815. {{"Upgrade", "bogus"},
  17816. {"Connection", "close"},
  17817. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17818. {"Sec-WebSocket-Version", "8"}},
  17819. [](const Request &req, int) {
  17820. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17821. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17822. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17823. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17824. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17825. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17826. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17827. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17828. req.get_header_value("Sec-WebSocket-Key"));
  17829. });
  17830. }
  17831. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17832. // A header the client refuses to send must abort the handshake before any
  17833. // part of it reaches the wire; a lone request line would otherwise sit in
  17834. // the peer's buffer as a truncated request.
  17835. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17836. ASSERT_NE(INVALID_SOCKET, srv);
  17837. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17838. sockaddr_in addr{};
  17839. addr.sin_family = AF_INET;
  17840. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17842. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17843. ASSERT_EQ(0, ::listen(srv, 1));
  17844. sockaddr_in bound{};
  17845. socklen_t bound_len = sizeof(bound);
  17846. ASSERT_EQ(
  17847. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17848. auto port = ntohs(bound.sin_port);
  17849. ssize_t received = -1;
  17850. std::thread t([&] {
  17851. // Bound every blocking call so a regression fails the test with a bad
  17852. // value instead of hanging the suite.
  17853. fd_set rfds;
  17854. FD_ZERO(&rfds);
  17855. FD_SET(srv, &rfds);
  17856. timeval tv{5, 0};
  17857. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17858. 0) {
  17859. return;
  17860. }
  17861. sockaddr_in cli_addr{};
  17862. socklen_t cli_len = sizeof(cli_addr);
  17863. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17864. if (cli == INVALID_SOCKET) { return; }
  17865. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17866. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17867. char buf[4096];
  17868. received = ::recv(cli, buf, sizeof(buf), 0);
  17869. });
  17870. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17871. // connect() has already shut the socket down by the time it returns false,
  17872. // so the peer sees EOF without waiting for the client to be destroyed.
  17873. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17874. {{"X-Bad", "a\r\nInjected: 1"}});
  17875. EXPECT_FALSE(client.connect());
  17876. t.join();
  17877. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17878. EXPECT_EQ(0, received);
  17879. }
  17880. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  17881. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  17882. // contains "upgrade" as a substring is a different token and must not
  17883. // start a WebSocket handshake.
  17884. auto make_request = [](const std::vector<std::string> &connection_values) {
  17885. Request req;
  17886. req.method = "GET";
  17887. req.headers.emplace("Upgrade", "websocket");
  17888. for (const auto &value : connection_values) {
  17889. req.headers.emplace("Connection", value);
  17890. }
  17891. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  17892. req.headers.emplace("Sec-WebSocket-Version", "13");
  17893. return req;
  17894. };
  17895. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  17896. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  17897. EXPECT_TRUE(
  17898. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  17899. EXPECT_TRUE(
  17900. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  17901. EXPECT_TRUE(
  17902. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  17903. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  17904. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  17905. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  17906. EXPECT_FALSE(
  17907. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  17908. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  17909. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  17910. }
  17911. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  17912. Server svr;
  17913. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  17914. auto port = svr.bind_to_any_port("localhost");
  17915. std::thread t([&]() { svr.listen_after_bind(); });
  17916. auto se = detail::scope_exit([&] {
  17917. svr.stop();
  17918. t.join();
  17919. });
  17920. svr.wait_until_ready();
  17921. Headers headers = {{"Upgrade", "websocket"},
  17922. {"Connection", "notupgrade"},
  17923. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  17924. {"Sec-WebSocket-Version", "13"}};
  17925. Client cli("localhost", port);
  17926. auto res = cli.Get("/ws", headers);
  17927. // The route exists only as a WebSocket route, so a request that fails the
  17928. // handshake check falls through to ordinary routing.
  17929. ASSERT_TRUE(res);
  17930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  17931. }
  17932. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  17933. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  17934. // Connection value is the only thing left for the client to reject.
  17935. Server svr;
  17936. svr.Get("/ws", [](const Request &req, Response &res) {
  17937. res.status = StatusCode::SwitchingProtocol_101;
  17938. res.set_header("Upgrade", "websocket");
  17939. res.set_header("Connection", "notupgrade");
  17940. res.set_header("Sec-WebSocket-Accept",
  17941. detail::websocket_accept_key(
  17942. req.get_header_value("Sec-WebSocket-Key")));
  17943. });
  17944. auto port = svr.bind_to_any_port("localhost");
  17945. std::thread t([&]() { svr.listen_after_bind(); });
  17946. auto se = detail::scope_exit([&] {
  17947. svr.stop();
  17948. t.join();
  17949. });
  17950. svr.wait_until_ready();
  17951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17952. auto res = client.connect();
  17953. EXPECT_FALSE(res);
  17954. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17955. EXPECT_FALSE(client.is_open());
  17956. }
  17957. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17958. // The socket path doubles as the URL host, so it must not contain '/'.
  17959. const char *shard = getenv("GTEST_SHARD_INDEX");
  17960. const std::string sock_path =
  17961. shard ? std::string("httplib-ws-") + shard + ".sock"
  17962. : std::string("httplib-ws.sock");
  17963. std::remove(sock_path.c_str());
  17964. Server svr;
  17965. std::mutex mtx;
  17966. std::string received_host;
  17967. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17968. {
  17969. std::lock_guard<std::mutex> lock(mtx);
  17970. received_host = req.get_header_value("Host");
  17971. }
  17972. std::string msg;
  17973. while (ws.read(msg)) {
  17974. ws.send(msg);
  17975. }
  17976. });
  17977. svr.set_address_family(AF_UNIX);
  17978. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17979. auto se = detail::scope_exit([&] {
  17980. svr.stop();
  17981. t.join();
  17982. std::remove(sock_path.c_str());
  17983. });
  17984. svr.wait_until_ready();
  17985. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17986. client.set_address_family(AF_UNIX);
  17987. ASSERT_TRUE(client.connect());
  17988. ASSERT_TRUE(client.send("hello"));
  17989. std::string msg;
  17990. ASSERT_TRUE(client.read(msg));
  17991. client.close();
  17992. {
  17993. std::lock_guard<std::mutex> lock(mtx);
  17994. // There is no host:port for a Unix socket, so the same "localhost"
  17995. // placeholder the HTTP client uses is expected.
  17996. EXPECT_EQ("localhost", received_host);
  17997. }
  17998. }
  17999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18000. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18001. protected:
  18002. void SetUp() override {
  18003. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18004. SERVER_PRIVATE_KEY_FILE);
  18005. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18006. std::string msg;
  18007. ws::ReadResult ret;
  18008. while ((ret = ws.read(msg))) {
  18009. if (ret == ws::Binary) {
  18010. ws.send(msg.data(), msg.size());
  18011. } else {
  18012. ws.send(msg);
  18013. }
  18014. }
  18015. });
  18016. port_ = server_->bind_to_any_port(HOST);
  18017. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18018. server_->wait_until_ready();
  18019. }
  18020. void TearDown() override {
  18021. server_->stop();
  18022. if (server_thread_.joinable()) { server_thread_.join(); }
  18023. }
  18024. std::unique_ptr<SSLServer> server_;
  18025. std::thread server_thread_;
  18026. int port_ = 0;
  18027. };
  18028. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18029. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18030. "/ws-echo");
  18031. client.enable_server_certificate_verification(false);
  18032. ASSERT_TRUE(client.connect());
  18033. ASSERT_TRUE(client.is_open());
  18034. ASSERT_TRUE(client.send("Hello WSS"));
  18035. std::string msg;
  18036. EXPECT_EQ(ws::Text, client.read(msg));
  18037. EXPECT_EQ("Hello WSS", msg);
  18038. client.close();
  18039. }
  18040. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18041. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18042. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18043. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18044. // client (without calling close() first) is the only path that runs
  18045. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18046. // bug exactly.
  18047. //
  18048. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18049. // when linked against an instrumented libssl; run under Valgrind to catch it
  18050. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18051. // suite (the freed session otherwise stalls on the close handshake) — this test
  18052. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18053. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18054. {
  18055. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18056. "/ws-echo");
  18057. client.enable_server_certificate_verification(false);
  18058. client.set_read_timeout(2, 0);
  18059. client.set_write_timeout(2, 0);
  18060. ASSERT_TRUE(client.connect());
  18061. ASSERT_TRUE(client.is_open());
  18062. ASSERT_TRUE(client.send("still open"));
  18063. // Intentionally do NOT call client.close(): leaving scope runs
  18064. // shutdown_and_close() with the WebSocket still open, which must send the
  18065. // close frame while the TLS session is still alive.
  18066. }
  18067. }
  18068. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18069. // shutdown_and_close() at the start of connect(), reproducing the same
  18070. // use-after-free within the test body rather than at scope exit. The second
  18071. // connect must succeed and echo, proving the close handshake ran over a live
  18072. // session. See the note above about memory-tool requirements.
  18073. TEST_F(WebSocketSSLIntegrationTest,
  18074. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18075. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18076. "/ws-echo");
  18077. client.enable_server_certificate_verification(false);
  18078. client.set_read_timeout(2, 0);
  18079. client.set_write_timeout(2, 0);
  18080. ASSERT_TRUE(client.connect());
  18081. ASSERT_TRUE(client.is_open());
  18082. ASSERT_TRUE(client.send("still open"));
  18083. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18084. // the still-open connection, which must not touch a freed TLS session.
  18085. ASSERT_TRUE(client.connect());
  18086. ASSERT_TRUE(client.is_open());
  18087. ASSERT_TRUE(client.send("after reconnect"));
  18088. std::string msg;
  18089. EXPECT_EQ(ws::Text, client.read(msg));
  18090. EXPECT_EQ("after reconnect", msg);
  18091. client.close();
  18092. }
  18093. #endif
  18094. #ifdef CPPHTTPLIB_SSL_ENABLED
  18095. class WebSocketSSLCATest : public ::testing::Test {
  18096. protected:
  18097. void SetUp() override {
  18098. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18099. SERVER_PRIVATE_KEY_FILE);
  18100. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18101. std::string msg;
  18102. while (ws.read(msg)) {
  18103. ws.send(msg);
  18104. }
  18105. });
  18106. port_ = server_->bind_to_any_port("127.0.0.1");
  18107. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18108. server_->wait_until_ready();
  18109. }
  18110. void TearDown() override {
  18111. server_->stop();
  18112. if (server_thread_.joinable()) { server_thread_.join(); }
  18113. }
  18114. std::string url() const {
  18115. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18116. }
  18117. std::unique_ptr<SSLServer> server_;
  18118. std::thread server_thread_;
  18119. int port_ = 0;
  18120. };
  18121. // A custom CA loaded as PEM verifies the server with full certificate
  18122. // verification enabled
  18123. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18124. ws::WebSocketClient client(url());
  18125. std::string cert;
  18126. read_file(SERVER_CERT2_FILE, cert);
  18127. client.load_ca_cert_store(cert.c_str(), cert.size());
  18128. ASSERT_TRUE(client.connect());
  18129. ASSERT_TRUE(client.send("hello"));
  18130. std::string msg;
  18131. EXPECT_EQ(ws::Text, client.read(msg));
  18132. EXPECT_EQ("hello", msg);
  18133. client.close();
  18134. }
  18135. // A custom CA that does not cover the server must fail verification (the
  18136. // custom CA is exclusive; system certs are not loaded alongside it)
  18137. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18138. ws::WebSocketClient client(url());
  18139. std::string cert;
  18140. read_file(CLIENT_CA_CERT_FILE, cert);
  18141. client.load_ca_cert_store(cert.c_str(), cert.size());
  18142. auto res = client.connect();
  18143. ASSERT_FALSE(res);
  18144. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18145. EXPECT_EQ(-1, res.status());
  18146. EXPECT_NE(0u, res.ssl_backend_error());
  18147. }
  18148. // The same CA as a file path rather than PEM in memory
  18149. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18150. ws::WebSocketClient client(url());
  18151. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18152. ASSERT_TRUE(client.connect());
  18153. ASSERT_TRUE(client.send("hello"));
  18154. std::string msg;
  18155. EXPECT_EQ(ws::Text, client.read(msg));
  18156. EXPECT_EQ("hello", msg);
  18157. client.close();
  18158. }
  18159. // ...and a CA file that does not cover the server still fails, so it is the
  18160. // path above that decides the outcome
  18161. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18162. ws::WebSocketClient client(url());
  18163. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18164. ASSERT_FALSE(client.connect());
  18165. }
  18166. // Regression test: reconnecting with a native custom CA store used to reuse
  18167. // a store handle the previous TLS context had already freed (use-after-free
  18168. // under the OpenSSL backend). The context now lives as long as the client.
  18169. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18170. ws::WebSocketClient client(url());
  18171. std::string cert;
  18172. read_file(SERVER_CERT2_FILE, cert);
  18173. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18174. ASSERT_TRUE(client.connect());
  18175. client.close();
  18176. ASSERT_TRUE(client.connect());
  18177. ASSERT_TRUE(client.send("again"));
  18178. std::string msg;
  18179. EXPECT_EQ(ws::Text, client.read(msg));
  18180. EXPECT_EQ("again", msg);
  18181. client.close();
  18182. }
  18183. // Regression test: a certificate with a trusted chain but no identity match
  18184. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18185. // verification entirely for IP hosts, so this connection succeeded there.
  18186. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18187. // chain verification while the identity check must still fail.
  18188. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18190. ASSERT_TRUE(svr.is_valid());
  18191. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18192. std::string msg;
  18193. while (ws.read(msg)) {
  18194. ws.send(msg);
  18195. }
  18196. });
  18197. auto port = svr.bind_to_any_port("127.0.0.1");
  18198. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18199. auto se = detail::scope_exit([&] {
  18200. svr.stop();
  18201. t.join();
  18202. });
  18203. svr.wait_until_ready();
  18204. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18205. "/echo");
  18206. std::string cert;
  18207. read_file(SERVER_CERT_FILE, cert);
  18208. client.load_ca_cert_store(cert.c_str(), cert.size());
  18209. ASSERT_FALSE(client.connect());
  18210. }
  18211. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18212. // SNI, so nothing binds the host name to the TLS session. These bind the
  18213. // server to "localhost" instead, the only shape that exercises the SNI and
  18214. // hostname-verification path with certificate verification left enabled.
  18215. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18216. protected:
  18217. void Start(const char *cert_file) {
  18218. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18219. SERVER_PRIVATE_KEY_FILE);
  18220. ASSERT_TRUE(server_->is_valid());
  18221. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18222. std::string msg;
  18223. while (ws.read(msg)) {
  18224. ws.send(msg);
  18225. }
  18226. });
  18227. port_ = server_->bind_to_any_port("localhost");
  18228. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18229. server_->wait_until_ready();
  18230. }
  18231. void TearDown() override {
  18232. if (server_) { server_->stop(); }
  18233. if (server_thread_.joinable()) { server_thread_.join(); }
  18234. }
  18235. std::string url() const {
  18236. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18237. }
  18238. std::unique_ptr<SSLServer> server_;
  18239. std::thread server_thread_;
  18240. int port_ = 0;
  18241. };
  18242. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18243. // out and the connection is usable
  18244. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18245. Start(SERVER_CERT2_FILE);
  18246. ws::WebSocketClient client(url());
  18247. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18248. ASSERT_TRUE(client.connect());
  18249. ASSERT_TRUE(client.send("hello"));
  18250. std::string msg;
  18251. EXPECT_EQ(ws::Text, client.read(msg));
  18252. EXPECT_EQ("hello", msg);
  18253. client.close();
  18254. }
  18255. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18256. // while the identity check must still reject "localhost"
  18257. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18258. Start(SERVER_CERT_FILE);
  18259. ws::WebSocketClient client(url());
  18260. client.set_ca_cert_path(SERVER_CERT_FILE);
  18261. auto res = client.connect();
  18262. ASSERT_FALSE(res);
  18263. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18264. EXPECT_EQ(-1, res.status());
  18265. }
  18266. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18267. // disabled: the chain is still checked, only the identity check is skipped
  18268. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18269. Start(SERVER_CERT_FILE);
  18270. ws::WebSocketClient client(url());
  18271. client.set_ca_cert_path(SERVER_CERT_FILE);
  18272. client.enable_server_hostname_verification(false);
  18273. ASSERT_TRUE(client.connect());
  18274. ASSERT_TRUE(client.send("hello"));
  18275. std::string msg;
  18276. EXPECT_EQ(ws::Text, client.read(msg));
  18277. EXPECT_EQ("hello", msg);
  18278. client.close();
  18279. }
  18280. // A CA that did not sign the server certificate fails the chain, even though
  18281. // the name would match
  18282. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18283. Start(SERVER_CERT2_FILE);
  18284. ws::WebSocketClient client(url());
  18285. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18286. ASSERT_FALSE(client.connect());
  18287. }
  18288. // With verification disabled, neither the chain nor the name is checked
  18289. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18290. Start(SERVER_CERT_FILE);
  18291. ws::WebSocketClient client(url());
  18292. client.enable_server_certificate_verification(false);
  18293. ASSERT_TRUE(client.connect());
  18294. ASSERT_TRUE(client.send("hello"));
  18295. std::string msg;
  18296. EXPECT_EQ(ws::Text, client.read(msg));
  18297. EXPECT_EQ("hello", msg);
  18298. client.close();
  18299. }
  18300. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18301. protected:
  18302. void SetUp() override {
  18303. server_ = httplib::detail::make_unique<SSLServer>(
  18304. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18305. ASSERT_TRUE(server_->is_valid());
  18306. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18307. std::string msg;
  18308. while (ws.read(msg)) {
  18309. ws.send(msg);
  18310. }
  18311. });
  18312. port_ = server_->bind_to_any_port("localhost");
  18313. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18314. server_->wait_until_ready();
  18315. }
  18316. void TearDown() override {
  18317. server_->stop();
  18318. if (server_thread_.joinable()) { server_thread_.join(); }
  18319. }
  18320. std::string url() const {
  18321. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18322. }
  18323. void ConnectWithClientCert(const std::string &client_cert_file,
  18324. const std::string &client_private_key_file,
  18325. const char *private_key_password) {
  18326. std::string cert_pem, key_pem;
  18327. read_file(client_cert_file, cert_pem);
  18328. read_file(client_private_key_file, key_pem);
  18329. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18330. key_pem.c_str(), key_pem.size(),
  18331. private_key_password};
  18332. ws::WebSocketClient client(url(), pem);
  18333. ASSERT_TRUE(client.is_valid());
  18334. client.enable_server_certificate_verification(false);
  18335. ASSERT_TRUE(client.connect());
  18336. ASSERT_TRUE(client.send("hello"));
  18337. std::string msg;
  18338. EXPECT_EQ(ws::Text, client.read(msg));
  18339. EXPECT_EQ("hello", msg);
  18340. client.close();
  18341. }
  18342. std::unique_ptr<SSLServer> server_;
  18343. std::thread server_thread_;
  18344. int port_ = 0;
  18345. };
  18346. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18347. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18348. }
  18349. // Control for the tests above: the fixture's server really does require a
  18350. // client certificate, so it is the PEM the constructor installed that decides
  18351. // the outcome.
  18352. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18353. ws::WebSocketClient client(url());
  18354. ASSERT_TRUE(client.is_valid());
  18355. client.enable_server_certificate_verification(false);
  18356. EXPECT_FALSE(client.connect());
  18357. }
  18358. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18359. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18360. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18361. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18362. }
  18363. #endif
  18364. #if !defined(_WIN32)
  18365. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18366. auto secret_dir = std::string("./symlink_test_secret");
  18367. auto served_dir = std::string("./symlink_test_served");
  18368. auto secret_file = secret_dir + "/secret.txt";
  18369. auto symlink_path = served_dir + "/escape";
  18370. // Setup: create directories and files
  18371. mkdir(secret_dir.c_str(), 0755);
  18372. mkdir(served_dir.c_str(), 0755);
  18373. {
  18374. std::ofstream ofs(secret_file);
  18375. ofs << "SECRET_DATA";
  18376. }
  18377. // Create symlink using absolute path so it resolves correctly
  18378. #ifdef PATH_MAX
  18379. char abs_secret[PATH_MAX];
  18380. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18381. #else
  18382. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18383. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18384. ASSERT_NE(nullptr, abs_secret);
  18385. #endif
  18386. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18387. auto se = detail::scope_exit([&] {
  18388. unlink(symlink_path.c_str());
  18389. unlink(secret_file.c_str());
  18390. rmdir(served_dir.c_str());
  18391. rmdir(secret_dir.c_str());
  18392. });
  18393. Server svr;
  18394. svr.set_mount_point("/", served_dir);
  18395. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18396. auto se2 = detail::scope_exit([&] {
  18397. svr.stop();
  18398. listen_thread.join();
  18399. });
  18400. svr.wait_until_ready();
  18401. Client cli("localhost", PORT);
  18402. // Symlink pointing outside base dir should be blocked
  18403. auto res = cli.Get("/escape/secret.txt");
  18404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18405. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18406. }
  18407. #endif
  18408. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18409. // A GET request with Content-Length to a static file handler must have its
  18410. // body drained before the keep-alive connection is reused. Otherwise the
  18411. // unread body bytes are interpreted as the next HTTP request.
  18412. //
  18413. // The body is sent AFTER receiving the first response (as in the original
  18414. // PoC) so that the stream_line_reader cannot buffer it together with the
  18415. // headers of the first request.
  18416. Server svr;
  18417. svr.set_mount_point("/", "./www");
  18418. std::atomic<int> smuggled_count(0);
  18419. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18420. smuggled_count++;
  18421. res.set_content("oops", "text/plain");
  18422. });
  18423. auto port = svr.bind_to_any_port("localhost");
  18424. thread t = thread([&] { svr.listen_after_bind(); });
  18425. auto se = detail::scope_exit([&] {
  18426. svr.stop();
  18427. t.join();
  18428. });
  18429. svr.wait_until_ready();
  18430. auto error = Error::Success;
  18431. auto sock = detail::create_client_socket(
  18432. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18433. /*connection_timeout_sec=*/2, 0,
  18434. /*read_timeout_sec=*/2, 0,
  18435. /*write_timeout_sec=*/2, 0, std::string(), error);
  18436. ASSERT_NE(INVALID_SOCKET, sock);
  18437. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18438. // The "smuggled" request will be sent as the body of the outer GET
  18439. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18440. "Host: localhost\r\n"
  18441. "Connection: close\r\n"
  18442. "\r\n";
  18443. // Step 1: Send only the outer request headers (no body yet)
  18444. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18445. "Host: localhost\r\n"
  18446. "Content-Length: " +
  18447. std::to_string(smuggled.size()) +
  18448. "\r\n"
  18449. "\r\n";
  18450. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18451. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18452. // Step 2: Read the first response (server serves file without reading body)
  18453. std::string first_response;
  18454. char buf[4096];
  18455. for (;;) {
  18456. auto n = recv(sock, buf, sizeof(buf), 0);
  18457. if (n <= 0) break;
  18458. first_response.append(buf, static_cast<size_t>(n));
  18459. // Stop once we have a complete response (headers + body)
  18460. auto hdr_end = first_response.find("\r\n\r\n");
  18461. if (hdr_end != std::string::npos) {
  18462. // Check for Content-Length to know when the body is complete
  18463. auto cl_pos = first_response.find("Content-Length:");
  18464. if (cl_pos != std::string::npos) {
  18465. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18466. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18467. auto cl = std::stoul(
  18468. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18469. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18470. } else {
  18471. break; // No Content-Length, assume headers-only response
  18472. }
  18473. }
  18474. }
  18475. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18476. // Step 3: Now send the body, which looks like a new HTTP request.
  18477. // On a vulnerable server the keep-alive loop reads this as a second request.
  18478. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18479. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18480. // Step 4: Try to read a second response (should NOT exist after fix)
  18481. std::string second_response;
  18482. for (;;) {
  18483. auto n = recv(sock, buf, sizeof(buf), 0);
  18484. if (n <= 0) break;
  18485. second_response.append(buf, static_cast<size_t>(n));
  18486. }
  18487. // The smuggled request must NOT have been processed
  18488. EXPECT_EQ(0, smuggled_count.load());
  18489. }
  18490. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18491. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18492. // must be rejected with 400 Bad Request.
  18493. Server svr;
  18494. svr.Post("/test", [&](const Request &, Response &res) {
  18495. res.set_content("ok", "text/plain");
  18496. });
  18497. thread t = thread([&] { svr.listen(HOST, PORT); });
  18498. auto se = detail::scope_exit([&] {
  18499. svr.stop();
  18500. t.join();
  18501. ASSERT_FALSE(svr.is_running());
  18502. });
  18503. svr.wait_until_ready();
  18504. // Exact "chunked"
  18505. {
  18506. auto req = "POST /test HTTP/1.1\r\n"
  18507. "Host: localhost\r\n"
  18508. "Content-Length: 5\r\n"
  18509. "Transfer-Encoding: chunked\r\n"
  18510. "Connection: close\r\n"
  18511. "\r\n"
  18512. "hello";
  18513. std::string response;
  18514. ASSERT_TRUE(send_request(1, req, &response));
  18515. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18516. response.substr(0, response.find("\r\n")));
  18517. }
  18518. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18519. {
  18520. auto req = "POST /test HTTP/1.1\r\n"
  18521. "Host: localhost\r\n"
  18522. "Content-Length: 5\r\n"
  18523. "Transfer-Encoding: gzip, chunked\r\n"
  18524. "Connection: close\r\n"
  18525. "\r\n"
  18526. "hello";
  18527. std::string response;
  18528. ASSERT_TRUE(send_request(1, req, &response));
  18529. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18530. response.substr(0, response.find("\r\n")));
  18531. }
  18532. }
  18533. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18534. Server svr;
  18535. svr.Post("/test", [&](const Request &, Response &res) {
  18536. res.set_content("ok", "text/plain");
  18537. });
  18538. thread t = thread([&] { svr.listen(HOST, PORT); });
  18539. auto se = detail::scope_exit([&] {
  18540. svr.stop();
  18541. t.join();
  18542. ASSERT_FALSE(svr.is_running());
  18543. });
  18544. svr.wait_until_ready();
  18545. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18546. // length cannot be determined, so the server must answer 400 and close
  18547. // rather than treat the request as bodyless and leave the body in the
  18548. // socket for the next request to pick up.
  18549. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18550. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18551. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18552. std::string response;
  18553. ASSERT_TRUE(send_request(1, req, &response));
  18554. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18555. response.substr(0, response.find("\r\n")))
  18556. << transfer_encoding;
  18557. }
  18558. // RFC 9110 5.3: the codings may also be split across several
  18559. // Transfer-Encoding lines, which combine in the order they were received.
  18560. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18561. // just like the single-line "chunked, gzip" above.
  18562. {
  18563. auto req = "POST /test HTTP/1.1\r\n"
  18564. "Host: localhost\r\n"
  18565. "Transfer-Encoding: chunked\r\n"
  18566. "Transfer-Encoding: gzip\r\n"
  18567. "\r\n"
  18568. "0\r\n\r\n";
  18569. std::string response;
  18570. ASSERT_TRUE(send_request(1, req, &response));
  18571. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18572. response.substr(0, response.find("\r\n")));
  18573. }
  18574. // A sequence ending in chunked stays valid.
  18575. auto req = "POST /test HTTP/1.1\r\n"
  18576. "Host: localhost\r\n"
  18577. "Transfer-Encoding: gzip, chunked\r\n"
  18578. "Connection: close\r\n"
  18579. "\r\n"
  18580. "0\r\n\r\n";
  18581. std::string response;
  18582. ASSERT_TRUE(send_request(1, req, &response));
  18583. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18584. // ...including when it is spread over several lines.
  18585. auto split_req = "POST /test HTTP/1.1\r\n"
  18586. "Host: localhost\r\n"
  18587. "Transfer-Encoding: gzip\r\n"
  18588. "Transfer-Encoding: chunked\r\n"
  18589. "Connection: close\r\n"
  18590. "\r\n"
  18591. "0\r\n\r\n";
  18592. std::string split_response;
  18593. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18594. EXPECT_EQ("HTTP/1.1 200 OK",
  18595. split_response.substr(0, split_response.find("\r\n")));
  18596. }
  18597. // Regression for issue #2450: a DELETE without Content-Length on a
  18598. // keep-alive connection must not let the post-response drain consume the
  18599. // next request's bytes.
  18600. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18601. Server svr;
  18602. std::atomic<int> delete_count(0);
  18603. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18604. delete_count++;
  18605. res.status = StatusCode::NoContent_204;
  18606. });
  18607. auto port = svr.bind_to_any_port(HOST);
  18608. thread t = thread([&] { svr.listen_after_bind(); });
  18609. auto se = detail::scope_exit([&] {
  18610. svr.stop();
  18611. t.join();
  18612. });
  18613. svr.wait_until_ready();
  18614. auto error = Error::Success;
  18615. auto sock = detail::create_client_socket(
  18616. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18617. /*connection_timeout_sec=*/2, 0,
  18618. /*read_timeout_sec=*/2, 0,
  18619. /*write_timeout_sec=*/2, 0, std::string(), error);
  18620. ASSERT_NE(INVALID_SOCKET, sock);
  18621. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18622. auto send_request_and_read_response = [&](const std::string &req,
  18623. std::string &out) -> bool {
  18624. auto sent = send(sock, req.data(), req.size(), 0);
  18625. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18626. char buf[4096];
  18627. for (;;) {
  18628. auto n = recv(sock, buf, sizeof(buf), 0);
  18629. if (n <= 0) { return !out.empty(); }
  18630. out.append(buf, static_cast<size_t>(n));
  18631. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18632. }
  18633. };
  18634. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18635. "Host: localhost\r\n"
  18636. "\r\n";
  18637. std::string resp1;
  18638. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18639. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18640. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18641. "Host: localhost\r\n"
  18642. "Connection: close\r\n"
  18643. "\r\n";
  18644. std::string resp2;
  18645. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18646. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18647. EXPECT_EQ(2, delete_count.load());
  18648. }
  18649. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18650. Server svr;
  18651. svr.Post("/ingest", [&](const Request &, Response &res,
  18652. const ContentReader &content_reader) {
  18653. auto consumed = content_reader([](const char *, size_t) { return false; });
  18654. EXPECT_FALSE(consumed);
  18655. res.status = StatusCode::Conflict_409;
  18656. res.set_header("Connection", "close");
  18657. });
  18658. auto port = svr.bind_to_any_port(HOST);
  18659. thread t = thread([&] { svr.listen_after_bind(); });
  18660. auto se = detail::scope_exit([&] {
  18661. svr.stop();
  18662. t.join();
  18663. });
  18664. svr.wait_until_ready();
  18665. auto error = Error::Success;
  18666. auto sock = detail::create_client_socket(
  18667. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18668. /*connection_timeout_sec=*/2, 0,
  18669. /*read_timeout_sec=*/1, 0,
  18670. /*write_timeout_sec=*/2, 0, std::string(), error);
  18671. ASSERT_NE(INVALID_SOCKET, sock);
  18672. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18673. std::string request = "POST /ingest HTTP/1.1\r\n"
  18674. "Host: localhost\r\n"
  18675. "Transfer-Encoding: chunked\r\n"
  18676. "\r\n"
  18677. "4\r\n"
  18678. "data\r\n";
  18679. auto sent = send(sock, request.data(), request.size(), 0);
  18680. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18681. std::string response;
  18682. ssize_t received = 0;
  18683. do {
  18684. char buf[4096];
  18685. received = recv(sock, buf, sizeof(buf), 0);
  18686. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18687. } while (received > 0);
  18688. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18689. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18690. EXPECT_EQ(0, received);
  18691. }
  18692. namespace no_proxy_test {
  18693. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18694. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18695. // calling listen().
  18696. class ScopedServer {
  18697. public:
  18698. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18699. ~ScopedServer() {
  18700. svr_.stop();
  18701. if (th_.joinable()) { th_.join(); }
  18702. }
  18703. Server &svr() { return svr_; }
  18704. int port() const { return port_; }
  18705. void listen() {
  18706. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18707. svr_.wait_until_ready();
  18708. }
  18709. private:
  18710. Server svr_;
  18711. std::thread th_;
  18712. int port_ = 0;
  18713. };
  18714. class ProxyAndTargetServers {
  18715. public:
  18716. ProxyAndTargetServers() {
  18717. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18718. proxy_hits_++;
  18719. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18720. res.set_content("via-proxy", "text/plain");
  18721. });
  18722. target_.Get(".*", [this](const Request &req, Response &res) {
  18723. target_hits_++;
  18724. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18725. res.set_content("direct", "text/plain");
  18726. });
  18727. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18728. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18729. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18730. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18731. proxy_mock_.wait_until_ready();
  18732. target_.wait_until_ready();
  18733. }
  18734. ~ProxyAndTargetServers() {
  18735. proxy_mock_.stop();
  18736. target_.stop();
  18737. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18738. if (target_thread_.joinable()) { target_thread_.join(); }
  18739. }
  18740. Server &proxy_mock() { return proxy_mock_; }
  18741. Server &target() { return target_; }
  18742. int proxy_port() const { return proxy_port_; }
  18743. int target_port() const { return target_port_; }
  18744. int proxy_hits() const { return proxy_hits_.load(); }
  18745. int target_hits() const { return target_hits_.load(); }
  18746. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18747. void reset_counters() {
  18748. proxy_hits_ = 0;
  18749. target_hits_ = 0;
  18750. last_had_proxy_authz_ = false;
  18751. }
  18752. private:
  18753. Server proxy_mock_;
  18754. Server target_;
  18755. std::thread proxy_thread_;
  18756. std::thread target_thread_;
  18757. int proxy_port_ = 0;
  18758. int target_port_ = 0;
  18759. std::atomic<int> proxy_hits_{0};
  18760. std::atomic<int> target_hits_{0};
  18761. std::atomic<bool> last_had_proxy_authz_{false};
  18762. };
  18763. inline std::unique_ptr<Client> make_client(const std::string &host,
  18764. ProxyAndTargetServers &s) {
  18765. auto cli = detail::make_unique<Client>(host, s.target_port());
  18766. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18767. cli->set_proxy("127.0.0.1", s.proxy_port());
  18768. return cli;
  18769. }
  18770. } // namespace no_proxy_test
  18771. using no_proxy_test::make_client;
  18772. using no_proxy_test::ProxyAndTargetServers;
  18773. TEST(NoProxyTest, ExactHostnameBypasses) {
  18774. ProxyAndTargetServers s;
  18775. auto cli = make_client("example.com", s);
  18776. cli->set_no_proxy({"example.com"});
  18777. auto res = cli->Get("/");
  18778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18779. EXPECT_EQ(0, s.proxy_hits());
  18780. EXPECT_EQ(1, s.target_hits());
  18781. }
  18782. TEST(NoProxyTest, SubdomainBypasses) {
  18783. ProxyAndTargetServers s;
  18784. auto cli = make_client("foo.example.com", s);
  18785. cli->set_no_proxy({"example.com"});
  18786. auto res = cli->Get("/");
  18787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18788. EXPECT_EQ(0, s.proxy_hits());
  18789. EXPECT_EQ(1, s.target_hits());
  18790. }
  18791. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18792. // Regression guard: "evilexample.com" must not be considered a subdomain
  18793. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18794. // check would let traffic bypass the proxy and leak credentials direct
  18795. // to the attacker host.
  18796. ProxyAndTargetServers s;
  18797. auto cli = make_client("evilexample.com", s);
  18798. cli->set_no_proxy({"example.com"});
  18799. auto res = cli->Get("/");
  18800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18801. EXPECT_GE(s.proxy_hits(), 1);
  18802. EXPECT_EQ(0, s.target_hits());
  18803. }
  18804. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18805. ProxyAndTargetServers s;
  18806. auto cli = make_client("example.com.evil.com", s);
  18807. cli->set_no_proxy({"example.com"});
  18808. auto res = cli->Get("/");
  18809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18810. EXPECT_GE(s.proxy_hits(), 1);
  18811. EXPECT_EQ(0, s.target_hits());
  18812. }
  18813. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18814. ProxyAndTargetServers s;
  18815. auto cli = make_client("example.com", s);
  18816. cli->set_no_proxy({".example.com"});
  18817. auto res = cli->Get("/");
  18818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18819. EXPECT_EQ(0, s.proxy_hits());
  18820. EXPECT_EQ(1, s.target_hits());
  18821. }
  18822. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18823. ProxyAndTargetServers s;
  18824. auto cli = make_client("Example.COM", s);
  18825. cli->set_no_proxy({"EXAMPLE.com"});
  18826. auto res = cli->Get("/");
  18827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18828. EXPECT_EQ(0, s.proxy_hits());
  18829. EXPECT_EQ(1, s.target_hits());
  18830. }
  18831. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18832. ProxyAndTargetServers s;
  18833. auto cli = make_client("example.com.", s);
  18834. cli->set_no_proxy({"example.com"});
  18835. auto res = cli->Get("/");
  18836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18837. EXPECT_EQ(0, s.proxy_hits());
  18838. EXPECT_EQ(1, s.target_hits());
  18839. }
  18840. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18841. // Trailing dots must be normalized on BOTH sides — host and entry.
  18842. // An implementation that only strips the host-side trailing dot would
  18843. // fail to match host "example.com" against entry "example.com." because
  18844. // a literal substring search would compare 11 chars against 12.
  18845. ProxyAndTargetServers s;
  18846. auto cli = make_client("example.com", s);
  18847. cli->set_no_proxy({"example.com."});
  18848. auto res = cli->Get("/");
  18849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18850. EXPECT_EQ(0, s.proxy_hits());
  18851. EXPECT_EQ(1, s.target_hits());
  18852. }
  18853. TEST(NoProxyTest, WildcardBypassesEverything) {
  18854. ProxyAndTargetServers s;
  18855. auto cli = make_client("anything.invalid.test", s);
  18856. cli->set_no_proxy({"*"});
  18857. auto res = cli->Get("/");
  18858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18859. EXPECT_EQ(0, s.proxy_hits());
  18860. EXPECT_EQ(1, s.target_hits());
  18861. }
  18862. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18863. ProxyAndTargetServers s;
  18864. Client cli("127.0.0.1", s.target_port());
  18865. cli.set_proxy("127.0.0.1", s.proxy_port());
  18866. cli.set_no_proxy({"127.0.0.1"});
  18867. auto res = cli.Get("/");
  18868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18869. EXPECT_EQ(0, s.proxy_hits());
  18870. EXPECT_EQ(1, s.target_hits());
  18871. }
  18872. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18873. ProxyAndTargetServers s;
  18874. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18875. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18876. cli.set_proxy("127.0.0.1", s.proxy_port());
  18877. cli.set_no_proxy({"::1"});
  18878. auto res = cli.Get("/");
  18879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18880. EXPECT_EQ(0, s.proxy_hits());
  18881. EXPECT_EQ(1, s.target_hits());
  18882. }
  18883. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18884. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18885. // must still be recognized as IPv6 for CIDR matching. Implementations
  18886. // that detect IPv6 only when the host begins with '[' would parse the
  18887. // host as a hostname and miss the match.
  18888. ProxyAndTargetServers s;
  18889. Client cli("fe80::1", s.target_port());
  18890. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18891. cli.set_proxy("127.0.0.1", s.proxy_port());
  18892. cli.set_no_proxy({"fe80::/10"});
  18893. auto res = cli.Get("/");
  18894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18895. EXPECT_EQ(0, s.proxy_hits());
  18896. EXPECT_EQ(1, s.target_hits());
  18897. }
  18898. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18899. ProxyAndTargetServers s;
  18900. Client cli("::1", s.target_port());
  18901. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18902. cli.set_proxy("127.0.0.1", s.proxy_port());
  18903. cli.set_no_proxy({"[::1]"});
  18904. auto res = cli.Get("/");
  18905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18906. EXPECT_EQ(0, s.proxy_hits());
  18907. EXPECT_EQ(1, s.target_hits());
  18908. }
  18909. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18910. ProxyAndTargetServers s;
  18911. Client cli("fe80::1", s.target_port());
  18912. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18913. cli.set_proxy("127.0.0.1", s.proxy_port());
  18914. cli.set_no_proxy({"[fe80::]/10"});
  18915. auto res = cli.Get("/");
  18916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18917. EXPECT_EQ(0, s.proxy_hits());
  18918. EXPECT_EQ(1, s.target_hits());
  18919. }
  18920. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18921. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18922. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18923. // tricks via address-family conversion.
  18924. ProxyAndTargetServers s;
  18925. Client cli("::ffff:127.0.0.1", s.target_port());
  18926. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18927. cli.set_proxy("127.0.0.1", s.proxy_port());
  18928. cli.set_no_proxy({"127.0.0.1"});
  18929. auto res = cli.Get("/");
  18930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18931. EXPECT_GE(s.proxy_hits(), 1);
  18932. EXPECT_EQ(0, s.target_hits());
  18933. }
  18934. TEST(NoProxyTest, IPv4CidrMatch) {
  18935. ProxyAndTargetServers s;
  18936. Client cli("127.0.0.1", s.target_port());
  18937. cli.set_proxy("127.0.0.1", s.proxy_port());
  18938. cli.set_no_proxy({"127.0.0.0/8"});
  18939. auto res = cli.Get("/");
  18940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18941. EXPECT_EQ(0, s.proxy_hits());
  18942. EXPECT_EQ(1, s.target_hits());
  18943. }
  18944. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18945. ProxyAndTargetServers s;
  18946. Client cli("127.0.0.1", s.target_port());
  18947. cli.set_proxy("127.0.0.1", s.proxy_port());
  18948. cli.set_no_proxy({"10.0.0.0/8"});
  18949. auto res = cli.Get("/");
  18950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18951. EXPECT_GE(s.proxy_hits(), 1);
  18952. EXPECT_EQ(0, s.target_hits());
  18953. }
  18954. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18955. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18956. // IPv4 target matches.
  18957. ProxyAndTargetServers s;
  18958. Client cli("127.0.0.1", s.target_port());
  18959. cli.set_proxy("127.0.0.1", s.proxy_port());
  18960. cli.set_no_proxy({"0.0.0.0/0"});
  18961. auto res = cli.Get("/");
  18962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18963. EXPECT_EQ(0, s.proxy_hits());
  18964. EXPECT_EQ(1, s.target_hits());
  18965. }
  18966. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18967. ProxyAndTargetServers s;
  18968. Client cli("127.0.0.1", s.target_port());
  18969. cli.set_proxy("127.0.0.1", s.proxy_port());
  18970. cli.set_no_proxy({"127.0.0.1"});
  18971. auto res = cli.Get("/");
  18972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18973. EXPECT_EQ(0, s.proxy_hits());
  18974. EXPECT_EQ(1, s.target_hits());
  18975. }
  18976. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18977. ProxyAndTargetServers s;
  18978. Client cli("127.0.0.1", s.target_port());
  18979. cli.set_proxy("127.0.0.1", s.proxy_port());
  18980. cli.set_no_proxy({"127.0.0.0/33"});
  18981. auto res = cli.Get("/");
  18982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18983. EXPECT_GE(s.proxy_hits(), 1);
  18984. EXPECT_EQ(0, s.target_hits());
  18985. }
  18986. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18987. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18988. ProxyAndTargetServers s;
  18989. Client cli("127.0.0.1", s.target_port());
  18990. cli.set_proxy("127.0.0.1", s.proxy_port());
  18991. cli.set_no_proxy({"127.0.0.1/"});
  18992. auto res = cli.Get("/");
  18993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18994. EXPECT_GE(s.proxy_hits(), 1);
  18995. EXPECT_EQ(0, s.target_hits());
  18996. }
  18997. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18998. ProxyAndTargetServers s;
  18999. auto cli = make_client("internal.corp", s);
  19000. cli->set_proxy_basic_auth("u", "p");
  19001. cli->set_no_proxy({"internal.corp"});
  19002. auto res = cli->Get("/");
  19003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19004. EXPECT_EQ(1, s.target_hits());
  19005. EXPECT_EQ(0, s.proxy_hits());
  19006. EXPECT_FALSE(s.last_had_proxy_authz())
  19007. << "Proxy-Authorization must not be sent direct to the target";
  19008. }
  19009. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19010. ProxyAndTargetServers s;
  19011. auto cli = make_client("public.example", s);
  19012. cli->set_proxy_basic_auth("u", "p");
  19013. cli->set_no_proxy({"internal.corp"}); // does not match
  19014. auto res = cli->Get("/");
  19015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19016. EXPECT_GE(s.proxy_hits(), 1);
  19017. EXPECT_TRUE(s.last_had_proxy_authz());
  19018. }
  19019. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19020. ProxyAndTargetServers s;
  19021. auto cli = make_client("anything.test", s);
  19022. auto res = cli->Get("/");
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_GE(s.proxy_hits(), 1);
  19025. EXPECT_EQ(0, s.target_hits());
  19026. }
  19027. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19028. ProxyAndTargetServers s;
  19029. auto cli = make_client("example.com", s);
  19030. cli->set_no_proxy({"example.com:8080"});
  19031. auto res = cli->Get("/");
  19032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19033. EXPECT_GE(s.proxy_hits(), 1);
  19034. EXPECT_EQ(0, s.target_hits());
  19035. }
  19036. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19037. ProxyAndTargetServers s;
  19038. auto cli = make_client("anything.test", s);
  19039. cli->set_no_proxy({"", " ", "\t"});
  19040. auto res = cli->Get("/");
  19041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19042. EXPECT_GE(s.proxy_hits(), 1);
  19043. EXPECT_EQ(0, s.target_hits());
  19044. }
  19045. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19046. // An entry with leading/trailing whitespace must still match — env-style
  19047. // values are commonly pasted with stray spaces and an implementation
  19048. // that feeds the raw token directly to inet_pton would fail to match
  19049. // valid CIDRs because of the spaces.
  19050. ProxyAndTargetServers s;
  19051. Client cli("127.0.0.1", s.target_port());
  19052. cli.set_proxy("127.0.0.1", s.proxy_port());
  19053. cli.set_no_proxy({" 127.0.0.0/8 "});
  19054. auto res = cli.Get("/");
  19055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19056. EXPECT_EQ(0, s.proxy_hits());
  19057. EXPECT_EQ(1, s.target_hits());
  19058. }
  19059. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19060. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19061. // go direct and must NOT carry Proxy-Authorization.
  19062. std::atomic<int> proxy_hits{0};
  19063. std::atomic<int> target_hits{0};
  19064. std::atomic<bool> target_saw_authz{false};
  19065. no_proxy_test::ScopedServer proxy_mock, target;
  19066. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19067. proxy_hits++;
  19068. res.status = 302;
  19069. res.set_header("Location", "http://127.0.0.1:" +
  19070. std::to_string(target.port()) + "/landed");
  19071. });
  19072. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19073. target_hits++;
  19074. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19075. res.set_content("direct", "text/plain");
  19076. });
  19077. proxy_mock.listen();
  19078. target.listen();
  19079. Client cli("public.example", target.port());
  19080. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19081. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19082. cli.set_proxy_basic_auth("u", "p");
  19083. cli.set_no_proxy({"127.0.0.1"});
  19084. cli.set_follow_location(true);
  19085. auto res = cli.Get("/redir");
  19086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19087. EXPECT_GE(proxy_hits.load(), 1);
  19088. EXPECT_GE(target_hits.load(), 1);
  19089. EXPECT_FALSE(target_saw_authz.load());
  19090. }
  19091. #ifdef CPPHTTPLIB_SSL_ENABLED
  19092. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19093. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19094. // proxy creds would be sent to the (possibly hostile) origin.
  19095. std::atomic<int> target_hits{0};
  19096. std::atomic<bool> target_saw_proxy_authz{false};
  19097. no_proxy_test::ScopedServer target;
  19098. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19099. target_hits++;
  19100. if (req.has_header("Proxy-Authorization")) {
  19101. target_saw_proxy_authz = true;
  19102. }
  19103. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19104. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19105. "nonce=\"abc\", algorithm=MD5");
  19106. });
  19107. target.listen();
  19108. // The proxy address is set to the target's port: the bypass MUST kick in;
  19109. // if it doesn't, the test still routes "via proxy" to the same server and
  19110. // the Proxy-Authorization assertion below catches the leak.
  19111. Client cli("evil.example", target.port());
  19112. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19113. cli.set_proxy("127.0.0.1", target.port());
  19114. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19115. cli.set_no_proxy({"evil.example"});
  19116. auto res = cli.Get("/x");
  19117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19118. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19119. EXPECT_EQ(1, target_hits.load());
  19120. EXPECT_FALSE(target_saw_proxy_authz.load());
  19121. }
  19122. #endif
  19123. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19124. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19125. std::atomic<int> proxy_hits{0};
  19126. std::atomic<int> bypass_hits{0};
  19127. std::atomic<bool> proxy_saw_c_url{false};
  19128. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19129. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19130. proxy_hits++;
  19131. if (req.path.find("/start") != std::string::npos) {
  19132. res.status = 302;
  19133. res.set_header("Location", "http://127.0.0.1:" +
  19134. std::to_string(bypass_server.port()) +
  19135. "/middle");
  19136. return;
  19137. }
  19138. if (req.path.find("/end") != std::string::npos) {
  19139. proxy_saw_c_url = true;
  19140. res.set_content("c-via-proxy", "text/plain");
  19141. return;
  19142. }
  19143. res.set_content("unexpected", "text/plain");
  19144. });
  19145. // public.example's "advertised" port is arbitrary (the request never lands
  19146. // there — it goes through the proxy), but use a dynamic value to stay
  19147. // friendly with sharded parallel runs.
  19148. int public_port = bypass_server.port();
  19149. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19150. bypass_hits++;
  19151. res.status = 302;
  19152. res.set_header("Location", "http://public.example:" +
  19153. std::to_string(public_port) + "/end");
  19154. });
  19155. proxy_mock.listen();
  19156. bypass_server.listen();
  19157. Client cli("public.example", public_port);
  19158. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19159. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19160. cli.set_no_proxy({"127.0.0.1"});
  19161. cli.set_follow_location(true);
  19162. auto res = cli.Get("/start");
  19163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19164. EXPECT_EQ(StatusCode::OK_200, res->status);
  19165. EXPECT_EQ("c-via-proxy", res->body);
  19166. EXPECT_GE(proxy_hits.load(), 2);
  19167. EXPECT_GE(bypass_hits.load(), 1);
  19168. EXPECT_TRUE(proxy_saw_c_url.load());
  19169. }
  19170. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19171. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19172. // request reconnects to the correct endpoint.
  19173. std::atomic<int> proxy_hits{0};
  19174. std::atomic<int> target_hits{0};
  19175. no_proxy_test::ScopedServer proxy_mock, target;
  19176. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19177. proxy_hits++;
  19178. res.set_content("via-proxy", "text/plain");
  19179. });
  19180. target.svr().Get(".*", [&](const Request &, Response &res) {
  19181. target_hits++;
  19182. res.set_content("direct", "text/plain");
  19183. });
  19184. proxy_mock.listen();
  19185. target.listen();
  19186. Client cli("public.example", target.port());
  19187. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19188. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19189. cli.set_keep_alive(true);
  19190. auto res1 = cli.Get("/a");
  19191. ASSERT_TRUE(res1);
  19192. EXPECT_EQ("via-proxy", res1->body);
  19193. EXPECT_EQ(1, proxy_hits.load());
  19194. EXPECT_EQ(0, target_hits.load());
  19195. cli.set_no_proxy({"public.example"});
  19196. auto res2 = cli.Get("/b");
  19197. ASSERT_TRUE(res2);
  19198. EXPECT_EQ("direct", res2->body);
  19199. EXPECT_EQ(1, proxy_hits.load());
  19200. EXPECT_EQ(1, target_hits.load());
  19201. }
  19202. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19203. namespace proxy_tunnel_test {
  19204. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19205. class ScopedSSLServer {
  19206. public:
  19207. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19208. port_ = svr_.bind_to_any_port("127.0.0.1");
  19209. }
  19210. ~ScopedSSLServer() {
  19211. svr_.stop();
  19212. if (th_.joinable()) { th_.join(); }
  19213. }
  19214. SSLServer &svr() { return svr_; }
  19215. int port() const { return port_; }
  19216. void listen() {
  19217. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19218. svr_.wait_until_ready();
  19219. }
  19220. private:
  19221. SSLServer svr_;
  19222. std::thread th_;
  19223. int port_ = 0;
  19224. };
  19225. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19226. class ScopedConnectProxy {
  19227. public:
  19228. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19229. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19230. if (listen_fd_ < 0) { return; }
  19231. int yes = 1;
  19232. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19233. sockaddr_in a{};
  19234. a.sin_family = AF_INET;
  19235. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19236. a.sin_port = 0;
  19237. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19238. return;
  19239. }
  19240. socklen_t alen = sizeof(a);
  19241. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19242. 0) {
  19243. return;
  19244. }
  19245. port_ = ntohs(a.sin_port);
  19246. if (::listen(listen_fd_, 1) != 0) { return; }
  19247. th_ = std::thread([this] { run(); });
  19248. }
  19249. ~ScopedConnectProxy() {
  19250. stop_ = true;
  19251. if (listen_fd_ >= 0) {
  19252. ::shutdown(listen_fd_, SHUT_RDWR);
  19253. ::close(listen_fd_);
  19254. }
  19255. if (th_.joinable()) { th_.join(); }
  19256. }
  19257. int port() const { return port_; }
  19258. int connect_hits() const { return connect_hits_.load(); }
  19259. private:
  19260. void run() {
  19261. while (!stop_.load()) {
  19262. fd_set rfds;
  19263. FD_ZERO(&rfds);
  19264. FD_SET(listen_fd_, &rfds);
  19265. timeval tv{0, 100 * 1000};
  19266. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19267. if (sel <= 0) { continue; }
  19268. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19269. if (client_fd < 0) { continue; }
  19270. std::string req;
  19271. char buf[2048];
  19272. while (req.find("\r\n\r\n") == std::string::npos) {
  19273. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19274. if (n <= 0) { break; }
  19275. req.append(buf, static_cast<size_t>(n));
  19276. }
  19277. if (req.compare(0, 7, "CONNECT") != 0) {
  19278. ::close(client_fd);
  19279. continue;
  19280. }
  19281. connect_hits_++;
  19282. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19283. ::send(client_fd, ok, std::strlen(ok), 0);
  19284. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19285. sockaddr_in o{};
  19286. o.sin_family = AF_INET;
  19287. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19288. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19289. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19290. 0) {
  19291. ::close(client_fd);
  19292. ::close(origin_fd);
  19293. continue;
  19294. }
  19295. auto forward = [](int from, int to) {
  19296. char b[8192];
  19297. for (;;) {
  19298. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19299. if (n <= 0) { break; }
  19300. ssize_t off = 0;
  19301. while (off < n) {
  19302. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19303. if (s <= 0) {
  19304. off = n;
  19305. break;
  19306. }
  19307. off += s;
  19308. }
  19309. }
  19310. ::shutdown(to, SHUT_WR);
  19311. };
  19312. std::thread t1([&] { forward(client_fd, origin_fd); });
  19313. std::thread t2([&] { forward(origin_fd, client_fd); });
  19314. t1.join();
  19315. t2.join();
  19316. ::close(client_fd);
  19317. ::close(origin_fd);
  19318. }
  19319. }
  19320. int forward_port_ = -1;
  19321. int listen_fd_ = -1;
  19322. int port_ = 0;
  19323. std::thread th_;
  19324. std::atomic<bool> stop_{false};
  19325. std::atomic<int> connect_hits_{0};
  19326. };
  19327. } // namespace proxy_tunnel_test
  19328. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19329. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19330. // retry; otherwise proxy creds would be sent to the origin.
  19331. std::atomic<int> origin_hits{0};
  19332. std::atomic<bool> origin_saw_proxy_authz{false};
  19333. proxy_tunnel_test::ScopedSSLServer origin;
  19334. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19335. origin_hits++;
  19336. if (req.has_header("Proxy-Authorization")) {
  19337. origin_saw_proxy_authz = true;
  19338. }
  19339. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19340. res.set_header("Proxy-Authenticate",
  19341. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19342. "algorithm=MD5");
  19343. });
  19344. origin.listen();
  19345. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19346. ASSERT_NE(0, proxy.port());
  19347. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19348. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19349. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19350. // and answer with its own status, making this test flaky.
  19351. SSLClient cli("127.0.0.1", origin.port());
  19352. cli.enable_server_certificate_verification(false);
  19353. cli.set_proxy("127.0.0.1", proxy.port());
  19354. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19355. auto res = cli.Get("/x");
  19356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19357. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19358. EXPECT_EQ(1, origin_hits.load());
  19359. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19360. EXPECT_EQ(1, proxy.connect_hits());
  19361. }
  19362. #endif