1
0

test.cc 855 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. #endif
  2715. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2716. auto host = "google.com";
  2717. auto another_host = "example.com";
  2718. auto wrong_ip = "0.0.0.0";
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. SSLClient cli(host);
  2721. #else
  2722. Client cli(host);
  2723. #endif
  2724. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2725. auto res = cli.Get("/");
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2728. }
  2729. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2730. auto host = "google.com";
  2731. auto wrong_ip = "0.0.0.0";
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. SSLClient cli(host);
  2734. #else
  2735. Client cli(host);
  2736. #endif
  2737. cli.set_hostname_addr_map({{host, wrong_ip}});
  2738. auto res = cli.Get("/");
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Connection, res.error());
  2741. }
  2742. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2743. // A mapped value that is not an IP literal must be resolved. "localhost"
  2744. // resolves from the hosts file, so this test needs no external DNS.
  2745. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2746. auto host = "target.invalid";
  2747. Server svr;
  2748. std::string received_host;
  2749. svr.Get("/hi", [&](const Request &req, Response &res) {
  2750. received_host = req.get_header_value("Host");
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto port = svr.bind_to_any_port(HOST);
  2754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(host, port);
  2762. cli.set_hostname_addr_map({{host, HOST}});
  2763. auto res = cli.Get("/hi");
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. // The mapping only redirects the connection; the identity stays host_.
  2767. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2768. }
  2769. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2770. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2771. auto host = "target.invalid";
  2772. Server svr;
  2773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto port = svr.bind_to_any_port("127.0.0.1");
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(host, port);
  2785. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2786. auto res = cli.Get("/hi");
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::OK_200, res->status);
  2789. }
  2790. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2791. // An empty mapped value must leave host_ as the connection target. Without
  2792. // that guard the empty value would become the host argument, getaddrinfo
  2793. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2794. // loopback - silently connecting somewhere the caller never asked for.
  2795. // The server listens on loopback, so such a fallback would succeed and is
  2796. // therefore observable as a failure of this test.
  2797. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2798. Server svr;
  2799. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto port = svr.bind_to_any_port(HOST);
  2803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(blackhole, port);
  2811. cli.set_hostname_addr_map({{blackhole, ""}});
  2812. cli.set_connection_timeout(1);
  2813. auto res = cli.Get("/hi");
  2814. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2815. }
  2816. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto path = std::string{"/absolute-redirect/3"};
  2819. #ifdef CPPHTTPLIB_SSL_ENABLED
  2820. SSLClient cli(host);
  2821. #else
  2822. Client cli(host);
  2823. #endif
  2824. cli.set_follow_location(true);
  2825. auto res = cli.Get(path);
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. }
  2829. TEST(RedirectTest, Redirect_Online) {
  2830. auto host = "httpbingo.org";
  2831. auto path = std::string{"/redirect/3"};
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. SSLClient cli(host);
  2834. #else
  2835. Client cli(host);
  2836. #endif
  2837. cli.set_follow_location(true);
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. }
  2842. TEST(RelativeRedirectTest, Redirect_Online) {
  2843. auto host = "httpbingo.org";
  2844. auto path = std::string{"/relative-redirect/3"};
  2845. #ifdef CPPHTTPLIB_SSL_ENABLED
  2846. SSLClient cli(host);
  2847. #else
  2848. Client cli(host);
  2849. #endif
  2850. cli.set_follow_location(true);
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(TooManyRedirectTest, Redirect_Online) {
  2856. auto host = "httpbingo.org";
  2857. auto path = std::string{"/redirect/21"};
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. SSLClient cli(host);
  2860. #else
  2861. Client cli(host);
  2862. #endif
  2863. cli.set_follow_location(true);
  2864. auto res = cli.Get(path);
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2867. }
  2868. #ifdef CPPHTTPLIB_SSL_ENABLED
  2869. TEST(YahooRedirectTest, Redirect_Online) {
  2870. Client cli("yahoo.com");
  2871. auto res = cli.Get("/");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2874. cli.set_follow_location(true);
  2875. res = cli.Get("/");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2879. }
  2880. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2881. #define REDIR_HOST "httpbingo.org"
  2882. #define REDIR_PATH "/redirect-to"
  2883. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2884. SSLClient cli(REDIR_HOST);
  2885. cli.set_follow_location(true);
  2886. auto res =
  2887. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. params.emplace("status_code", "302");
  2897. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. }
  2901. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2902. SSLClient cli(REDIR_HOST);
  2903. cli.set_follow_location(true);
  2904. Params params;
  2905. params.emplace("url", "http://example.com");
  2906. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(UrlWithSpace, Redirect_Online) {
  2911. SSLClient cli("edge.forgecdn.net");
  2912. cli.set_follow_location(true);
  2913. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2917. }
  2918. #endif
  2919. #if !defined(_WIN32) && !defined(_WIN64)
  2920. TEST(ReceiveSignals, Signal) {
  2921. auto setupSignalHandlers = []() {
  2922. struct sigaction act;
  2923. sigemptyset(&act.sa_mask);
  2924. act.sa_flags = SA_SIGINFO;
  2925. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2926. switch (sig) {
  2927. case SIGINT:
  2928. default: break;
  2929. }
  2930. };
  2931. ::sigaction(SIGINT, &act, nullptr);
  2932. };
  2933. Server svr;
  2934. int port = 0;
  2935. auto thread = std::thread([&]() {
  2936. setupSignalHandlers();
  2937. port = svr.bind_to_any_port(HOST);
  2938. svr.listen_after_bind();
  2939. });
  2940. auto se = detail::scope_exit([&] {
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. ASSERT_TRUE(svr.is_running());
  2947. pthread_kill(thread.native_handle(), SIGINT);
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2949. ASSERT_TRUE(svr.is_running());
  2950. }
  2951. #endif
  2952. TEST(RedirectToDifferentPort, Redirect) {
  2953. Server svr1;
  2954. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. int svr1_port = 0;
  2958. auto thread1 = std::thread([&]() {
  2959. svr1_port = svr1.bind_to_any_port(HOST);
  2960. svr1.listen_after_bind();
  2961. });
  2962. Server svr2;
  2963. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2964. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2965. });
  2966. int svr2_port = 0;
  2967. auto thread2 = std::thread([&]() {
  2968. svr2_port = svr2.bind_to_any_port(HOST);
  2969. svr2.listen_after_bind();
  2970. });
  2971. auto se = detail::scope_exit([&] {
  2972. svr2.stop();
  2973. thread2.join();
  2974. svr1.stop();
  2975. thread1.join();
  2976. ASSERT_FALSE(svr2.is_running());
  2977. ASSERT_FALSE(svr1.is_running());
  2978. });
  2979. svr1.wait_until_ready();
  2980. svr2.wait_until_ready();
  2981. Client cli("localhost", svr2_port);
  2982. cli.set_follow_location(true);
  2983. auto res = cli.Get("/2");
  2984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2985. EXPECT_EQ(StatusCode::OK_200, res->status);
  2986. EXPECT_EQ("Hello World!", res->body);
  2987. }
  2988. static void
  2989. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2990. Server svr1;
  2991. std::string captured_authorization;
  2992. svr1.Get("/target", [&](const Request &req, Response &res) {
  2993. captured_authorization = req.get_header_value("Authorization");
  2994. res.set_content("OK", "text/plain");
  2995. });
  2996. int svr1_port = 0;
  2997. auto thread1 = std::thread([&]() {
  2998. svr1_port = svr1.bind_to_any_port(HOST);
  2999. svr1.listen_after_bind();
  3000. });
  3001. Server svr2;
  3002. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3003. res.set_redirect(
  3004. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3005. });
  3006. int svr2_port = 0;
  3007. auto thread2 = std::thread([&]() {
  3008. svr2_port = svr2.bind_to_any_port(HOST);
  3009. svr2.listen_after_bind();
  3010. });
  3011. auto se = detail::scope_exit([&] {
  3012. svr2.stop();
  3013. thread2.join();
  3014. svr1.stop();
  3015. thread1.join();
  3016. ASSERT_FALSE(svr2.is_running());
  3017. ASSERT_FALSE(svr1.is_running());
  3018. });
  3019. svr1.wait_until_ready();
  3020. svr2.wait_until_ready();
  3021. Client cli("localhost", svr2_port);
  3022. cli.set_follow_location(true);
  3023. set_auth(cli);
  3024. auto res = cli.Get("/redir");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::OK_200, res->status);
  3027. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3028. EXPECT_TRUE(captured_authorization.empty());
  3029. }
  3030. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3031. TestDoNotForwardCredentialsOnRedirect(
  3032. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3033. }
  3034. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3035. TestDoNotForwardCredentialsOnRedirect(
  3036. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3037. }
  3038. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3039. Server svr1;
  3040. std::string captured_cookie;
  3041. bool target_hit = false;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_cookie = req.get_header_value("Cookie");
  3044. target_hit = true;
  3045. res.set_content("OK", "text/plain");
  3046. });
  3047. int svr1_port = 0;
  3048. auto thread1 = std::thread([&]() {
  3049. svr1_port = svr1.bind_to_any_port(HOST);
  3050. svr1.listen_after_bind();
  3051. });
  3052. Server svr2;
  3053. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3054. res.set_redirect(
  3055. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3056. });
  3057. int svr2_port = 0;
  3058. auto thread2 = std::thread([&]() {
  3059. svr2_port = svr2.bind_to_any_port(HOST);
  3060. svr2.listen_after_bind();
  3061. });
  3062. auto se = detail::scope_exit([&] {
  3063. svr2.stop();
  3064. thread2.join();
  3065. svr1.stop();
  3066. thread1.join();
  3067. ASSERT_FALSE(svr2.is_running());
  3068. ASSERT_FALSE(svr1.is_running());
  3069. });
  3070. svr1.wait_until_ready();
  3071. svr2.wait_until_ready();
  3072. Client cli("localhost", svr2_port);
  3073. cli.set_follow_location(true);
  3074. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3075. auto res = cli.Get("/redir", headers);
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_TRUE(target_hit);
  3079. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3080. EXPECT_TRUE(captured_cookie.empty());
  3081. }
  3082. TEST(RedirectToSamePort, ForwardCookie) {
  3083. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3084. // header so that ordinary session flows keep working.
  3085. Server svr;
  3086. std::string captured_cookie;
  3087. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3088. res.set_redirect("/target", 302);
  3089. });
  3090. svr.Get("/target", [&](const Request &req, Response &res) {
  3091. captured_cookie = req.get_header_value("Cookie");
  3092. res.set_content("OK", "text/plain");
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_follow_location(true);
  3104. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3105. auto res = cli.Get("/redir", headers);
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3109. }
  3110. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3111. Server svr;
  3112. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3113. // Port number that overflows int — should not crash
  3114. res.set_redirect("http://localhost:99999999999999999999/target");
  3115. });
  3116. auto port = svr.bind_to_any_port(HOST);
  3117. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3118. auto se = detail::scope_exit([&] {
  3119. svr.stop();
  3120. thread.join();
  3121. ASSERT_FALSE(svr.is_running());
  3122. });
  3123. svr.wait_until_ready();
  3124. Client cli(HOST, port);
  3125. cli.set_follow_location(true);
  3126. auto res = cli.Get("/redir");
  3127. // Should fail gracefully, not crash (no valid response due to bad port)
  3128. EXPECT_FALSE(res);
  3129. }
  3130. TEST(RedirectFromPageWithContent, Redirect) {
  3131. Server svr;
  3132. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3133. res.set_content("___", "text/plain");
  3134. res.set_redirect("/2");
  3135. });
  3136. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3137. res.set_content("Hello World!", "text/plain");
  3138. });
  3139. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3140. auto se = detail::scope_exit([&] {
  3141. svr.stop();
  3142. th.join();
  3143. ASSERT_FALSE(svr.is_running());
  3144. });
  3145. svr.wait_until_ready();
  3146. {
  3147. Client cli("localhost", PORT);
  3148. cli.set_follow_location(true);
  3149. std::string body;
  3150. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3151. body.append(data, data_length);
  3152. return true;
  3153. });
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("Hello World!", body);
  3157. }
  3158. {
  3159. Client cli("localhost", PORT);
  3160. std::string body;
  3161. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3162. body.append(data, data_length);
  3163. return true;
  3164. });
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::Found_302, res->status);
  3167. EXPECT_EQ("___", body);
  3168. }
  3169. }
  3170. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3171. Server svr;
  3172. auto port_str = std::to_string(PORT);
  3173. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3174. auto expected_host = "[::1]:" + port_str;
  3175. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3176. res.set_content("___", "text/plain");
  3177. // res.set_redirect("/2");
  3178. res.set_redirect(redirect_url);
  3179. });
  3180. svr.Get("/2", [&](const Request &req, Response &res) {
  3181. auto host_header = req.headers.find("Host");
  3182. ASSERT_TRUE(host_header != req.headers.end());
  3183. EXPECT_EQ(expected_host, host_header->second);
  3184. res.set_content("Hello World!", "text/plain");
  3185. });
  3186. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3187. auto se = detail::scope_exit([&] {
  3188. svr.stop();
  3189. th.join();
  3190. ASSERT_FALSE(svr.is_running());
  3191. });
  3192. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3193. // actually starts anything, so the condition !svr.is_running() will
  3194. // always remain true, and the loop never stops.
  3195. // This basically counts how many milliseconds have passed since the
  3196. // call to svr.listen(), and if after 5 seconds nothing started yet
  3197. // aborts the test.
  3198. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3199. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3200. ASSERT_LT(milliseconds, 5000U);
  3201. }
  3202. {
  3203. Client cli("::1", PORT);
  3204. cli.set_follow_location(true);
  3205. std::string body;
  3206. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3207. body.append(data, data_length);
  3208. return true;
  3209. });
  3210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("Hello World!", body);
  3213. }
  3214. {
  3215. Client cli("::1", PORT);
  3216. std::string body;
  3217. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Found_302, res->status);
  3223. EXPECT_EQ("___", body);
  3224. }
  3225. }
  3226. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3227. Server svr;
  3228. svr.Get("/foo", [](const Request &req, Response &res) {
  3229. auto a = req.params.find("a");
  3230. if (a != req.params.end()) {
  3231. res.set_content((*a).second, "text/plain");
  3232. res.status = StatusCode::OK_200;
  3233. } else {
  3234. res.status = StatusCode::BadRequest_400;
  3235. }
  3236. });
  3237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. {
  3245. Client cli(HOST, PORT);
  3246. cli.set_path_encode(false);
  3247. auto res = cli.Get("/foo?a=explicitly+encoded");
  3248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. // This expects it back with a space, as the `+` won't have been
  3251. // url-encoded, and server-side the params get decoded turning `+`
  3252. // into spaces.
  3253. EXPECT_EQ("explicitly encoded", res->body);
  3254. }
  3255. }
  3256. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3257. // When path encoding is disabled the client must transmit the supplied
  3258. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3259. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3260. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3261. // than a space (0x20). Assert on the raw wire target to catch this.
  3262. Server svr;
  3263. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3264. svr.Get("/foo", [&](const Request &req, Response &res) {
  3265. EXPECT_EQ(expected_target, req.target);
  3266. res.status = StatusCode::OK_200;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. {
  3276. Client cli(HOST, PORT);
  3277. cli.set_path_encode(false);
  3278. auto res = cli.Get(expected_target.c_str());
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. }
  3283. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3284. // `open_stream()` used to skip the path encoding that the buffered send
  3285. // path applies, so the same `path` produced different bytes in the request
  3286. // line depending on which API was used. Assert the two agree.
  3287. Server svr;
  3288. std::string target;
  3289. svr.Get(".*", [&](const Request &req, Response &res) {
  3290. target = req.target;
  3291. res.status = StatusCode::OK_200;
  3292. });
  3293. auto port = svr.bind_to_any_port(HOST);
  3294. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3295. auto se = detail::scope_exit([&] {
  3296. svr.stop();
  3297. thread.join();
  3298. ASSERT_FALSE(svr.is_running());
  3299. });
  3300. svr.wait_until_ready();
  3301. struct {
  3302. const char *path;
  3303. const char *expected;
  3304. } cases[] = {
  3305. {"/a b?x=1", "/a%20b?x=1"},
  3306. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3307. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3308. };
  3309. for (const auto &c : cases) {
  3310. Client cli(HOST, port);
  3311. target.clear();
  3312. auto res = cli.Get(c.path);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3315. auto buffered_target = target;
  3316. target.clear();
  3317. auto handle = cli.open_stream("GET", c.path);
  3318. EXPECT_TRUE(handle.is_valid())
  3319. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3320. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3321. }
  3322. }
  3323. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3324. // The `set_path_encode(false)` contract — transmit the supplied target
  3325. // verbatim — must hold for the streaming API too.
  3326. Server svr;
  3327. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3328. std::string target;
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. target = req.target;
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto port = svr.bind_to_any_port(HOST);
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, port);
  3343. cli.set_path_encode(false);
  3344. auto handle = cli.open_stream("GET", expected_target);
  3345. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3346. EXPECT_EQ(expected_target, target);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3350. // With path encoding enabled a CR/LF in the target is percent-encoded
  3351. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3352. // write_request_line still backstops `set_path_encode(false)`, which is
  3353. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3354. Server svr;
  3355. // Captured before routing: the decoded path contains a newline, which a
  3356. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3357. std::string target;
  3358. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3359. target = req.target;
  3360. res.status = StatusCode::OK_200;
  3361. return Server::HandlerResponse::Handled;
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. thread.join();
  3368. ASSERT_FALSE(svr.is_running());
  3369. });
  3370. svr.wait_until_ready();
  3371. {
  3372. Client cli(HOST, port);
  3373. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3374. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3375. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3376. }
  3377. }
  3378. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3379. // Every control character is percent-encoded, not just CR/LF, so the target
  3380. // passes the request-target check in write_request_line.
  3381. Server svr;
  3382. std::string target;
  3383. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3384. target = req.target;
  3385. res.status = StatusCode::OK_200;
  3386. return Server::HandlerResponse::Handled;
  3387. });
  3388. auto port = svr.bind_to_any_port(HOST);
  3389. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3390. auto se = detail::scope_exit([&] {
  3391. svr.stop();
  3392. thread.join();
  3393. ASSERT_FALSE(svr.is_running());
  3394. });
  3395. svr.wait_until_ready();
  3396. {
  3397. Client cli(HOST, port);
  3398. auto res = cli.Get("/a\tb\x1b\x7f");
  3399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3400. EXPECT_EQ("/a%09b%1B%7F", target);
  3401. }
  3402. }
  3403. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3404. // Nothing may reach the wire: a raw CR/LF target would split the request
  3405. // line and inject headers.
  3406. Server svr;
  3407. // Pre-routing so that "not called" means nothing reached the server at all,
  3408. // rather than merely failing to match a handler pattern.
  3409. auto handler_called = false;
  3410. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3411. handler_called = true;
  3412. res.status = StatusCode::OK_200;
  3413. return Server::HandlerResponse::Handled;
  3414. });
  3415. auto port = svr.bind_to_any_port(HOST);
  3416. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. {
  3424. Client cli(HOST, port);
  3425. cli.set_path_encode(false);
  3426. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3427. EXPECT_FALSE(handle.is_valid());
  3428. EXPECT_EQ(Error::Write, handle.error);
  3429. EXPECT_FALSE(handler_called);
  3430. }
  3431. }
  3432. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3433. // Which of the two branches runs is decided by whether the query component
  3434. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3435. // an empty query and must still fall back to building one from
  3436. // `req.params`, while a non-empty query must win over `req.params`.
  3437. Server svr;
  3438. std::string target;
  3439. svr.Get("/foo", [&](const Request &req, Response &res) {
  3440. target = req.target;
  3441. res.status = StatusCode::OK_200;
  3442. });
  3443. auto port = svr.bind_to_any_port(HOST);
  3444. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3445. auto se = detail::scope_exit([&] {
  3446. svr.stop();
  3447. thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. });
  3450. svr.wait_until_ready();
  3451. {
  3452. // Trailing `?` -> empty query component -> `req.params` is used.
  3453. Client cli(HOST, port);
  3454. Request req;
  3455. req.method = "GET";
  3456. req.path = "/foo?";
  3457. req.params.emplace("a", "1");
  3458. target.clear();
  3459. auto res = cli.send(req);
  3460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3461. EXPECT_EQ("/foo?a=1", target);
  3462. }
  3463. {
  3464. // Non-empty query in `req.path` -> `req.params` is not appended.
  3465. Client cli(HOST, port);
  3466. Request req;
  3467. req.method = "GET";
  3468. req.path = "/foo?b=2";
  3469. req.params.emplace("a", "1");
  3470. target.clear();
  3471. auto res = cli.send(req);
  3472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3473. EXPECT_EQ("/foo?b=2", target);
  3474. }
  3475. }
  3476. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3477. Server svr;
  3478. svr.Get("/", [](const Request &req, Response &) {
  3479. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3480. });
  3481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, PORT);
  3490. cli.set_path_encode(false);
  3491. auto res = cli.Get("/?something=%0A");
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. }
  3495. }
  3496. TEST(BindServerTest, BindDualStack) {
  3497. Server svr;
  3498. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3499. res.set_content("Hello World!", "text/plain");
  3500. });
  3501. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3502. auto se = detail::scope_exit([&] {
  3503. svr.stop();
  3504. thread.join();
  3505. ASSERT_FALSE(svr.is_running());
  3506. });
  3507. svr.wait_until_ready();
  3508. {
  3509. Client cli("127.0.0.1", PORT);
  3510. auto res = cli.Get("/1");
  3511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("Hello World!", res->body);
  3514. }
  3515. {
  3516. Client cli("::1", PORT);
  3517. auto res = cli.Get("/1");
  3518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("Hello World!", res->body);
  3521. }
  3522. }
  3523. TEST(BindServerTest, BindAndListenSeparately) {
  3524. Server svr;
  3525. int port = svr.bind_to_any_port("0.0.0.0");
  3526. ASSERT_TRUE(svr.is_valid());
  3527. ASSERT_TRUE(port > 0);
  3528. svr.stop();
  3529. }
  3530. // Reports whether anything is still listening on a loopback port. A plain
  3531. // connect() is used instead of a Client request because a socket left bound by
  3532. // mistake accepts the connection into its backlog and never answers, which
  3533. // would hang the test instead of failing it.
  3534. static bool is_loopback_port_accepting(int port) {
  3535. sockaddr_in addr{};
  3536. addr.sin_family = AF_INET;
  3537. addr.sin_port = htons(static_cast<uint16_t>(port));
  3538. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3539. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3540. EXPECT_NE(sock, INVALID_SOCKET);
  3541. if (sock == INVALID_SOCKET) { return false; }
  3542. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3543. static_cast<socklen_t>(sizeof(addr)));
  3544. detail::close_socket(sock);
  3545. return ret == 0;
  3546. }
  3547. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3548. Server svr;
  3549. auto port = svr.bind_to_any_port("127.0.0.1");
  3550. ASSERT_TRUE(port > 0);
  3551. svr.stop();
  3552. // bind_to_any_port() already called listen(2), so until stop() closed the
  3553. // descriptor the port kept accepting connections into the backlog. ASSERT
  3554. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3555. // below blocks forever in the accept loop.
  3556. ASSERT_FALSE(is_loopback_port_accepting(port));
  3557. // Nothing is left to accept on, so listen_after_bind() must report failure
  3558. // instead of returning success without ever serving.
  3559. EXPECT_FALSE(svr.listen_after_bind());
  3560. // The failed listen marks the server decommissioned, so a waiter returns
  3561. // instead of spinning forever.
  3562. svr.wait_until_ready();
  3563. }
  3564. #ifdef CPPHTTPLIB_SSL_ENABLED
  3565. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3567. CLIENT_CA_CERT_DIR);
  3568. int port = svr.bind_to_any_port("0.0.0.0");
  3569. ASSERT_TRUE(svr.is_valid());
  3570. ASSERT_TRUE(port > 0);
  3571. svr.stop();
  3572. }
  3573. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3574. // or a rejected CustomRoute() registration would not stop the server binding.
  3575. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3577. CLIENT_CA_CERT_DIR);
  3578. ASSERT_TRUE(svr.is_valid());
  3579. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3580. EXPECT_FALSE(svr.is_valid());
  3581. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3582. }
  3583. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3584. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3585. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3586. int port = svr.bind_to_any_port("0.0.0.0");
  3587. ASSERT_TRUE(svr.is_valid());
  3588. ASSERT_TRUE(port > 0);
  3589. svr.stop();
  3590. }
  3591. TEST(BindServerTest, UpdateCertsPem) {
  3592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3593. int port = svr.bind_to_any_port("0.0.0.0");
  3594. ASSERT_TRUE(svr.is_valid());
  3595. ASSERT_TRUE(port > 0);
  3596. // Read PEM files
  3597. std::string cert_pem, key_pem, ca_pem;
  3598. read_file(SERVER_CERT_FILE, cert_pem);
  3599. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3600. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3601. // Update server certificates using PEM API
  3602. ASSERT_TRUE(
  3603. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3604. ASSERT_TRUE(svr.is_valid());
  3605. svr.stop();
  3606. }
  3607. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3608. // Start server with client CA (enables client auth)
  3609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3610. ASSERT_TRUE(svr.is_valid());
  3611. bool handler_called = false;
  3612. svr.Get("/test", [&](const Request &req, Response &res) {
  3613. handler_called = true;
  3614. // Verify client certificate is present
  3615. auto cert = req.peer_cert();
  3616. EXPECT_TRUE(static_cast<bool>(cert));
  3617. res.set_content("ok", "text/plain");
  3618. });
  3619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. t.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. // Read PEM files
  3627. std::string cert_pem, key_pem, ca_pem;
  3628. read_file(SERVER_CERT_FILE, cert_pem);
  3629. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3630. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3631. // Update server certificates and client CA using PEM API while server running
  3632. ASSERT_TRUE(
  3633. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3634. // Connect with client certificate
  3635. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3636. cli.enable_server_certificate_verification(false);
  3637. cli.set_connection_timeout(30);
  3638. auto res = cli.Get("/test");
  3639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_TRUE(handler_called);
  3642. EXPECT_EQ("ok", res->body);
  3643. }
  3644. #endif
  3645. TEST(ErrorHandlerTest, ContentLength) {
  3646. Server svr;
  3647. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3648. res.status = StatusCode::OK_200;
  3649. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3650. "text/html"); // <= Content-Length still 13
  3651. });
  3652. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3653. res.set_content("Hello World!\n", "text/plain");
  3654. res.status = 524;
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3670. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3671. }
  3672. }
  3673. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3674. TEST(ExceptionTest, WithoutExceptionHandler) {
  3675. Server svr;
  3676. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3677. throw std::runtime_error("exception...");
  3678. });
  3679. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3680. throw std::runtime_error("exception\r\n...");
  3681. });
  3682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. listen_thread.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli("localhost", PORT);
  3690. {
  3691. auto res = cli.Get("/exception");
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3695. }
  3696. {
  3697. auto res = cli.Get("/unknown");
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3700. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3701. }
  3702. }
  3703. TEST(ExceptionTest, WithExceptionHandler) {
  3704. Server svr;
  3705. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3706. std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. EXPECT_EQ("abc", std::string(e.what()));
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13 at this point
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. throw std::runtime_error("abc");
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. for (size_t i = 0; i < 10; i++) {
  3729. Client cli(HOST, PORT);
  3730. for (size_t j = 0; j < 100; j++) {
  3731. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3737. }
  3738. cli.set_keep_alive(true);
  3739. for (size_t j = 0; j < 100; j++) {
  3740. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3743. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3744. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3746. }
  3747. }
  3748. }
  3749. TEST(ExceptionTest, AndErrorHandler) {
  3750. Server svr;
  3751. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3752. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3753. });
  3754. svr.set_exception_handler(
  3755. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3756. EXPECT_FALSE(ep == nullptr);
  3757. try {
  3758. std::rethrow_exception(ep);
  3759. } catch (std::exception &e) {
  3760. res.set_content(e.what(), "text/html");
  3761. } catch (...) {}
  3762. res.status = StatusCode::InternalServerError_500;
  3763. });
  3764. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3765. throw std::runtime_error("EXCEPTION");
  3766. });
  3767. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3768. res.set_content("ERROR", "text/html");
  3769. res.status = StatusCode::InternalServerError_500;
  3770. });
  3771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3772. auto se = detail::scope_exit([&] {
  3773. svr.stop();
  3774. thread.join();
  3775. ASSERT_FALSE(svr.is_running());
  3776. });
  3777. svr.wait_until_ready();
  3778. Client cli(HOST, PORT);
  3779. {
  3780. auto res = cli.Get("/exception");
  3781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3782. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3783. EXPECT_EQ("EXCEPTION", res->body);
  3784. }
  3785. {
  3786. auto res = cli.Get("/error");
  3787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3788. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3789. EXPECT_EQ("ERROR", res->body);
  3790. }
  3791. {
  3792. auto res = cli.Get("/invalid");
  3793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3795. EXPECT_EQ("NOT_FOUND", res->body);
  3796. }
  3797. }
  3798. #endif
  3799. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3800. // process_request() wraps only routing() in a try/catch, so an exception from
  3801. // any other user callback used to unwind into the task queue - which does not
  3802. // catch - and terminate the process. Each test below runs the server on a
  3803. // single worker thread: a guard that catches the exception but still loses the
  3804. // thread would otherwise be hidden by a spare worker serving the follow-up
  3805. // request. Note that a regression here aborts the whole test binary rather
  3806. // than failing one test.
  3807. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3808. Server svr;
  3809. svr.new_task_queue = [] { return new ThreadPool(1); };
  3810. std::atomic<int> reported{0};
  3811. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3812. if (err == Error::UserCallbackException) { reported++; }
  3813. });
  3814. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3815. res.set_content_provider(
  3816. 1024, "text/plain",
  3817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3818. sink.write("hello", 5);
  3819. throw std::runtime_error("from the content provider");
  3820. });
  3821. });
  3822. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3823. res.set_content("ok", "text/plain");
  3824. });
  3825. auto port = svr.bind_to_any_port(HOST);
  3826. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3827. auto se = detail::scope_exit([&] {
  3828. svr.stop();
  3829. listen_thread.join();
  3830. ASSERT_FALSE(svr.is_running());
  3831. });
  3832. svr.wait_until_ready();
  3833. {
  3834. Client cli(HOST, port);
  3835. cli.set_read_timeout(5, 0);
  3836. EXPECT_FALSE(cli.Get("/throw"));
  3837. }
  3838. EXPECT_TRUE(svr.is_running());
  3839. EXPECT_EQ(1, reported.load());
  3840. // A request on a fresh connection is still served.
  3841. {
  3842. Client cli(HOST, port);
  3843. auto res = cli.Get("/ok");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("ok", res->body);
  3847. }
  3848. }
  3849. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3850. Server svr;
  3851. svr.new_task_queue = [] { return new ThreadPool(1); };
  3852. std::atomic<bool> should_throw{true};
  3853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3854. res.set_content("hi", "text/plain");
  3855. });
  3856. svr.set_post_routing_handler(
  3857. [&](const Request & /*req*/, Response & /*res*/) {
  3858. if (should_throw) {
  3859. throw std::runtime_error("from the post-routing handler");
  3860. }
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. listen_thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. Client cli(HOST, port);
  3872. cli.set_read_timeout(5, 0);
  3873. EXPECT_FALSE(cli.Get("/hi"));
  3874. }
  3875. EXPECT_TRUE(svr.is_running());
  3876. should_throw = false;
  3877. {
  3878. Client cli(HOST, port);
  3879. auto res = cli.Get("/hi");
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ(StatusCode::OK_200, res->status);
  3882. EXPECT_EQ("hi", res->body);
  3883. }
  3884. }
  3885. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3886. // The guard reports the caught exception through the error logger, which is
  3887. // a user callback too. A logger that throws has to be contained as well, or
  3888. // the process would terminate from inside the catch.
  3889. Server svr;
  3890. svr.new_task_queue = [] { return new ThreadPool(1); };
  3891. std::atomic<int> reported{0};
  3892. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3893. if (err == Error::UserCallbackException) {
  3894. reported++;
  3895. throw std::runtime_error("from the error logger");
  3896. }
  3897. });
  3898. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3899. res.set_content_provider(
  3900. 1024, "text/plain",
  3901. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3902. sink.write("hello", 5);
  3903. throw std::runtime_error("from the content provider");
  3904. });
  3905. });
  3906. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3907. res.set_content("ok", "text/plain");
  3908. });
  3909. auto port = svr.bind_to_any_port(HOST);
  3910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3911. auto se = detail::scope_exit([&] {
  3912. svr.stop();
  3913. listen_thread.join();
  3914. ASSERT_FALSE(svr.is_running());
  3915. });
  3916. svr.wait_until_ready();
  3917. {
  3918. Client cli(HOST, port);
  3919. cli.set_read_timeout(5, 0);
  3920. EXPECT_FALSE(cli.Get("/throw"));
  3921. }
  3922. EXPECT_TRUE(svr.is_running());
  3923. EXPECT_EQ(1, reported.load());
  3924. {
  3925. Client cli(HOST, port);
  3926. auto res = cli.Get("/ok");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. EXPECT_EQ("ok", res->body);
  3930. }
  3931. }
  3932. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3933. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3934. // so the exception unwinds through the ws::WebSocket object on its way to
  3935. // the guard. None of the HTTP cases above cross that.
  3936. Server svr;
  3937. svr.new_task_queue = [] { return new ThreadPool(1); };
  3938. std::atomic<int> reported{0};
  3939. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3940. if (err == Error::UserCallbackException) { reported++; }
  3941. });
  3942. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3943. throw std::runtime_error("from the WebSocket handler");
  3944. });
  3945. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3946. res.set_content("ok", "text/plain");
  3947. });
  3948. auto port = svr.bind_to_any_port(HOST);
  3949. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. listen_thread.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. {
  3957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3958. "/ws");
  3959. auto res = client.connect();
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. // The server dropped the connection instead of dying.
  3962. std::string msg;
  3963. EXPECT_FALSE(client.read(msg));
  3964. client.close();
  3965. }
  3966. EXPECT_TRUE(svr.is_running());
  3967. EXPECT_EQ(1, reported.load());
  3968. {
  3969. Client cli(HOST, port);
  3970. auto res = cli.Get("/ok");
  3971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. EXPECT_EQ("ok", res->body);
  3974. }
  3975. }
  3976. #ifdef CPPHTTPLIB_SSL_ENABLED
  3977. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3978. // SSLServer::process_and_close_socket() is a separate overload with its own
  3979. // guard, so it is exercised on its own.
  3980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3981. ASSERT_TRUE(svr.is_valid());
  3982. svr.new_task_queue = [] { return new ThreadPool(1); };
  3983. std::atomic<int> reported{0};
  3984. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3985. if (err == Error::UserCallbackException) { reported++; }
  3986. });
  3987. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3988. res.set_content_provider(
  3989. 1024, "text/plain",
  3990. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3991. sink.write("hello", 5);
  3992. throw std::runtime_error("from the content provider");
  3993. });
  3994. });
  3995. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3996. res.set_content("ok", "text/plain");
  3997. });
  3998. auto port = svr.bind_to_any_port(HOST);
  3999. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4000. auto se = detail::scope_exit([&] {
  4001. svr.stop();
  4002. listen_thread.join();
  4003. ASSERT_FALSE(svr.is_running());
  4004. });
  4005. svr.wait_until_ready();
  4006. {
  4007. SSLClient cli(HOST, port);
  4008. cli.enable_server_certificate_verification(false);
  4009. cli.set_read_timeout(5, 0);
  4010. EXPECT_FALSE(cli.Get("/throw"));
  4011. }
  4012. EXPECT_TRUE(svr.is_running());
  4013. EXPECT_EQ(1, reported.load());
  4014. {
  4015. SSLClient cli(HOST, port);
  4016. cli.enable_server_certificate_verification(false);
  4017. auto res = cli.Get("/ok");
  4018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("ok", res->body);
  4021. }
  4022. }
  4023. #endif
  4024. #endif
  4025. TEST(NoContentTest, ContentLength) {
  4026. Server svr;
  4027. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4028. res.status = StatusCode::NoContent_204;
  4029. });
  4030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4031. auto se = detail::scope_exit([&] {
  4032. svr.stop();
  4033. thread.join();
  4034. ASSERT_FALSE(svr.is_running());
  4035. });
  4036. svr.wait_until_ready();
  4037. {
  4038. Client cli(HOST, PORT);
  4039. auto res = cli.Get("/hi");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4042. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4043. }
  4044. }
  4045. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4048. ASSERT_TRUE(svr.is_valid());
  4049. #else
  4050. Server svr;
  4051. #endif
  4052. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4053. if (req.path == "/routing_handler") {
  4054. res.set_header("PRE_ROUTING", "on");
  4055. res.set_content("Routing Handler", "text/plain");
  4056. return httplib::Server::HandlerResponse::Handled;
  4057. }
  4058. return httplib::Server::HandlerResponse::Unhandled;
  4059. });
  4060. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4061. res.set_content("Error", "text/html");
  4062. });
  4063. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4064. if (req.path == "/routing_handler") {
  4065. res.set_header("POST_ROUTING", "on");
  4066. }
  4067. });
  4068. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4069. res.set_content("Hello World!\n", "text/plain");
  4070. });
  4071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4072. auto se = detail::scope_exit([&] {
  4073. svr.stop();
  4074. thread.join();
  4075. ASSERT_FALSE(svr.is_running());
  4076. });
  4077. svr.wait_until_ready();
  4078. {
  4079. #ifdef CPPHTTPLIB_SSL_ENABLED
  4080. SSLClient cli(HOST, PORT);
  4081. cli.enable_server_certificate_verification(false);
  4082. #else
  4083. Client cli(HOST, PORT);
  4084. #endif
  4085. auto res = cli.Get("/routing_handler");
  4086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. EXPECT_EQ("Routing Handler", res->body);
  4089. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4090. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4091. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4092. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4093. }
  4094. {
  4095. #ifdef CPPHTTPLIB_SSL_ENABLED
  4096. SSLClient cli(HOST, PORT);
  4097. cli.enable_server_certificate_verification(false);
  4098. #else
  4099. Client cli(HOST, PORT);
  4100. #endif
  4101. auto res = cli.Get("/hi");
  4102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("Hello World!\n", res->body);
  4105. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4106. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4107. }
  4108. {
  4109. #ifdef CPPHTTPLIB_SSL_ENABLED
  4110. SSLClient cli(HOST, PORT);
  4111. cli.enable_server_certificate_verification(false);
  4112. #else
  4113. Client cli(HOST, PORT);
  4114. #endif
  4115. auto res = cli.Get("/aaa");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("Error", res->body);
  4119. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4120. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4121. }
  4122. }
  4123. TEST(RequestHandlerTest, PreRequestHandler) {
  4124. auto route_path = "/user/:user";
  4125. Server svr;
  4126. svr.Get("/hi", [](const Request &, Response &res) {
  4127. res.set_content("hi", "text/plain");
  4128. });
  4129. svr.Get(route_path, [](const Request &req, Response &res) {
  4130. res.set_content(req.path_params.at("user"), "text/plain");
  4131. });
  4132. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4133. if (req.matched_route == route_path) {
  4134. auto user = req.path_params.at("user");
  4135. if (user != "john") {
  4136. res.status = StatusCode::Forbidden_403;
  4137. res.set_content("error", "text/html");
  4138. return Server::HandlerResponse::Handled;
  4139. }
  4140. }
  4141. return Server::HandlerResponse::Unhandled;
  4142. });
  4143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. thread.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. Client cli(HOST, PORT);
  4151. {
  4152. auto res = cli.Get("/hi");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::OK_200, res->status);
  4155. EXPECT_EQ("hi", res->body);
  4156. }
  4157. {
  4158. auto res = cli.Get("/user/john");
  4159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4160. EXPECT_EQ(StatusCode::OK_200, res->status);
  4161. EXPECT_EQ("john", res->body);
  4162. }
  4163. {
  4164. auto res = cli.Get("/user/invalid-user");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4167. EXPECT_EQ("error", res->body);
  4168. }
  4169. }
  4170. // The pre-request handler must run before the request body is read, so a
  4171. // rejected request never forces the server to buffer a (potentially large)
  4172. // body. Here the posted body is larger than the payload limit: if the body
  4173. // were read first the server would answer 413, but because the pre-request
  4174. // handler runs first it answers 403 and the body is never read.
  4175. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4176. Server svr;
  4177. svr.set_payload_max_length(8);
  4178. auto handler_ran = false;
  4179. svr.Post("/reject", [&](const Request &req, Response &res) {
  4180. handler_ran = true;
  4181. res.set_content(req.body, "text/plain");
  4182. });
  4183. svr.Post("/accept", [](const Request &req, Response &res) {
  4184. res.set_content(req.body, "text/plain");
  4185. });
  4186. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4187. if (req.matched_route == "/reject") {
  4188. res.status = StatusCode::Forbidden_403;
  4189. res.set_content("denied", "text/plain");
  4190. return Server::HandlerResponse::Handled;
  4191. }
  4192. return Server::HandlerResponse::Unhandled;
  4193. });
  4194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4195. auto se = detail::scope_exit([&] {
  4196. svr.stop();
  4197. thread.join();
  4198. ASSERT_FALSE(svr.is_running());
  4199. });
  4200. svr.wait_until_ready();
  4201. Client cli(HOST, PORT);
  4202. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4203. // rejects with 403 before the body is read, so 413 is never reached.
  4204. {
  4205. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4208. EXPECT_EQ("denied", res->body);
  4209. EXPECT_FALSE(handler_ran);
  4210. }
  4211. // An approved route still reads the body and enforces the payload limit.
  4212. {
  4213. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4215. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4216. }
  4217. }
  4218. TEST(UserDataTest, BasicOperations) {
  4219. httplib::UserData ud;
  4220. // Initially empty
  4221. EXPECT_FALSE(ud.has("key"));
  4222. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4223. // set and get
  4224. ud.set("key", 42);
  4225. EXPECT_TRUE(ud.has("key"));
  4226. auto *p = ud.get<int>("key");
  4227. ASSERT_NE(nullptr, p);
  4228. EXPECT_EQ(42, *p);
  4229. // Type mismatch → nullptr
  4230. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4231. // Overwrite with different type
  4232. ud.set("key", std::string("hello"));
  4233. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4234. auto *s = ud.get<std::string>("key");
  4235. ASSERT_NE(nullptr, s);
  4236. EXPECT_EQ("hello", *s);
  4237. // erase
  4238. ud.erase("key");
  4239. EXPECT_FALSE(ud.has("key"));
  4240. // clear
  4241. ud.set("a", 1);
  4242. ud.set("b", 2);
  4243. ud.clear();
  4244. EXPECT_FALSE(ud.has("a"));
  4245. EXPECT_FALSE(ud.has("b"));
  4246. }
  4247. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4248. struct AuthCtx {
  4249. std::string user_id;
  4250. };
  4251. Server svr;
  4252. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4253. res.user_data.set("auth", AuthCtx{"alice"});
  4254. return Server::HandlerResponse::Unhandled;
  4255. });
  4256. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4257. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4258. ASSERT_NE(nullptr, ctx);
  4259. res.set_content("Hello " + ctx->user_id, "text/plain");
  4260. });
  4261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. thread.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. Client cli(HOST, PORT);
  4269. auto res = cli.Get("/me");
  4270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4271. EXPECT_EQ(StatusCode::OK_200, res->status);
  4272. EXPECT_EQ("Hello alice", res->body);
  4273. }
  4274. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4275. struct RoleCtx {
  4276. std::string role;
  4277. };
  4278. Server svr;
  4279. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4280. res.user_data.set("role", RoleCtx{"admin"});
  4281. return Server::HandlerResponse::Unhandled;
  4282. });
  4283. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4284. auto *ctx = res.user_data.get<RoleCtx>("role");
  4285. ASSERT_NE(nullptr, ctx);
  4286. res.set_content(ctx->role, "text/plain");
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. Client cli(HOST, PORT);
  4296. auto res = cli.Get("/role");
  4297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("admin", res->body);
  4300. }
  4301. TEST(InvalidFormatTest, StatusCode) {
  4302. Server svr;
  4303. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4304. res.set_content("Hello World!\n", "text/plain");
  4305. res.status = 9999; // Status should be a three-digit code...
  4306. });
  4307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4308. auto se = detail::scope_exit([&] {
  4309. svr.stop();
  4310. thread.join();
  4311. ASSERT_FALSE(svr.is_running());
  4312. });
  4313. svr.wait_until_ready();
  4314. {
  4315. Client cli(HOST, PORT);
  4316. auto res = cli.Get("/hi");
  4317. ASSERT_FALSE(res);
  4318. }
  4319. }
  4320. TEST(URLFragmentTest, WithFragment) {
  4321. Server svr;
  4322. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4323. EXPECT_TRUE(req.target == "/hi");
  4324. });
  4325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4326. auto se = detail::scope_exit([&] {
  4327. svr.stop();
  4328. thread.join();
  4329. ASSERT_FALSE(svr.is_running());
  4330. });
  4331. svr.wait_until_ready();
  4332. {
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4335. EXPECT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. res = cli.Get("/hi%23key1=val1=key2=val2");
  4338. EXPECT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4340. }
  4341. }
  4342. TEST(HeaderWriter, SetHeaderWriter) {
  4343. Server svr;
  4344. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4345. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4346. return detail::write_headers(strm, hdrs);
  4347. });
  4348. svr.Get("/hi", [](const Request &req, Response &res) {
  4349. auto it = req.headers.find("CustomClientHeader");
  4350. EXPECT_TRUE(it != req.headers.end());
  4351. EXPECT_EQ(it->second, "CustomClientValue");
  4352. res.set_content("Hello World!\n", "text/plain");
  4353. });
  4354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. thread.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. {
  4362. Client cli(HOST, PORT);
  4363. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4364. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4365. return detail::write_headers(strm, hdrs);
  4366. });
  4367. auto res = cli.Get("/hi");
  4368. EXPECT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. auto it = res->headers.find("CustomServerHeader");
  4371. EXPECT_TRUE(it != res->headers.end());
  4372. EXPECT_EQ(it->second, "CustomServerValue");
  4373. }
  4374. }
  4375. class ServerTest : public ::testing::Test {
  4376. protected:
  4377. ServerTest()
  4378. : cli_(HOST, PORT)
  4379. #ifdef CPPHTTPLIB_SSL_ENABLED
  4380. ,
  4381. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4382. #endif
  4383. {
  4384. #ifdef CPPHTTPLIB_SSL_ENABLED
  4385. cli_.enable_server_certificate_verification(false);
  4386. #endif
  4387. // Allow LARGE_DATA (100MB) responses
  4388. cli_.set_payload_max_length(200 * 1024 * 1024);
  4389. }
  4390. virtual void SetUp() {
  4391. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4392. svr_.set_payload_max_length(200 * 1024 * 1024);
  4393. svr_.set_mount_point("/", "./www");
  4394. svr_.set_mount_point("/mount", "./www2");
  4395. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4396. svr_.Get("/hi",
  4397. [&](const Request & /*req*/, Response &res) {
  4398. res.set_content("Hello World!", "text/plain");
  4399. })
  4400. .Get("/file_content",
  4401. [&](const Request & /*req*/, Response &res) {
  4402. res.set_file_content("./www/dir/test.html");
  4403. })
  4404. .Get("/file_content_with_content_type",
  4405. [&](const Request & /*req*/, Response &res) {
  4406. res.set_file_content("./www/file", "text/plain");
  4407. })
  4408. .Get("/invalid_file_content",
  4409. [&](const Request & /*req*/, Response &res) {
  4410. res.set_file_content("./www/dir/invalid_file_path");
  4411. })
  4412. .Get("/http_response_splitting",
  4413. [&](const Request & /*req*/, Response &res) {
  4414. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4415. EXPECT_EQ(0U, res.headers.size());
  4416. EXPECT_FALSE(res.has_header("a"));
  4417. res.set_header("a", "1\nSet-Cookie: a=1");
  4418. EXPECT_EQ(0U, res.headers.size());
  4419. EXPECT_FALSE(res.has_header("a"));
  4420. res.set_header("a", "1\rSet-Cookie: a=1");
  4421. EXPECT_EQ(0U, res.headers.size());
  4422. EXPECT_FALSE(res.has_header("a"));
  4423. res.set_header("a\r\nb", "0");
  4424. EXPECT_EQ(0U, res.headers.size());
  4425. EXPECT_FALSE(res.has_header("a"));
  4426. res.set_header("a\rb", "0");
  4427. EXPECT_EQ(0U, res.headers.size());
  4428. EXPECT_FALSE(res.has_header("a"));
  4429. res.set_header("a\nb", "0");
  4430. EXPECT_EQ(0U, res.headers.size());
  4431. EXPECT_FALSE(res.has_header("a"));
  4432. res.set_redirect("1\r\nSet-Cookie: a=1");
  4433. EXPECT_EQ(0U, res.headers.size());
  4434. EXPECT_FALSE(res.has_header("Location"));
  4435. })
  4436. .Get("/slow",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. std::this_thread::sleep_for(std::chrono::seconds(4));
  4439. res.set_content("slow", "text/plain");
  4440. })
  4441. #if 0
  4442. .Post("/slowpost",
  4443. [&](const Request & /*req*/, Response &res) {
  4444. std::this_thread::sleep_for(std::chrono::seconds(2));
  4445. res.set_content("slow", "text/plain");
  4446. })
  4447. #endif
  4448. .Get("/remote_addr",
  4449. [&](const Request &req, Response &res) {
  4450. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4451. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4452. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4453. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4455. #endif
  4456. res.set_content(req.remote_addr, "text/plain");
  4457. })
  4458. .Get("/local_addr",
  4459. [&](const Request &req, Response &res) {
  4460. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4461. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4462. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4463. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4465. #endif
  4466. auto local_addr = req.local_addr;
  4467. auto local_port = std::to_string(req.local_port);
  4468. res.set_content(local_addr.append(":").append(local_port),
  4469. "text/plain");
  4470. })
  4471. .Get("/endwith%",
  4472. [&](const Request & /*req*/, Response &res) {
  4473. res.set_content("Hello World!", "text/plain");
  4474. })
  4475. .Get("/a\\+\\+b",
  4476. [&](const Request &req, Response &res) {
  4477. ASSERT_TRUE(req.has_param("a +b"));
  4478. auto val = req.get_param_value("a +b");
  4479. res.set_content(val, "text/plain");
  4480. })
  4481. .Get("/", [&](const Request & /*req*/,
  4482. Response &res) { res.set_redirect("/hi"); })
  4483. .Post("/1",
  4484. [](const Request & /*req*/, Response &res) {
  4485. res.set_redirect("/2", StatusCode::SeeOther_303);
  4486. })
  4487. .Get("/2",
  4488. [](const Request & /*req*/, Response &res) {
  4489. res.set_content("redirected.", "text/plain");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Post("/person",
  4493. [&](const Request &req, Response &res) {
  4494. if (req.has_param("name") && req.has_param("note")) {
  4495. persons_[req.get_param_value("name")] =
  4496. req.get_param_value("note");
  4497. } else {
  4498. res.status = StatusCode::BadRequest_400;
  4499. }
  4500. })
  4501. .Put("/person",
  4502. [&](const Request &req, Response &res) {
  4503. if (req.has_param("name") && req.has_param("note")) {
  4504. persons_[req.get_param_value("name")] =
  4505. req.get_param_value("note");
  4506. } else {
  4507. res.status = StatusCode::BadRequest_400;
  4508. }
  4509. })
  4510. .Get("/person/(.*)",
  4511. [&](const Request &req, Response &res) {
  4512. string name = req.matches[1];
  4513. if (persons_.find(name) != persons_.end()) {
  4514. auto note = persons_[name];
  4515. res.set_content(note, "text/plain");
  4516. } else {
  4517. res.status = StatusCode::NotFound_404;
  4518. }
  4519. })
  4520. .Delete("/person",
  4521. [&](const Request &req, Response &res) {
  4522. if (req.has_param("name")) {
  4523. string name = req.get_param_value("name");
  4524. if (persons_.find(name) != persons_.end()) {
  4525. persons_.erase(name);
  4526. res.set_content("DELETED", "text/plain");
  4527. } else {
  4528. res.status = StatusCode::NotFound_404;
  4529. }
  4530. } else {
  4531. res.status = StatusCode::BadRequest_400;
  4532. }
  4533. })
  4534. .Post("/x-www-form-urlencoded-json",
  4535. [&](const Request &req, Response &res) {
  4536. auto json = req.get_param_value("json");
  4537. ASSERT_EQ(JSON_DATA, json);
  4538. res.set_content(json, "appliation/json");
  4539. res.status = StatusCode::OK_200;
  4540. })
  4541. .Get("/streamed-chunked",
  4542. [&](const Request & /*req*/, Response &res) {
  4543. res.set_chunked_content_provider(
  4544. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4545. sink.os << "123";
  4546. sink.os << "456";
  4547. sink.os << "789";
  4548. sink.done();
  4549. return true;
  4550. });
  4551. })
  4552. .Get("/streamed-chunked-with-prohibited-trailer",
  4553. [&](const Request & /*req*/, Response &res) {
  4554. auto i = new int(0);
  4555. // Declare both a prohibited trailer (Content-Length) and an
  4556. // allowed one
  4557. res.set_header("Trailer", "Content-Length, X-Allowed");
  4558. res.set_chunked_content_provider(
  4559. "text/plain",
  4560. [i](size_t /*offset*/, DataSink &sink) {
  4561. switch (*i) {
  4562. case 0: sink.os << "123"; break;
  4563. case 1: sink.os << "456"; break;
  4564. case 2: sink.os << "789"; break;
  4565. case 3: {
  4566. sink.done_with_trailer(
  4567. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4568. } break;
  4569. }
  4570. (*i)++;
  4571. return true;
  4572. },
  4573. [i](bool success) {
  4574. EXPECT_TRUE(success);
  4575. delete i;
  4576. });
  4577. })
  4578. .Get("/streamed-chunked2",
  4579. [&](const Request & /*req*/, Response &res) {
  4580. auto i = new int(0);
  4581. res.set_chunked_content_provider(
  4582. "text/plain",
  4583. [i](size_t /*offset*/, DataSink &sink) {
  4584. switch (*i) {
  4585. case 0: sink.os << "123"; break;
  4586. case 1: sink.os << "456"; break;
  4587. case 2: sink.os << "789"; break;
  4588. case 3: sink.done(); break;
  4589. }
  4590. (*i)++;
  4591. return true;
  4592. },
  4593. [i](bool success) {
  4594. EXPECT_TRUE(success);
  4595. delete i;
  4596. });
  4597. })
  4598. .Get("/streamed-chunked-with-trailer",
  4599. [&](const Request & /*req*/, Response &res) {
  4600. auto i = new int(0);
  4601. res.set_header("Trailer", "Dummy1, Dummy2");
  4602. res.set_chunked_content_provider(
  4603. "text/plain",
  4604. [i](size_t /*offset*/, DataSink &sink) {
  4605. switch (*i) {
  4606. case 0: sink.os << "123"; break;
  4607. case 1: sink.os << "456"; break;
  4608. case 2: sink.os << "789"; break;
  4609. case 3: {
  4610. sink.done_with_trailer(
  4611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4612. } break;
  4613. }
  4614. (*i)++;
  4615. return true;
  4616. },
  4617. [i](bool success) {
  4618. EXPECT_TRUE(success);
  4619. delete i;
  4620. });
  4621. })
  4622. .Get("/streamed",
  4623. [&](const Request & /*req*/, Response &res) {
  4624. res.set_content_provider(
  4625. 6, "text/plain",
  4626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4627. sink.os << (offset < 3 ? "a" : "b");
  4628. return true;
  4629. });
  4630. })
  4631. .Get("/streamed-without-length",
  4632. [&](const Request & /*req*/, Response &res) {
  4633. auto data = new std::string("abcdefg");
  4634. res.set_content_provider(
  4635. "text/plain",
  4636. [data](size_t offset, DataSink &sink) {
  4637. if (offset < data->size()) {
  4638. sink.os << data->substr(offset);
  4639. }
  4640. sink.done();
  4641. return true;
  4642. },
  4643. [data](bool success) {
  4644. EXPECT_TRUE(success);
  4645. delete data;
  4646. });
  4647. })
  4648. .Get("/streamed-with-range",
  4649. [&](const Request &req, Response &res) {
  4650. auto data = new std::string("abcdefg");
  4651. // An explicit status keeps the server from picking the 206 it
  4652. // would otherwise choose for a ranged request, so the response
  4653. // is not a partial representation.
  4654. auto status = req.get_param_value("status");
  4655. if (status == "200") {
  4656. res.status = StatusCode::OK_200;
  4657. } else if (status == "403") {
  4658. res.status = StatusCode::Forbidden_403;
  4659. }
  4660. res.set_content_provider(
  4661. data->size(), "text/plain",
  4662. [data](size_t offset, size_t length, DataSink &sink) {
  4663. size_t DATA_CHUNK_SIZE = 4;
  4664. const auto &d = *data;
  4665. auto out_len =
  4666. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4667. auto ret =
  4668. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4669. EXPECT_TRUE(ret);
  4670. return true;
  4671. },
  4672. [data, &req](bool success) {
  4673. EXPECT_EQ(success, !req.has_param("error"));
  4674. delete data;
  4675. });
  4676. })
  4677. .Get("/streamed-cancel",
  4678. [&](const Request & /*req*/, Response &res) {
  4679. res.set_content_provider(
  4680. size_t(-1), "text/plain",
  4681. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4682. sink.os << "data_chunk";
  4683. return true;
  4684. });
  4685. })
  4686. .Get("/regex-with-delimiter",
  4687. [&](const Request &req, Response & /*res*/) {
  4688. ASSERT_TRUE(req.has_param("key"));
  4689. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4690. })
  4691. .Get("/with-range",
  4692. [&](const Request & /*req*/, Response &res) {
  4693. res.set_content("abcdefg", "text/plain");
  4694. })
  4695. .Get("/test-start-time",
  4696. [&](const Request &req, Response & /*res*/) {
  4697. EXPECT_NE(req.start_time_,
  4698. std::chrono::steady_clock::time_point::min());
  4699. })
  4700. .Get("/with-range-customized-response",
  4701. [&](const Request & /*req*/, Response &res) {
  4702. res.status = StatusCode::BadRequest_400;
  4703. res.set_content(JSON_DATA, "application/json");
  4704. })
  4705. .Post("/chunked",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(req.body, "dechunked post body");
  4708. })
  4709. .Post("/large-chunked",
  4710. [&](const Request &req, Response & /*res*/) {
  4711. std::string expected(6 * 30 * 1024u, 'a');
  4712. EXPECT_EQ(req.body, expected);
  4713. })
  4714. .Post("/multipart",
  4715. [&](const Request &req, Response & /*res*/) {
  4716. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4717. req.form.get_field_count("text2") +
  4718. req.form.get_field_count("file3") +
  4719. req.form.get_field_count("file4"));
  4720. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4721. req.form.get_file_count("file2"));
  4722. ASSERT_TRUE(!req.form.has_file("???"));
  4723. ASSERT_TRUE(!req.form.has_field("???"));
  4724. ASSERT_TRUE(req.body.empty());
  4725. {
  4726. const auto &text = req.form.get_field("text1");
  4727. EXPECT_EQ("text default", text);
  4728. }
  4729. {
  4730. const auto &text = req.form.get_field("text2");
  4731. EXPECT_EQ("aωb", text);
  4732. }
  4733. {
  4734. const auto &file = req.form.get_file("file1");
  4735. EXPECT_EQ("hello.txt", file.filename);
  4736. EXPECT_EQ("text/plain", file.content_type);
  4737. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4738. }
  4739. {
  4740. const auto &file = req.form.get_file("file2");
  4741. EXPECT_EQ("world.json", file.filename);
  4742. EXPECT_EQ("application/json", file.content_type);
  4743. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4744. }
  4745. {
  4746. const auto &text = req.form.get_field("file3");
  4747. EXPECT_EQ(0u, text.size());
  4748. }
  4749. {
  4750. const auto &text = req.form.get_field("file4");
  4751. EXPECT_EQ(0u, text.size());
  4752. }
  4753. })
  4754. .Post("/multipart/multi_file_values",
  4755. [&](const Request &req, Response & /*res*/) {
  4756. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4757. req.form.get_field_count("multi_text1"));
  4758. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4759. ASSERT_TRUE(!req.form.has_file("???"));
  4760. ASSERT_TRUE(!req.form.has_field("???"));
  4761. ASSERT_TRUE(req.body.empty());
  4762. {
  4763. const auto &text = req.form.get_field("text");
  4764. EXPECT_EQ("default text", text);
  4765. }
  4766. {
  4767. const auto &text1_values = req.form.get_fields("multi_text1");
  4768. EXPECT_EQ(2u, text1_values.size());
  4769. EXPECT_EQ("aaaaa", text1_values[0]);
  4770. EXPECT_EQ("bbbbb", text1_values[1]);
  4771. }
  4772. {
  4773. const auto &file1_values = req.form.get_files("multi_file1");
  4774. EXPECT_EQ(2u, file1_values.size());
  4775. auto file1 = file1_values[0];
  4776. EXPECT_EQ(file1.filename, "hello.txt");
  4777. EXPECT_EQ(file1.content_type, "text/plain");
  4778. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4779. auto file2 = file1_values[1];
  4780. EXPECT_EQ(file2.filename, "world.json");
  4781. EXPECT_EQ(file2.content_type, "application/json");
  4782. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4783. }
  4784. })
  4785. .Post("/empty",
  4786. [&](const Request &req, Response &res) {
  4787. EXPECT_EQ(req.body, "");
  4788. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4789. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4790. res.set_content("empty", "text/plain");
  4791. })
  4792. .Post("/empty-no-content-type",
  4793. [&](const Request &req, Response &res) {
  4794. EXPECT_EQ(req.body, "");
  4795. EXPECT_FALSE(req.has_header("Content-Type"));
  4796. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4797. res.set_content("empty-no-content-type", "text/plain");
  4798. })
  4799. .Post("/path-only",
  4800. [&](const Request &req, Response &res) {
  4801. EXPECT_EQ(req.body, "");
  4802. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4803. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4804. res.set_content("path-only", "text/plain");
  4805. })
  4806. .Post("/path-headers-only",
  4807. [&](const Request &req, Response &res) {
  4808. EXPECT_EQ(req.body, "");
  4809. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4810. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4811. EXPECT_EQ("world", req.get_header_value("hello"));
  4812. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4813. res.set_content("path-headers-only", "text/plain");
  4814. })
  4815. .Post("/post-large",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, LARGE_DATA);
  4818. res.set_content(req.body, "text/plain");
  4819. })
  4820. .Post("/post-loopback",
  4821. [&](const Request &, Response &res,
  4822. ContentReader const &content_reader) {
  4823. std::string body;
  4824. content_reader([&](const char *data, size_t data_length) {
  4825. body.append(data, data_length);
  4826. return true;
  4827. });
  4828. res.set_content(body, "text/plain");
  4829. })
  4830. .Put("/put-loopback",
  4831. [&](const Request &, Response &res,
  4832. ContentReader const &content_reader) {
  4833. std::string body;
  4834. content_reader([&](const char *data, size_t data_length) {
  4835. body.append(data, data_length);
  4836. return true;
  4837. });
  4838. res.set_content(body, "text/plain");
  4839. })
  4840. .Patch("/patch-loopback",
  4841. [&](const Request &, Response &res,
  4842. ContentReader const &content_reader) {
  4843. std::string body;
  4844. content_reader([&](const char *data, size_t data_length) {
  4845. body.append(data, data_length);
  4846. return true;
  4847. });
  4848. res.set_content(body, "text/plain");
  4849. })
  4850. .Put("/empty-no-content-type",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_FALSE(req.has_header("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty-no-content-type", "text/plain");
  4856. })
  4857. .Put("/put",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "PUT");
  4860. res.set_content(req.body, "text/plain");
  4861. })
  4862. .Put("/put-large",
  4863. [&](const Request &req, Response &res) {
  4864. EXPECT_EQ(req.body, LARGE_DATA);
  4865. res.set_content(req.body, "text/plain");
  4866. })
  4867. .Patch("/patch",
  4868. [&](const Request &req, Response &res) {
  4869. EXPECT_EQ(req.body, "PATCH");
  4870. res.set_content(req.body, "text/plain");
  4871. })
  4872. .Delete("/delete",
  4873. [&](const Request & /*req*/, Response &res) {
  4874. res.set_content("DELETE", "text/plain");
  4875. })
  4876. .Delete("/delete-body",
  4877. [&](const Request &req, Response &res) {
  4878. EXPECT_EQ(req.body, "content");
  4879. res.set_content(req.body, "text/plain");
  4880. })
  4881. .Options(R"(\*)",
  4882. [&](const Request & /*req*/, Response &res) {
  4883. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4884. })
  4885. .CustomRoute("PROPFIND", "/dav/:id",
  4886. [&](const Request &req, Response &res) {
  4887. res.set_header("x-body-size",
  4888. std::to_string(req.body.size()));
  4889. res.set_header("x-matched-route", req.matched_route);
  4890. res.set_header("x-dav-id", req.path_params.at("id"));
  4891. res.status = StatusCode::MultiStatus_207;
  4892. res.set_content(req.body, "application/xml");
  4893. })
  4894. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4895. [&](const Request &req, Response &res) {
  4896. res.set_header("x-dav-match", req.matches[1]);
  4897. res.status = StatusCode::MultiStatus_207;
  4898. })
  4899. .CustomRoute("MKCOL", "/dav-mkcol",
  4900. [&](const Request &req, Response &res) {
  4901. EXPECT_TRUE(req.body.empty());
  4902. res.status = StatusCode::Created_201;
  4903. })
  4904. .CustomRoute(
  4905. "REPORT", "/dav-report",
  4906. [&](const Request & /*req*/, Response &res,
  4907. const ContentReader &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_header("x-body-size", std::to_string(body.size()));
  4914. res.status = StatusCode::MultiStatus_207;
  4915. res.set_content(body, "application/xml");
  4916. })
  4917. .Get("/request-target",
  4918. [&](const Request &req, Response & /*res*/) {
  4919. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4920. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4921. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4922. })
  4923. .Get("/long-query-value",
  4924. [&](const Request &req, Response & /*res*/) {
  4925. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4926. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4927. })
  4928. .Get("/too-long-query-value",
  4929. [&](const Request &req, Response & /*res*/) {
  4930. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4931. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4932. })
  4933. .Get("/array-param",
  4934. [&](const Request &req, Response & /*res*/) {
  4935. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4936. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4937. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4938. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4939. })
  4940. .Get("/array-param-values",
  4941. [&](const Request &req, Response & /*res*/) {
  4942. auto values = req.get_param_values("array");
  4943. EXPECT_EQ(3u, values.size());
  4944. EXPECT_EQ("value1", values[0]);
  4945. EXPECT_EQ("value2", values[1]);
  4946. EXPECT_EQ("value3", values[2]);
  4947. auto empty = req.get_param_values("nonexistent");
  4948. EXPECT_TRUE(empty.empty());
  4949. })
  4950. .Post("/validate-no-multiple-headers",
  4951. [&](const Request &req, Response & /*res*/) {
  4952. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4953. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4954. })
  4955. .Post("/content_receiver",
  4956. [&](const Request &req, Response &res,
  4957. const ContentReader &content_reader) {
  4958. if (req.is_multipart_form_data()) {
  4959. std::vector<FormData> items;
  4960. content_reader(
  4961. [&](const FormData &file) {
  4962. items.push_back(file);
  4963. return true;
  4964. },
  4965. [&](const char *data, size_t data_length) {
  4966. items.back().content.append(data, data_length);
  4967. return true;
  4968. });
  4969. EXPECT_EQ(5u, items.size());
  4970. {
  4971. const auto &file = get_file_value(items, "text1");
  4972. EXPECT_TRUE(file.filename.empty());
  4973. EXPECT_EQ("text default", file.content);
  4974. }
  4975. {
  4976. const auto &file = get_file_value(items, "text2");
  4977. EXPECT_TRUE(file.filename.empty());
  4978. EXPECT_EQ("aωb", file.content);
  4979. }
  4980. {
  4981. const auto &file = get_file_value(items, "file1");
  4982. EXPECT_EQ("hello.txt", file.filename);
  4983. EXPECT_EQ("text/plain", file.content_type);
  4984. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4985. }
  4986. {
  4987. const auto &file = get_file_value(items, "file2");
  4988. EXPECT_EQ("world.json", file.filename);
  4989. EXPECT_EQ("application/json", file.content_type);
  4990. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4991. }
  4992. {
  4993. const auto &file = get_file_value(items, "file3");
  4994. EXPECT_TRUE(file.filename.empty());
  4995. EXPECT_EQ("application/octet-stream", file.content_type);
  4996. EXPECT_EQ(0u, file.content.size());
  4997. }
  4998. } else {
  4999. std::string body;
  5000. content_reader([&](const char *data, size_t data_length) {
  5001. EXPECT_EQ(7U, data_length);
  5002. body.append(data, data_length);
  5003. return true;
  5004. });
  5005. EXPECT_EQ(body, "content");
  5006. res.set_content(body, "text/plain");
  5007. }
  5008. })
  5009. .Put("/content_receiver",
  5010. [&](const Request & /*req*/, Response &res,
  5011. const ContentReader &content_reader) {
  5012. std::string body;
  5013. content_reader([&](const char *data, size_t data_length) {
  5014. body.append(data, data_length);
  5015. return true;
  5016. });
  5017. EXPECT_EQ(body, "content");
  5018. res.set_content(body, "text/plain");
  5019. })
  5020. .Patch("/content_receiver",
  5021. [&](const Request & /*req*/, Response &res,
  5022. const ContentReader &content_reader) {
  5023. std::string body;
  5024. content_reader([&](const char *data, size_t data_length) {
  5025. body.append(data, data_length);
  5026. return true;
  5027. });
  5028. EXPECT_EQ(body, "content");
  5029. res.set_content(body, "text/plain");
  5030. })
  5031. .Post("/query-string-and-body",
  5032. [&](const Request &req, Response & /*res*/) {
  5033. ASSERT_TRUE(req.has_param("key"));
  5034. EXPECT_EQ(req.get_param_value("key"), "value");
  5035. EXPECT_EQ(req.body, "content");
  5036. })
  5037. .Get("/last-request",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ("close", req.get_header_value("Connection"));
  5040. })
  5041. .Get(R"(/redirect/(\d+))",
  5042. [&](const Request &req, Response &res) {
  5043. auto num = std::stoi(req.matches[1]) + 1;
  5044. std::string url = "/redirect/" + std::to_string(num);
  5045. res.set_redirect(url);
  5046. })
  5047. .Post("/binary",
  5048. [&](const Request &req, Response &res) {
  5049. EXPECT_EQ(4U, req.body.size());
  5050. EXPECT_EQ("application/octet-stream",
  5051. req.get_header_value("Content-Type"));
  5052. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5053. res.set_content(req.body, "application/octet-stream");
  5054. })
  5055. .Put("/binary",
  5056. [&](const Request &req, Response &res) {
  5057. EXPECT_EQ(4U, req.body.size());
  5058. EXPECT_EQ("application/octet-stream",
  5059. req.get_header_value("Content-Type"));
  5060. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5061. res.set_content(req.body, "application/octet-stream");
  5062. })
  5063. .Patch("/binary",
  5064. [&](const Request &req, Response &res) {
  5065. EXPECT_EQ(4U, req.body.size());
  5066. EXPECT_EQ("application/octet-stream",
  5067. req.get_header_value("Content-Type"));
  5068. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5069. res.set_content(req.body, "application/octet-stream");
  5070. })
  5071. .Delete("/binary",
  5072. [&](const Request &req, Response &res) {
  5073. EXPECT_EQ(4U, req.body.size());
  5074. EXPECT_EQ("application/octet-stream",
  5075. req.get_header_value("Content-Type"));
  5076. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5077. res.set_content(req.body, "application/octet-stream");
  5078. })
  5079. .Get("/issue1772",
  5080. [&](const Request & /*req*/, Response &res) {
  5081. res.status = 401;
  5082. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5083. })
  5084. .Delete("/issue609",
  5085. [](const httplib::Request &, httplib::Response &res,
  5086. const httplib::ContentReader &) {
  5087. res.set_content("ok", "text/plain");
  5088. })
  5089. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5090. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5091. .Get("/compress",
  5092. [&](const Request & /*req*/, Response &res) {
  5093. res.set_content(
  5094. "12345678901234567890123456789012345678901234567890123456789"
  5095. "01234567890123456789012345678901234567890",
  5096. "text/plain");
  5097. })
  5098. .Get("/compress-with-charset",
  5099. [&](const Request & /*req*/, Response &res) {
  5100. res.set_content(
  5101. "12345678901234567890123456789012345678901234567890123456789"
  5102. "01234567890123456789012345678901234567890",
  5103. "application/json; charset=utf-8");
  5104. })
  5105. .Get("/nocompress",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content(
  5108. "12345678901234567890123456789012345678901234567890123456789"
  5109. "01234567890123456789012345678901234567890",
  5110. "application/octet-stream");
  5111. })
  5112. .Post("/compress-multipart",
  5113. [&](const Request &req, Response & /*res*/) {
  5114. EXPECT_EQ(2u, req.form.fields.size());
  5115. ASSERT_TRUE(!req.form.has_field("???"));
  5116. {
  5117. const auto &text = req.form.get_field("key1");
  5118. EXPECT_EQ("test", text);
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("key2");
  5122. EXPECT_EQ("--abcdefg123", text);
  5123. }
  5124. })
  5125. #endif
  5126. ;
  5127. persons_["john"] = "programmer";
  5128. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5129. svr_.wait_until_ready();
  5130. }
  5131. virtual void TearDown() {
  5132. svr_.stop();
  5133. if (!request_threads_.empty()) {
  5134. std::this_thread::sleep_for(std::chrono::seconds(1));
  5135. for (auto &t : request_threads_) {
  5136. t.join();
  5137. }
  5138. }
  5139. t_.join();
  5140. }
  5141. map<string, string> persons_;
  5142. #ifdef CPPHTTPLIB_SSL_ENABLED
  5143. SSLClient cli_;
  5144. SSLServer svr_;
  5145. #else
  5146. Client cli_;
  5147. Server svr_;
  5148. #endif
  5149. thread t_;
  5150. std::vector<thread> request_threads_;
  5151. };
  5152. TEST_F(ServerTest, GetMethod200) {
  5153. auto res = cli_.Get("/hi");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ("HTTP/1.1", res->version);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("OK", res->reason);
  5158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5159. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5160. EXPECT_EQ("Hello World!", res->body);
  5161. }
  5162. TEST_F(ServerTest, GetEmptyFile) {
  5163. auto res = cli_.Get("/empty_file");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5168. EXPECT_EQ("", res->body);
  5169. }
  5170. TEST_F(ServerTest, GetFileContent) {
  5171. auto res = cli_.Get("/file_content");
  5172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5176. EXPECT_EQ("test.html", res->body);
  5177. }
  5178. TEST_F(ServerTest, GetFileContentWithRange) {
  5179. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5182. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5183. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5184. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5185. EXPECT_EQ("est", res->body);
  5186. }
  5187. TEST_F(ServerTest, GetFileContentWithContentType) {
  5188. auto res = cli_.Get("/file_content_with_content_type");
  5189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5193. EXPECT_EQ("file\n", res->body);
  5194. }
  5195. TEST_F(ServerTest, GetInvalidFileContent) {
  5196. auto res = cli_.Get("/invalid_file_content");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5199. }
  5200. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5201. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ("HTTP/1.1", res->version);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5206. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5207. EXPECT_EQ("Hello World!", res->body);
  5208. }
  5209. TEST_F(ServerTest, GetMethod302) {
  5210. auto res = cli_.Get("/");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::Found_302, res->status);
  5213. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5214. }
  5215. TEST_F(ServerTest, GetMethod302Redirect) {
  5216. cli_.set_follow_location(true);
  5217. auto res = cli_.Get("/");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ(StatusCode::OK_200, res->status);
  5220. EXPECT_EQ("Hello World!", res->body);
  5221. EXPECT_EQ("/hi", res->location);
  5222. }
  5223. TEST_F(ServerTest, GetMethod404) {
  5224. auto res = cli_.Get("/invalid");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5227. }
  5228. TEST_F(ServerTest, HeadMethod200) {
  5229. auto res = cli_.Head("/hi");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. EXPECT_TRUE(res->body.empty());
  5234. }
  5235. TEST_F(ServerTest, HeadMethod200Static) {
  5236. auto res = cli_.Head("/mount/dir/index.html");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_TRUE(res->body.empty());
  5242. }
  5243. TEST_F(ServerTest, HeadMethod404) {
  5244. auto res = cli_.Head("/invalid");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5247. EXPECT_TRUE(res->body.empty());
  5248. }
  5249. TEST_F(ServerTest, GetMethodPersonJohn) {
  5250. auto res = cli_.Get("/person/john");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5254. EXPECT_EQ("programmer", res->body);
  5255. }
  5256. TEST_F(ServerTest, PostMethod1) {
  5257. auto res = cli_.Get("/person/john1");
  5258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5259. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5260. res = cli_.Post("/person", "name=john1&note=coder",
  5261. "application/x-www-form-urlencoded");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. res = cli_.Get("/person/john1");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. ASSERT_EQ(StatusCode::OK_200, res->status);
  5267. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5268. ASSERT_EQ("coder", res->body);
  5269. }
  5270. TEST_F(ServerTest, PostMethod2) {
  5271. auto res = cli_.Get("/person/john2");
  5272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5273. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5274. Params params;
  5275. params.emplace("name", "john2");
  5276. params.emplace("note", "coder");
  5277. res = cli_.Post("/person", params);
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. res = cli_.Get("/person/john2");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. ASSERT_EQ(StatusCode::OK_200, res->status);
  5283. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. ASSERT_EQ("coder", res->body);
  5285. }
  5286. TEST_F(ServerTest, PutMethod3) {
  5287. auto res = cli_.Get("/person/john3");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5290. Params params;
  5291. params.emplace("name", "john3");
  5292. params.emplace("note", "coder");
  5293. res = cli_.Put("/person", params);
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::OK_200, res->status);
  5296. res = cli_.Get("/person/john3");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. ASSERT_EQ(StatusCode::OK_200, res->status);
  5299. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. ASSERT_EQ("coder", res->body);
  5301. }
  5302. TEST_F(ServerTest, DeleteMethod1) {
  5303. auto res = cli_.Get("/person/john4");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5306. Params params;
  5307. params.emplace("name", "john4");
  5308. params.emplace("note", "coder");
  5309. res = cli_.Post("/person", params);
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. ASSERT_EQ(StatusCode::OK_200, res->status);
  5312. res = cli_.Get("/person/john4");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. ASSERT_EQ("coder", res->body);
  5317. Params delete_params;
  5318. delete_params.emplace("name", "john4");
  5319. res = cli_.Delete("/person", delete_params);
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. ASSERT_EQ("DELETED", res->body);
  5323. res = cli_.Get("/person/john4");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5326. }
  5327. TEST_F(ServerTest, DeleteMethod2) {
  5328. auto res = cli_.Get("/person/john5");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. Params params;
  5332. params.emplace("name", "john5");
  5333. params.emplace("note", "developer");
  5334. res = cli_.Post("/person", params);
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. ASSERT_EQ(StatusCode::OK_200, res->status);
  5337. res = cli_.Get("/person/john5");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::OK_200, res->status);
  5340. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. ASSERT_EQ("developer", res->body);
  5342. Params delete_params;
  5343. delete_params.emplace("name", "john5");
  5344. Headers headers;
  5345. headers.emplace("Custom-Header", "test-value");
  5346. res = cli_.Delete("/person", headers, delete_params);
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ("DELETED", res->body);
  5350. res = cli_.Get("/person/john5");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5353. }
  5354. TEST_F(ServerTest, DeleteMethod3) {
  5355. auto res = cli_.Get("/person/john6");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5358. Params params;
  5359. params.emplace("name", "john6");
  5360. params.emplace("note", "tester");
  5361. res = cli_.Post("/person", params);
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. res = cli_.Get("/person/john6");
  5365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5366. ASSERT_EQ(StatusCode::OK_200, res->status);
  5367. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5368. ASSERT_EQ("tester", res->body);
  5369. Params delete_params;
  5370. delete_params.emplace("name", "john6");
  5371. Headers headers;
  5372. headers.emplace("Custom-Header", "test-value");
  5373. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. ASSERT_EQ(StatusCode::OK_200, res->status);
  5376. ASSERT_EQ("DELETED", res->body);
  5377. res = cli_.Get("/person/john6");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5380. }
  5381. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5382. Params params;
  5383. params.emplace("json", JSON_DATA);
  5384. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ(JSON_DATA, res->body);
  5388. }
  5389. TEST_F(ServerTest, PostEmptyContent) {
  5390. auto res = cli_.Post("/empty", "", "text/plain");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::OK_200, res->status);
  5393. ASSERT_EQ("empty", res->body);
  5394. }
  5395. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5396. auto res = cli_.Post("/empty-no-content-type");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::OK_200, res->status);
  5399. ASSERT_EQ("empty-no-content-type", res->body);
  5400. }
  5401. TEST_F(ServerTest, PostPathOnly) {
  5402. auto res = cli_.Post("/path-only");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("path-only", res->body);
  5406. }
  5407. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5408. auto res = cli_.Post("/path-headers-only",
  5409. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5411. ASSERT_EQ(StatusCode::OK_200, res->status);
  5412. ASSERT_EQ("path-headers-only", res->body);
  5413. }
  5414. TEST_F(ServerTest, PostLarge) {
  5415. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ(LARGE_DATA, res->body);
  5419. }
  5420. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5421. auto res = cli_.Put("/empty-no-content-type");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. ASSERT_EQ("empty-no-content-type", res->body);
  5425. }
  5426. TEST_F(ServerTest, GetMethodDir) {
  5427. auto res = cli_.Get("/dir/");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5431. auto body = R"(<html>
  5432. <head>
  5433. </head>
  5434. <body>
  5435. <a href="/dir/test.html">Test</a>
  5436. <a href="/hi">hi</a>
  5437. </body>
  5438. </html>
  5439. )";
  5440. EXPECT_EQ(body, res->body);
  5441. }
  5442. TEST_F(ServerTest, GetMethodDirTest) {
  5443. auto res = cli_.Get("/dir/test.html");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("test.html", res->body);
  5448. }
  5449. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5450. auto res = cli_.Get("/dir/../dir/test.html");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5454. EXPECT_EQ("test.html", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetMethodInvalidPath) {
  5457. auto res = cli_.Get("/dir/../test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5462. auto res = cli_.Get("/../www/dir/test.html");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5465. }
  5466. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5467. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5470. }
  5471. TEST_F(ServerTest, GetMethodDirMountTest) {
  5472. auto res = cli_.Get("/mount/dir/test.html");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5476. EXPECT_EQ("test.html", res->body);
  5477. }
  5478. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5479. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ("test.html", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5486. auto res = cli_.Get("/mount/dir/../test.html");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5489. }
  5490. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5491. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5494. }
  5495. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5496. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5499. }
  5500. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5501. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5506. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostMethod303) {
  5511. auto res = cli_.Post("/1", "body", "text/plain");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5514. EXPECT_EQ("/2", res->get_header_value("Location"));
  5515. }
  5516. TEST_F(ServerTest, PostMethod303Redirect) {
  5517. cli_.set_follow_location(true);
  5518. auto res = cli_.Post("/1", "body", "text/plain");
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. EXPECT_EQ("redirected.", res->body);
  5522. EXPECT_EQ("/2", res->location);
  5523. }
  5524. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5525. auto res = cli_.Get("/dir/test.abcde");
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ("abcde", res->body);
  5530. }
  5531. TEST_F(ServerTest, StaticFileRange) {
  5532. auto res =
  5533. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5536. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ(true, res->has_header("Content-Range"));
  5539. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5540. EXPECT_EQ(std::string("cd"), res->body);
  5541. }
  5542. TEST_F(ServerTest, StaticFileRanges) {
  5543. auto res = cli_.Get("/dir/test.abcde",
  5544. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5547. EXPECT_TRUE(
  5548. res->get_header_value("Content-Type")
  5549. .find(
  5550. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5551. 0);
  5552. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5553. }
  5554. TEST_F(ServerTest, StaticFileRangeHead) {
  5555. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5559. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ(true, res->has_header("Content-Range"));
  5561. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5562. }
  5563. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5564. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5568. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5569. EXPECT_EQ(true, res->has_header("Content-Range"));
  5570. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5571. res->get_header_value("Content-Range"));
  5572. EXPECT_EQ("LAST\n", res->body);
  5573. }
  5574. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5575. auto res =
  5576. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5580. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5581. EXPECT_EQ(true, res->has_header("Content-Range"));
  5582. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5583. }
  5584. TEST_F(ServerTest, StaticFileBigFile) {
  5585. auto res = cli_.Get("/dir/1MB.txt");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::OK_200, res->status);
  5588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5589. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5590. }
  5591. TEST_F(ServerTest, InvalidBaseDirMount) {
  5592. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5593. }
  5594. TEST_F(ServerTest, Binary) {
  5595. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5596. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5597. "application/octet-stream");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. ASSERT_EQ(StatusCode::OK_200, res->status);
  5600. ASSERT_EQ(4U, res->body.size());
  5601. res = cli_.Put("/binary", binary.data(), binary.size(),
  5602. "application/octet-stream");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::OK_200, res->status);
  5605. ASSERT_EQ(4U, res->body.size());
  5606. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5607. "application/octet-stream");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. ASSERT_EQ(StatusCode::OK_200, res->status);
  5610. ASSERT_EQ(4U, res->body.size());
  5611. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5612. "application/octet-stream");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ(4U, res->body.size());
  5616. }
  5617. TEST_F(ServerTest, BinaryString) {
  5618. auto binary = std::string("\x00\x01\x02\x03", 4);
  5619. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ(4U, res->body.size());
  5623. res = cli_.Put("/binary", binary, "application/octet-stream");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. ASSERT_EQ(StatusCode::OK_200, res->status);
  5626. ASSERT_EQ(4U, res->body.size());
  5627. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. ASSERT_EQ(StatusCode::OK_200, res->status);
  5630. ASSERT_EQ(4U, res->body.size());
  5631. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. ASSERT_EQ(4U, res->body.size());
  5635. }
  5636. TEST_F(ServerTest, EmptyRequest) {
  5637. auto res = cli_.Get("");
  5638. ASSERT_TRUE(!res);
  5639. EXPECT_EQ(Error::Connection, res.error());
  5640. }
  5641. TEST_F(ServerTest, LongRequest) {
  5642. std::string request;
  5643. for (size_t i = 0; i < 545; i++) {
  5644. request += "/TooLongRequest";
  5645. }
  5646. request += "OK";
  5647. auto res = cli_.Get(request.c_str());
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5650. }
  5651. TEST_F(ServerTest, TooLongRequest) {
  5652. std::string request;
  5653. for (size_t i = 0; i < 546; i++) {
  5654. request += "/TooLongRequest";
  5655. }
  5656. request += "_NG";
  5657. auto start = std::chrono::high_resolution_clock::now();
  5658. cli_.set_keep_alive(true);
  5659. auto res = cli_.Get(request.c_str());
  5660. auto end = std::chrono::high_resolution_clock::now();
  5661. auto elapsed =
  5662. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5663. .count();
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5666. EXPECT_LE(elapsed, 1000);
  5667. EXPECT_EQ("close", res->get_header_value("Connection"));
  5668. EXPECT_FALSE(cli_.is_socket_open());
  5669. }
  5670. TEST_F(ServerTest, AlmostTooLongRequest) {
  5671. // test for #2046 - URI length check shouldn't include other content on req
  5672. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5673. // leading /, space, HTTP/1.1)
  5674. std::string request =
  5675. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5676. auto res = cli_.Get(request.c_str());
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5679. }
  5680. TEST_F(ServerTest, LongHeader) {
  5681. Request req;
  5682. req.method = "GET";
  5683. req.path = "/hi";
  5684. std::string host_and_port;
  5685. host_and_port += HOST;
  5686. host_and_port += ":";
  5687. host_and_port += std::to_string(PORT);
  5688. req.headers.emplace("Host", host_and_port.c_str());
  5689. req.headers.emplace("Accept", "*/*");
  5690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5691. req.headers.emplace(
  5692. "Header-Name",
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@");
  5722. auto res = std::make_shared<Response>();
  5723. auto error = Error::Success;
  5724. auto ret = cli_.send(req, *res, error);
  5725. ASSERT_TRUE(ret);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. }
  5728. TEST_F(ServerTest, LongQueryValue) {
  5729. auto start = std::chrono::high_resolution_clock::now();
  5730. cli_.set_keep_alive(true);
  5731. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5732. auto end = std::chrono::high_resolution_clock::now();
  5733. auto elapsed =
  5734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5735. .count();
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5738. EXPECT_LE(elapsed, 1000);
  5739. EXPECT_EQ("close", res->get_header_value("Connection"));
  5740. EXPECT_FALSE(cli_.is_socket_open());
  5741. }
  5742. TEST_F(ServerTest, TooLongQueryValue) {
  5743. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5744. ASSERT_FALSE(res);
  5745. EXPECT_EQ(Error::Read, res.error());
  5746. }
  5747. TEST_F(ServerTest, TooLongHeader) {
  5748. Request req;
  5749. req.method = "GET";
  5750. req.path = "/hi";
  5751. std::string host_and_port;
  5752. host_and_port += HOST;
  5753. host_and_port += ":";
  5754. host_and_port += std::to_string(PORT);
  5755. req.headers.emplace("Host", host_and_port.c_str());
  5756. req.headers.emplace("Accept", "*/*");
  5757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5758. req.headers.emplace(
  5759. "Header-Name",
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@@");
  5789. auto res = std::make_shared<Response>();
  5790. auto error = Error::Success;
  5791. auto ret = cli_.send(req, *res, error);
  5792. ASSERT_TRUE(ret);
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. }
  5795. TEST_F(ServerTest, HeaderCountAtLimit) {
  5796. // Test with headers just under the 100 limit
  5797. httplib::Headers headers;
  5798. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5799. // This should keep us just under the 100 header limit
  5800. for (int i = 0; i < 95; i++) {
  5801. std::string name = "X-Test-Header-" + std::to_string(i);
  5802. std::string value = "value" + std::to_string(i);
  5803. headers.emplace(name, value);
  5804. }
  5805. // This should work fine as we're under the limit
  5806. auto res = cli_.Get("/hi", headers);
  5807. EXPECT_TRUE(res);
  5808. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5809. }
  5810. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5811. // Test with many headers to exceed the 100 limit
  5812. httplib::Headers headers;
  5813. // Add 150 headers to definitely exceed the 100 limit
  5814. for (int i = 0; i < 150; i++) {
  5815. std::string name = "X-Test-Header-" + std::to_string(i);
  5816. std::string value = "value" + std::to_string(i);
  5817. headers.emplace(name, value);
  5818. }
  5819. // This should fail due to exceeding header count limit
  5820. cli_.set_keep_alive(true);
  5821. auto res = cli_.Get("/hi", headers);
  5822. // The server should respond with 400 Bad Request
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5825. EXPECT_EQ("close", res->get_header_value("Connection"));
  5826. EXPECT_FALSE(cli_.is_socket_open());
  5827. }
  5828. TEST_F(ServerTest, PercentEncoding) {
  5829. auto res = cli_.Get("/e%6edwith%");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. }
  5833. TEST_F(ServerTest, PercentEncodingUnicode) {
  5834. auto res = cli_.Get("/e%u006edwith%");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST_F(ServerTest, InvalidPercentEncoding) {
  5839. auto res = cli_.Get("/%endwith%");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5842. }
  5843. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5844. auto res = cli_.Get("/%uendwith%");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5847. }
  5848. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5849. auto res = cli_.Get("/hello?aaa=bbb%");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. }
  5853. TEST_F(ServerTest, PlusSignEncoding) {
  5854. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. EXPECT_EQ("a +b", res->body);
  5858. }
  5859. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5860. // This test simulates a potential DoS attack using many headers
  5861. // to verify our security fix prevents memory exhaustion
  5862. httplib::Headers attack_headers;
  5863. // Attempt to add many headers like an attacker would (200 headers to far
  5864. // exceed limit)
  5865. for (int i = 0; i < 200; i++) {
  5866. std::string name = "X-Attack-Header-" + std::to_string(i);
  5867. std::string value = "attack_payload_" + std::to_string(i);
  5868. attack_headers.emplace(name, value);
  5869. }
  5870. // Try to POST with excessive headers
  5871. cli_.set_keep_alive(true);
  5872. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5873. // Should either fail or return 400 Bad Request due to security limit
  5874. if (res) {
  5875. // If we get a response, it should be 400 Bad Request
  5876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5877. EXPECT_EQ("close", res->get_header_value("Connection"));
  5878. }
  5879. EXPECT_FALSE(cli_.is_socket_open());
  5880. }
  5881. TEST_F(ServerTest, MultipartFormData) {
  5882. UploadFormDataItems items = {
  5883. {"text1", "text default", "", ""},
  5884. {"text2", "aωb", "", ""},
  5885. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5886. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5887. {"file3", "", "", "application/octet-stream"},
  5888. {"file4", "", "", " application/json tmp-string "}};
  5889. auto res = cli_.Post("/multipart", items);
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. }
  5893. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5894. UploadFormDataItems items = {
  5895. {"text", "default text", "", ""},
  5896. {"multi_text1", "aaaaa", "", ""},
  5897. {"multi_text1", "bbbbb", "", ""},
  5898. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5899. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5900. "application/json"},
  5901. };
  5902. auto res = cli_.Post("/multipart/multi_file_values", items);
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. }
  5906. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. }
  5913. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5914. Request req;
  5915. req.method = "POST";
  5916. req.path = "/chunked";
  5917. std::string host_and_port;
  5918. host_and_port += HOST;
  5919. host_and_port += ":";
  5920. host_and_port += std::to_string(PORT);
  5921. req.headers.emplace("Host", host_and_port.c_str());
  5922. req.headers.emplace("Accept", "*/*");
  5923. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5924. req.headers.emplace("Content-Type", "text/plain");
  5925. req.headers.emplace("Content-Length", "0");
  5926. req.headers.emplace(
  5927. "Transfer-Encoding",
  5928. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5929. // Client does not chunk, so make a chunked body manually.
  5930. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5931. auto res = std::make_shared<Response>();
  5932. auto error = Error::Success;
  5933. auto ret = cli_.send(req, *res, error);
  5934. ASSERT_TRUE(ret);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. }
  5937. template <typename ClientT>
  5938. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5939. int expected_status) {
  5940. Request req;
  5941. req.method = "POST";
  5942. req.path = "/chunked";
  5943. std::string host_and_port;
  5944. host_and_port += HOST;
  5945. host_and_port += ":";
  5946. host_and_port += std::to_string(PORT);
  5947. req.headers.emplace("Host", host_and_port.c_str());
  5948. req.headers.emplace("Content-Length", "0");
  5949. req.headers.emplace("Transfer-Encoding", "chunked");
  5950. req.body = body;
  5951. auto res = std::make_shared<Response>();
  5952. auto error = Error::Success;
  5953. ASSERT_TRUE(cli.send(req, *res, error));
  5954. EXPECT_EQ(expected_status, res->status);
  5955. }
  5956. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5957. // rather than treat them as valid lengths.
  5958. template <typename ClientT>
  5959. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5960. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5961. }
  5962. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5963. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5964. }
  5965. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5966. expect_chunked_body_rejected(
  5967. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5968. }
  5969. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5970. // chunk-size line carries no CR, LF or other control character ahead of its
  5971. // terminator. Such a line must be refused rather than read as extension text.
  5972. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5973. expect_chunked_body_rejected(
  5974. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5975. }
  5976. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5977. expect_chunked_body_rejected(
  5978. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5979. }
  5980. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5981. expect_chunked_body_rejected(
  5982. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5983. }
  5984. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5985. // The literal stays split: a hex escape consumes every hex digit that
  5986. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5987. expect_chunked_body_rejected(
  5988. cli_, "4;a\x01"
  5989. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5990. }
  5991. TEST_F(ServerTest, AcceptsChunkExtension) {
  5992. expect_chunked_body_status(cli_,
  5993. "4;name=value\r\ndech\r\n"
  5994. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5995. "0;last\r\n\r\n",
  5996. StatusCode::OK_200);
  5997. }
  5998. TEST_F(ServerTest, GetStreamed2) {
  5999. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6002. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6003. EXPECT_EQ(true, res->has_header("Content-Range"));
  6004. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6005. EXPECT_EQ(std::string("ab"), res->body);
  6006. }
  6007. TEST_F(ServerTest, GetStreamed) {
  6008. auto res = cli_.Get("/streamed");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6012. EXPECT_EQ(std::string("aaabbb"), res->body);
  6013. }
  6014. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6015. auto res = cli_.Get("/streamed-without-length",
  6016. Headers{make_range_header({{0, -1}})});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(false, res->has_header("Content-Length"));
  6020. EXPECT_EQ(false, res->has_header("Content-Range"));
  6021. EXPECT_EQ(std::string("abcdefg"), res->body);
  6022. }
  6023. TEST_F(ServerTest, GetStreamedWithRange1) {
  6024. auto res =
  6025. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6029. EXPECT_EQ(true, res->has_header("Content-Range"));
  6030. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6031. EXPECT_EQ(std::string("def"), res->body);
  6032. }
  6033. TEST_F(ServerTest, GetStreamedWithRange2) {
  6034. auto res =
  6035. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6039. EXPECT_EQ(true, res->has_header("Content-Range"));
  6040. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6041. EXPECT_EQ(std::string("bcdefg"), res->body);
  6042. }
  6043. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6044. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6047. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6048. EXPECT_EQ(true, res->has_header("Content-Range"));
  6049. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6050. EXPECT_EQ(std::string("efg"), res->body);
  6051. }
  6052. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6053. auto res =
  6054. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6058. EXPECT_EQ(false, res->has_header("Content-Range"));
  6059. EXPECT_EQ(0U, res->body.size());
  6060. }
  6061. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6062. // Only a 206 is served as a partial representation. Under any other status
  6063. // `apply_ranges()` reported the full content length, so the body must match
  6064. // that header, and the content provider must never be asked for an offset
  6065. // outside the representation.
  6066. auto check = [&](int status, const char *range) {
  6067. auto path =
  6068. std::string("/streamed-with-range?status=") + std::to_string(status);
  6069. auto ctx = path + " Range: " + range;
  6070. auto res = cli_.Get(path, Headers{{"Range", range}});
  6071. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6072. EXPECT_EQ(status, res->status) << ctx;
  6073. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6075. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6076. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6077. };
  6078. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6079. check(403, "bytes=3-5");
  6080. // The offset is far past the representation.
  6081. check(403, "bytes=100000-100200");
  6082. // `first_pos` is still -1 here, and the bounds asserts in
  6083. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6084. check(403, "bytes=-3");
  6085. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6086. // multipart branch would have written one that is empty.
  6087. check(403, "bytes=1-2, 4-5");
  6088. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6089. // covers the whole representation.
  6090. check(200, "bytes=3-5");
  6091. check(200, "bytes=1-2, 4-5");
  6092. }
  6093. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6094. auto res =
  6095. cli_.Get("/streamed-with-range",
  6096. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6097. "92233720368547758079223372036854775807"}});
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6100. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6101. EXPECT_EQ(false, res->has_header("Content-Range"));
  6102. EXPECT_EQ(0U, res->body.size());
  6103. }
  6104. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6105. auto res = cli_.Get(
  6106. "/with-range",
  6107. Headers{{"Range",
  6108. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6109. {"Accept-Encoding", ""}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("abcdefg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6118. auto res = cli_.Get("/with-range", Headers{
  6119. {"Range", "bytes=0-"},
  6120. {"Accept-Encoding", ""},
  6121. });
  6122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6124. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6125. EXPECT_EQ(true, res->has_header("Content-Range"));
  6126. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6127. EXPECT_EQ(std::string("abcdefg"), res->body);
  6128. }
  6129. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6130. auto res = cli_.Get("/streamed-with-range",
  6131. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6134. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6135. EXPECT_EQ(false, res->has_header("Content-Range"));
  6136. EXPECT_EQ(267U, res->body.size());
  6137. // Check that both range contents are present
  6138. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6139. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6140. // Check that Content-Range headers are present for both ranges
  6141. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6142. std::string::npos);
  6143. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6144. std::string::npos);
  6145. }
  6146. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6147. Ranges ranges;
  6148. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6149. ranges.emplace_back(0, -1);
  6150. }
  6151. auto res = cli_.Get("/streamed-with-range?error",
  6152. Headers{{make_range_header(ranges)}});
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6156. EXPECT_EQ(false, res->has_header("Content-Range"));
  6157. EXPECT_EQ(0U, res->body.size());
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6160. auto res = cli_.Get("/streamed-with-range",
  6161. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_EQ(5U, res->body.size());
  6165. // Check that overlapping ranges are coalesced into a single range
  6166. EXPECT_EQ("bcdef", res->body);
  6167. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6168. // Should be single range, not multipart
  6169. EXPECT_TRUE(res->has_header("Content-Range"));
  6170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6171. }
  6172. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6173. auto res = cli_.Get("/streamed-with-range",
  6174. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ(268U, res->body.size());
  6178. // Check that both range contents are present
  6179. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6180. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6181. // Check that Content-Range headers are present for both ranges
  6182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6183. std::string::npos);
  6184. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6185. std::string::npos);
  6186. }
  6187. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6188. auto res = cli_.Get("/streamed-with-range",
  6189. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6192. EXPECT_EQ(269U, res->body.size());
  6193. // Check that both duplicate range contents are present
  6194. size_t first_abc = res->body.find("abc\r\n");
  6195. EXPECT_TRUE(first_abc != std::string::npos);
  6196. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6197. EXPECT_TRUE(second_abc != std::string::npos);
  6198. // Check that Content-Range headers are present for both ranges
  6199. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6200. EXPECT_TRUE(first_range != std::string::npos);
  6201. size_t second_range =
  6202. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6203. EXPECT_TRUE(second_range != std::string::npos);
  6204. }
  6205. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6206. auto res =
  6207. cli_.Get("/streamed-with-range?error",
  6208. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6212. EXPECT_EQ(false, res->has_header("Content-Range"));
  6213. EXPECT_EQ(0U, res->body.size());
  6214. }
  6215. TEST_F(ServerTest, GetStreamedEndless) {
  6216. uint64_t offset = 0;
  6217. auto res = cli_.Get("/streamed-cancel",
  6218. [&](const char * /*data*/, uint64_t data_length) {
  6219. if (offset < 100) {
  6220. offset += data_length;
  6221. return true;
  6222. }
  6223. return false;
  6224. });
  6225. ASSERT_TRUE(!res);
  6226. EXPECT_EQ(Error::Canceled, res.error());
  6227. }
  6228. TEST_F(ServerTest, ClientStop) {
  6229. std::atomic_size_t count{4};
  6230. std::vector<std::thread> threads;
  6231. for (auto i = count.load(); i != 0; --i) {
  6232. threads.emplace_back([&]() {
  6233. auto res = cli_.Get("/streamed-cancel",
  6234. [&](const char *, uint64_t) { return true; });
  6235. --count;
  6236. ASSERT_TRUE(!res);
  6237. EXPECT_TRUE(res.error() == Error::Canceled ||
  6238. res.error() == Error::Read || res.error() == Error::Write);
  6239. });
  6240. }
  6241. std::this_thread::sleep_for(std::chrono::seconds(2));
  6242. while (count != 0) {
  6243. cli_.stop();
  6244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6245. }
  6246. for (auto &t : threads) {
  6247. t.join();
  6248. }
  6249. }
  6250. TEST_F(ServerTest, GetWithRange1) {
  6251. auto res = cli_.Get("/with-range", Headers{
  6252. make_range_header({{3, 5}}),
  6253. {"Accept-Encoding", ""},
  6254. });
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6258. EXPECT_EQ(true, res->has_header("Content-Range"));
  6259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6260. EXPECT_EQ(std::string("def"), res->body);
  6261. }
  6262. TEST_F(ServerTest, GetWithRange2) {
  6263. auto res = cli_.Get("/with-range", Headers{
  6264. make_range_header({{1, -1}}),
  6265. {"Accept-Encoding", ""},
  6266. });
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6270. EXPECT_EQ(true, res->has_header("Content-Range"));
  6271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6272. EXPECT_EQ(std::string("bcdefg"), res->body);
  6273. }
  6274. TEST_F(ServerTest, GetWithRange3) {
  6275. auto res = cli_.Get("/with-range", Headers{
  6276. make_range_header({{0, 0}}),
  6277. {"Accept-Encoding", ""},
  6278. });
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6282. EXPECT_EQ(true, res->has_header("Content-Range"));
  6283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6284. EXPECT_EQ(std::string("a"), res->body);
  6285. }
  6286. TEST_F(ServerTest, GetWithRange4) {
  6287. auto res = cli_.Get("/with-range", Headers{
  6288. make_range_header({{-1, 2}}),
  6289. {"Accept-Encoding", ""},
  6290. });
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6294. EXPECT_EQ(true, res->has_header("Content-Range"));
  6295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6296. EXPECT_EQ(std::string("fg"), res->body);
  6297. }
  6298. TEST_F(ServerTest, GetWithRange5) {
  6299. auto res = cli_.Get("/with-range", Headers{
  6300. make_range_header({{0, 5}}),
  6301. {"Accept-Encoding", ""},
  6302. });
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6306. EXPECT_EQ(true, res->has_header("Content-Range"));
  6307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6308. EXPECT_EQ(std::string("abcdef"), res->body);
  6309. }
  6310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6311. auto res =
  6312. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetWithRangeMultipart) {
  6317. auto res =
  6318. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6321. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6322. EXPECT_EQ(false, res->has_header("Content-Range"));
  6323. EXPECT_EQ(267U, res->body.size());
  6324. }
  6325. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6326. auto res = cli_.Get("/with-range",
  6327. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6330. }
  6331. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6332. auto res = cli_.Get("/with-range-customized-response",
  6333. Headers{{make_range_header({{1, 2}})}});
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6336. EXPECT_EQ(true, res->has_header("Content-Length"));
  6337. EXPECT_EQ(false, res->has_header("Content-Range"));
  6338. EXPECT_EQ(JSON_DATA, res->body);
  6339. }
  6340. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6341. auto res = cli_.Get("/with-range-customized-response",
  6342. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6345. EXPECT_EQ(true, res->has_header("Content-Length"));
  6346. EXPECT_EQ(false, res->has_header("Content-Range"));
  6347. EXPECT_EQ(JSON_DATA, res->body);
  6348. }
  6349. TEST_F(ServerTest, Issue1772) {
  6350. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6353. }
  6354. TEST_F(ServerTest, Issue609) {
  6355. auto res = cli_.Delete("/issue609");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. EXPECT_EQ(std::string("ok"), res->body);
  6359. }
  6360. TEST_F(ServerTest, GetStreamedChunked) {
  6361. auto res = cli_.Get("/streamed-chunked");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. EXPECT_EQ(std::string("123456789"), res->body);
  6365. }
  6366. TEST_F(ServerTest, GetStreamedChunked2) {
  6367. auto res = cli_.Get("/streamed-chunked2");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::OK_200, res->status);
  6370. EXPECT_EQ(std::string("123456789"), res->body);
  6371. }
  6372. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6373. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ(std::string("123456789"), res->body);
  6377. EXPECT_TRUE(res->has_header("Trailer"));
  6378. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6379. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6380. // Trailers are now stored separately from headers (security fix)
  6381. EXPECT_EQ(2U, res->trailers.size());
  6382. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6383. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6384. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6385. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6386. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6387. // Verify trailers are NOT in headers (security verification)
  6388. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6389. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6390. }
  6391. TEST_F(ServerTest, LargeChunkedPost) {
  6392. Request req;
  6393. req.method = "POST";
  6394. req.path = "/large-chunked";
  6395. std::string host_and_port;
  6396. host_and_port += HOST;
  6397. host_and_port += ":";
  6398. host_and_port += std::to_string(PORT);
  6399. req.headers.emplace("Host", host_and_port.c_str());
  6400. req.headers.emplace("Accept", "*/*");
  6401. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6402. req.headers.emplace("Content-Type", "text/plain");
  6403. req.headers.emplace("Content-Length", "0");
  6404. req.headers.emplace("Transfer-Encoding", "chunked");
  6405. std::string long_string(30 * 1024u, 'a');
  6406. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6407. // Attempt to make a large enough post to exceed OS buffers, to test that
  6408. // the server handles short reads if the full chunk data isn't available.
  6409. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6410. auto res = std::make_shared<Response>();
  6411. auto error = Error::Success;
  6412. auto ret = cli_.send(req, *res, error);
  6413. ASSERT_TRUE(ret);
  6414. EXPECT_EQ(StatusCode::OK_200, res->status);
  6415. }
  6416. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6417. auto res = cli_.Get("/remote_addr");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6421. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6422. }
  6423. TEST_F(ServerTest, GetMethodLocalAddr) {
  6424. auto res = cli_.Get("/local_addr");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6428. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6429. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6430. }
  6431. TEST_F(ServerTest, HTTPResponseSplitting) {
  6432. auto res = cli_.Get("/http_response_splitting");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. }
  6436. TEST_F(ServerTest, SlowRequest) {
  6437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6438. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6439. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6440. }
  6441. #if 0
  6442. TEST_F(ServerTest, SlowPost) {
  6443. char buffer[64 * 1024];
  6444. memset(buffer, 0x42, sizeof(buffer));
  6445. auto res = cli_.Post(
  6446. "/slowpost", 64 * 1024 * 1024,
  6447. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6448. auto ret = sink.write(buffer, sizeof(buffer));
  6449. EXPECT_TRUE(ret);
  6450. return true;
  6451. },
  6452. "text/plain");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, SlowPostFail) {
  6457. char buffer[64 * 1024];
  6458. memset(buffer, 0x42, sizeof(buffer));
  6459. cli_.set_write_timeout(std::chrono::seconds(0));
  6460. auto res = cli_.Post(
  6461. "/slowpost", 64 * 1024 * 1024,
  6462. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6463. sink.write(buffer, sizeof(buffer));
  6464. return true;
  6465. },
  6466. "text/plain");
  6467. ASSERT_TRUE(!res);
  6468. EXPECT_EQ(Error::Write, res.error());
  6469. }
  6470. #endif
  6471. TEST_F(ServerTest, Put) {
  6472. auto res = cli_.Put("/put", "PUT", "text/plain");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::OK_200, res->status);
  6475. EXPECT_EQ("PUT", res->body);
  6476. }
  6477. TEST_F(ServerTest, PutWithContentProvider) {
  6478. auto res = cli_.Put(
  6479. "/put", 3,
  6480. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6481. sink.os << "PUT";
  6482. return true;
  6483. },
  6484. "text/plain");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::OK_200, res->status);
  6487. EXPECT_EQ("PUT", res->body);
  6488. }
  6489. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6490. auto res = cli_.Post(
  6491. "/post", 42,
  6492. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6493. return false;
  6494. },
  6495. "text/plain");
  6496. ASSERT_TRUE(!res);
  6497. EXPECT_EQ(Error::Canceled, res.error());
  6498. }
  6499. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6500. auto res = cli_.Put(
  6501. "/put",
  6502. [](size_t /*offset*/, DataSink &sink) {
  6503. sink.os << "PUT";
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::OK_200, res->status);
  6510. EXPECT_EQ("PUT", res->body);
  6511. }
  6512. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6513. auto res = cli_.Post(
  6514. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6515. "text/plain");
  6516. ASSERT_TRUE(!res);
  6517. EXPECT_EQ(Error::Canceled, res.error());
  6518. }
  6519. TEST_F(ServerTest, PostLoopBack) {
  6520. std::string body;
  6521. auto res = cli_.Post(
  6522. "/post-loopback", 9,
  6523. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6524. EXPECT_EQ(9u, length);
  6525. sink.write("123", 3);
  6526. sink.write("456", 3);
  6527. sink.write("789", 3);
  6528. return true;
  6529. },
  6530. "text/plain",
  6531. [&body](const char *data, size_t data_length) {
  6532. body.append(data, data_length);
  6533. return true;
  6534. });
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("123456789", body);
  6538. }
  6539. TEST_F(ServerTest, PutLoopBack) {
  6540. std::string body;
  6541. auto res = cli_.Put(
  6542. "/put-loopback", 9,
  6543. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6544. EXPECT_EQ(9u, length);
  6545. sink.write("123", 3);
  6546. sink.write("456", 3);
  6547. sink.write("789", 3);
  6548. return true;
  6549. },
  6550. "text/plain",
  6551. [&body](const char *data, size_t data_length) {
  6552. body.append(data, data_length);
  6553. return true;
  6554. });
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::OK_200, res->status);
  6557. EXPECT_EQ("123456789", body);
  6558. }
  6559. TEST_F(ServerTest, PatchLoopBack) {
  6560. std::string body;
  6561. auto res = cli_.Patch(
  6562. "/patch-loopback", 9,
  6563. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6564. EXPECT_EQ(9u, length);
  6565. sink.write("123", 3);
  6566. sink.write("456", 3);
  6567. sink.write("789", 3);
  6568. return true;
  6569. },
  6570. "text/plain",
  6571. [&body](const char *data, size_t data_length) {
  6572. body.append(data, data_length);
  6573. return true;
  6574. });
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. EXPECT_EQ("123456789", body);
  6578. }
  6579. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6580. std::string body;
  6581. auto res = cli_.Post(
  6582. "/post-loopback",
  6583. [](size_t /*offset*/, DataSink &sink) {
  6584. sink.write("123", 3);
  6585. sink.write("456", 3);
  6586. sink.write("789", 3);
  6587. sink.done();
  6588. return true;
  6589. },
  6590. "text/plain",
  6591. [&body](const char *data, size_t data_length) {
  6592. body.append(data, data_length);
  6593. return true;
  6594. });
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("123456789", body);
  6598. }
  6599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6600. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6601. cli_.set_compress(true);
  6602. auto res = cli_.Put(
  6603. "/put", 3,
  6604. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6605. sink.os << "PUT";
  6606. return true;
  6607. },
  6608. "text/plain");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. EXPECT_EQ("PUT", res->body);
  6612. }
  6613. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6614. cli_.set_compress(true);
  6615. auto res = cli_.Post(
  6616. "/post", 42,
  6617. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6618. return false;
  6619. },
  6620. "text/plain");
  6621. ASSERT_TRUE(!res);
  6622. EXPECT_EQ(Error::Canceled, res.error());
  6623. }
  6624. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6625. cli_.set_compress(true);
  6626. auto res = cli_.Put(
  6627. "/put",
  6628. [](size_t /*offset*/, DataSink &sink) {
  6629. sink.os << "PUT";
  6630. sink.done();
  6631. return true;
  6632. },
  6633. "text/plain");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("PUT", res->body);
  6637. }
  6638. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6639. cli_.set_compress(true);
  6640. auto res = cli_.Post(
  6641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6642. "text/plain");
  6643. ASSERT_TRUE(!res);
  6644. EXPECT_EQ(Error::Canceled, res.error());
  6645. }
  6646. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6647. cli_.set_compress(true);
  6648. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. EXPECT_EQ(LARGE_DATA, res->body);
  6652. }
  6653. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6656. Client cli(s.c_str());
  6657. cli.enable_server_certificate_verification(false);
  6658. #else
  6659. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6660. Client cli(s.c_str());
  6661. #endif
  6662. cli.set_compress(true);
  6663. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. EXPECT_EQ(StatusCode::OK_200, res->status);
  6666. EXPECT_EQ(LARGE_DATA, res->body);
  6667. // The compressed size should be less than a 10th of the original. May vary
  6668. // depending on the zlib library.
  6669. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6670. static_cast<uint64_t>(10 * 1024 * 1024));
  6671. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6672. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6673. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6674. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6675. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6676. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6677. #endif
  6678. }
  6679. TEST_F(ServerTest, PutContentWithDeflate) {
  6680. cli_.set_compress(false);
  6681. Headers headers;
  6682. headers.emplace("Content-Encoding", "deflate");
  6683. // PUT in deflate format:
  6684. auto res = cli_.Put("/put", headers,
  6685. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. EXPECT_EQ("PUT", res->body);
  6689. }
  6690. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6691. Headers headers;
  6692. headers.emplace("Accept-Encoding", "gzip, deflate");
  6693. auto res = cli_.Get("/streamed-chunked", headers);
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. EXPECT_EQ(std::string("123456789"), res->body);
  6697. }
  6698. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6699. Headers headers;
  6700. headers.emplace("Accept-Encoding", "gzip, deflate");
  6701. auto res = cli_.Get("/streamed-chunked2", headers);
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. EXPECT_EQ(std::string("123456789"), res->body);
  6705. }
  6706. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6707. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST(GzipDecompressor, ChunkedDecompression) {
  6712. std::string data;
  6713. for (size_t i = 0; i < 32 * 1024; ++i) {
  6714. data.push_back(static_cast<char>('a' + i % 26));
  6715. }
  6716. std::string compressed_data;
  6717. {
  6718. httplib::detail::gzip_compressor compressor;
  6719. bool result = compressor.compress(
  6720. data.data(), data.size(),
  6721. /*last=*/true,
  6722. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6723. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6724. compressed_data_size);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(result);
  6728. }
  6729. std::string decompressed_data;
  6730. {
  6731. httplib::detail::gzip_decompressor decompressor;
  6732. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6733. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6734. size_t chunk_size = 130;
  6735. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6736. chunk_begin += chunk_size) {
  6737. size_t current_chunk_size =
  6738. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6739. bool result = decompressor.decompress(
  6740. compressed_data.data() + chunk_begin, current_chunk_size,
  6741. [&](const char *decompressed_data_chunk,
  6742. size_t decompressed_data_chunk_size) {
  6743. decompressed_data.insert(decompressed_data.size(),
  6744. decompressed_data_chunk,
  6745. decompressed_data_chunk_size);
  6746. return true;
  6747. });
  6748. ASSERT_TRUE(result);
  6749. }
  6750. }
  6751. ASSERT_EQ(data, decompressed_data);
  6752. }
  6753. TEST(GzipDecompressor, DeflateDecompression) {
  6754. std::string original_text = "Raw deflate without gzip";
  6755. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6756. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6757. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6758. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6759. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6760. std::string decompressed_data;
  6761. {
  6762. httplib::detail::gzip_decompressor decompressor;
  6763. bool result = decompressor.decompress(
  6764. compressed_data.data(), compressed_data.size(),
  6765. [&](const char *decompressed_data_chunk,
  6766. size_t decompressed_data_chunk_size) {
  6767. decompressed_data.insert(decompressed_data.size(),
  6768. decompressed_data_chunk,
  6769. decompressed_data_chunk_size);
  6770. return true;
  6771. });
  6772. ASSERT_TRUE(result);
  6773. }
  6774. ASSERT_EQ(original_text, decompressed_data);
  6775. }
  6776. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6777. std::string original_text = "Raw deflate without gzip";
  6778. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6782. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6783. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6784. std::string decompressed_data;
  6785. {
  6786. httplib::detail::gzip_decompressor decompressor;
  6787. bool result = decompressor.decompress(
  6788. compressed_data.data(), compressed_data.size(),
  6789. [&](const char *decompressed_data_chunk,
  6790. size_t decompressed_data_chunk_size) {
  6791. decompressed_data.insert(decompressed_data.size(),
  6792. decompressed_data_chunk,
  6793. decompressed_data_chunk_size);
  6794. return true;
  6795. });
  6796. ASSERT_TRUE(result);
  6797. }
  6798. ASSERT_EQ(original_text, decompressed_data);
  6799. }
  6800. #endif
  6801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6802. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6803. Headers headers;
  6804. headers.emplace("Accept-Encoding", "br");
  6805. auto res = cli_.Get("/streamed-chunked", headers);
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ(std::string("123456789"), res->body);
  6809. }
  6810. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6811. Headers headers;
  6812. headers.emplace("Accept-Encoding", "br");
  6813. auto res = cli_.Get("/streamed-chunked2", headers);
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ(std::string("123456789"), res->body);
  6817. }
  6818. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6819. cli_.set_compress(true);
  6820. auto res = cli_.Put(
  6821. "/put", 3,
  6822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6823. sink.os << "PUT";
  6824. return true;
  6825. },
  6826. "text/plain");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("PUT", res->body);
  6830. }
  6831. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6832. cli_.set_compress(true);
  6833. auto res = cli_.Put(
  6834. "/put",
  6835. [](size_t /*offset*/, DataSink &sink) {
  6836. sink.os << "PUT";
  6837. sink.done();
  6838. return true;
  6839. },
  6840. "text/plain");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::OK_200, res->status);
  6843. EXPECT_EQ("PUT", res->body);
  6844. }
  6845. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6846. cli_.set_compress(true);
  6847. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ(LARGE_DATA, res->body);
  6851. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6852. }
  6853. #endif
  6854. TEST_F(ServerTest, Patch) {
  6855. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. EXPECT_EQ("PATCH", res->body);
  6859. }
  6860. TEST_F(ServerTest, Delete) {
  6861. auto res = cli_.Delete("/delete");
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_EQ(StatusCode::OK_200, res->status);
  6864. EXPECT_EQ("DELETE", res->body);
  6865. }
  6866. TEST_F(ServerTest, DeleteContentReceiver) {
  6867. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("content", res->body);
  6871. }
  6872. TEST_F(ServerTest, Options) {
  6873. auto res = cli_.Options("*");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6877. EXPECT_TRUE(res->body.empty());
  6878. }
  6879. TEST_F(ServerTest, URL) {
  6880. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(ServerTest, ArrayParam) {
  6885. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. }
  6889. TEST_F(ServerTest, ArrayParamValues) {
  6890. auto res =
  6891. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, NoMultipleHeaders) {
  6896. Headers headers = {{"Content-Length", "5"}};
  6897. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6898. "text/plain");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, PostContentReceiver) {
  6903. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, res->status);
  6906. ASSERT_EQ("content", res->body);
  6907. }
  6908. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6909. UploadFormDataItems items = {
  6910. {"text1", "text default", "", ""},
  6911. {"text2", "aωb", "", ""},
  6912. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6913. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6914. {"file3", "", "", "application/octet-stream"},
  6915. };
  6916. auto res = cli_.Post("/content_receiver", items);
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. }
  6920. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6921. UploadFormDataItems items = {
  6922. {"text1", "text default", "", ""},
  6923. {"text2", "aωb", "", ""},
  6924. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6925. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6926. {"file3", "", "", "application/octet-stream"},
  6927. };
  6928. auto boundary = std::string("+++++");
  6929. std::string body;
  6930. for (const auto &item : items) {
  6931. body += "--" + boundary + "\r\n";
  6932. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6933. if (!item.filename.empty()) {
  6934. body += "; filename=\"" + item.filename + "\"";
  6935. }
  6936. body += "\r\n";
  6937. if (!item.content_type.empty()) {
  6938. body += "Content-Type: " + item.content_type + "\r\n";
  6939. }
  6940. body += "\r\n";
  6941. body += item.content + "\r\n";
  6942. }
  6943. body += "--" + boundary + "--\r\n";
  6944. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6945. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST(MultipartFormDataTest, FieldEscaping) {
  6950. Server svr;
  6951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6952. const ContentReader &content_reader) {
  6953. ASSERT_TRUE(req.is_multipart_form_data());
  6954. std::vector<FormData> received;
  6955. content_reader(
  6956. [&](const FormData &file) {
  6957. received.push_back(file);
  6958. return true;
  6959. },
  6960. [&](const char *data, size_t data_length) {
  6961. received.back().content.append(data, data_length);
  6962. return true;
  6963. });
  6964. // '"', CR and LF in names and filenames are escaped following the
  6965. // WHATWG HTML standard, so each part still parses as a single part
  6966. // with no injected headers. Content types get CR/LF escaped too,
  6967. // while '"' (legal there, e.g. quoted charset) is preserved.
  6968. ASSERT_EQ(4U, received.size());
  6969. EXPECT_EQ("na%22me", received[0].name);
  6970. EXPECT_EQ("quoted name", received[0].content);
  6971. EXPECT_EQ("file", received[1].name);
  6972. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6973. received[1].filename);
  6974. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6975. EXPECT_EQ("injected", received[1].content);
  6976. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6977. EXPECT_EQ("my%22file.txt", received[2].filename);
  6978. EXPECT_EQ("cr lf name", received[2].content);
  6979. EXPECT_EQ("typed", received[3].name);
  6980. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6981. received[3].content_type);
  6982. EXPECT_EQ("typed content", received[3].content);
  6983. });
  6984. auto port = svr.bind_to_any_port("localhost");
  6985. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6986. auto se = detail::scope_exit([&] {
  6987. svr.stop();
  6988. t.join();
  6989. ASSERT_FALSE(svr.is_running());
  6990. });
  6991. svr.wait_until_ready();
  6992. Client cli("localhost", port);
  6993. UploadFormDataItems items = {
  6994. {"na\"me", "quoted name", "", ""},
  6995. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6996. "application/octet-stream"},
  6997. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6998. {"typed", "typed content", "",
  6999. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7000. };
  7001. auto res = cli.Post("/post", items);
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. }
  7005. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7006. const UploadFormDataItems items = {
  7007. {"name1", "Content 1", "", ""},
  7008. {"name2", "Content 2", "file2.txt", "text/plain"},
  7009. };
  7010. Server svr;
  7011. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7012. const ContentReader &content_reader) {
  7013. ASSERT_TRUE(req.is_multipart_form_data());
  7014. std::vector<FormData> received;
  7015. content_reader(
  7016. [&](const FormData &file) {
  7017. received.push_back(file);
  7018. return true;
  7019. },
  7020. [&](const char *data, size_t data_length) {
  7021. received.back().content.append(data, data_length);
  7022. return true;
  7023. });
  7024. ASSERT_EQ(2U, received.size());
  7025. EXPECT_EQ("name1", received[0].name);
  7026. EXPECT_EQ("Content 1", received[0].content);
  7027. EXPECT_EQ("name2", received[1].name);
  7028. EXPECT_EQ("Content 2", received[1].content);
  7029. EXPECT_EQ("file2.txt", received[1].filename);
  7030. EXPECT_EQ("text/plain", received[1].content_type);
  7031. });
  7032. auto port = svr.bind_to_any_port("localhost");
  7033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. ASSERT_FALSE(svr.is_running());
  7038. });
  7039. svr.wait_until_ready();
  7040. Client cli("localhost", port);
  7041. // Whole-body serialization with a generated boundary
  7042. {
  7043. MultipartFormDataWriter writer;
  7044. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7045. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7046. writer.content_type());
  7047. auto body = writer.serialize(items);
  7048. EXPECT_EQ(body.size(), writer.content_length(items));
  7049. auto res = cli.Post("/post", body, writer.content_type());
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. // Per-part framing with a custom boundary via a content provider
  7054. {
  7055. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7056. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7057. MultipartFormDataWriter writer("custom-boundary_123");
  7058. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7059. std::string body;
  7060. for (const auto &item : items) {
  7061. body += writer.item_begin(item);
  7062. body += item.content;
  7063. body += MultipartFormDataWriter::item_end();
  7064. }
  7065. body += writer.finish();
  7066. EXPECT_EQ(body.size(), writer.content_length(items));
  7067. auto res = cli.Post(
  7068. "/post", body.size(),
  7069. [&](size_t offset, size_t length, DataSink &sink) {
  7070. sink.write(body.data() + offset, length);
  7071. return true;
  7072. },
  7073. writer.content_type());
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. }
  7077. }
  7078. TEST_F(ServerTest, PostContentReceiverGzip) {
  7079. cli_.set_compress(true);
  7080. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. ASSERT_EQ(StatusCode::OK_200, res->status);
  7083. ASSERT_EQ("content", res->body);
  7084. }
  7085. TEST_F(ServerTest, PutContentReceiver) {
  7086. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. ASSERT_EQ(StatusCode::OK_200, res->status);
  7089. ASSERT_EQ("content", res->body);
  7090. }
  7091. TEST_F(ServerTest, PatchContentReceiver) {
  7092. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. ASSERT_EQ(StatusCode::OK_200, res->status);
  7095. ASSERT_EQ("content", res->body);
  7096. }
  7097. template <typename ClientType>
  7098. void TestWithHeadersAndContentReceiver(
  7099. ClientType &cli,
  7100. std::function<Result(ClientType &, const std::string &, const Headers &,
  7101. const std::string &, const std::string &,
  7102. ContentReceiver, DownloadProgress)>
  7103. request_func) {
  7104. Headers headers;
  7105. headers.emplace("X-Custom-Header", "test-value");
  7106. std::string received_body;
  7107. auto res = request_func(
  7108. cli, "/content_receiver", headers, "content", "application/json",
  7109. [&](const char *data, size_t data_length) {
  7110. received_body.append(data, data_length);
  7111. return true;
  7112. },
  7113. nullptr);
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("content", received_body);
  7117. }
  7118. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7119. #ifdef CPPHTTPLIB_SSL_ENABLED
  7120. using ClientT = SSLClient;
  7121. #else
  7122. using ClientT = Client;
  7123. #endif
  7124. TestWithHeadersAndContentReceiver<ClientT>(
  7125. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7126. const std::string &body, const std::string &content_type,
  7127. ContentReceiver receiver, DownloadProgress progress) {
  7128. return cli.Post(path, headers, body, content_type, receiver, progress);
  7129. });
  7130. }
  7131. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7132. #ifdef CPPHTTPLIB_SSL_ENABLED
  7133. using ClientT = SSLClient;
  7134. #else
  7135. using ClientT = Client;
  7136. #endif
  7137. TestWithHeadersAndContentReceiver<ClientT>(
  7138. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7139. const std::string &body, const std::string &content_type,
  7140. ContentReceiver receiver, DownloadProgress progress) {
  7141. return cli.Put(path, headers, body, content_type, receiver, progress);
  7142. });
  7143. }
  7144. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. using ClientT = SSLClient;
  7147. #else
  7148. using ClientT = Client;
  7149. #endif
  7150. TestWithHeadersAndContentReceiver<ClientT>(
  7151. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7152. const std::string &body, const std::string &content_type,
  7153. ContentReceiver receiver, DownloadProgress progress) {
  7154. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7155. });
  7156. }
  7157. template <typename ClientType>
  7158. void TestWithHeadersAndContentReceiverWithProgress(
  7159. ClientType &cli,
  7160. std::function<Result(ClientType &, const std::string &, const Headers &,
  7161. const std::string &, const std::string &,
  7162. ContentReceiver, DownloadProgress)>
  7163. request_func) {
  7164. Headers headers;
  7165. headers.emplace("X-Test-Header", "progress-test");
  7166. std::string received_body;
  7167. auto progress_called = false;
  7168. auto res = request_func(
  7169. cli, "/content_receiver", headers, "content", "text/plain",
  7170. [&](const char *data, size_t data_length) {
  7171. received_body.append(data, data_length);
  7172. return true;
  7173. },
  7174. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7175. progress_called = true;
  7176. return true;
  7177. });
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. EXPECT_EQ(StatusCode::OK_200, res->status);
  7180. EXPECT_EQ("content", received_body);
  7181. EXPECT_TRUE(progress_called);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverError(
  7224. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7225. const Headers &, const std::string &,
  7226. const std::string &, ContentReceiver)>
  7227. request_func) {
  7228. Headers headers;
  7229. headers.emplace("X-Error-Test", "true");
  7230. std::string received_body;
  7231. auto receiver_failed = false;
  7232. auto res =
  7233. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7234. [&](const char *data, size_t data_length) {
  7235. received_body.append(data, data_length);
  7236. receiver_failed = true;
  7237. return false;
  7238. });
  7239. ASSERT_FALSE(res);
  7240. EXPECT_TRUE(receiver_failed);
  7241. }
  7242. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7243. #ifdef CPPHTTPLIB_SSL_ENABLED
  7244. using ClientT = SSLClient;
  7245. #else
  7246. using ClientT = Client;
  7247. #endif
  7248. TestWithHeadersAndContentReceiverError<ClientT>(
  7249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7250. const std::string &body, const std::string &content_type,
  7251. ContentReceiver receiver) {
  7252. return cli.Post(path, headers, body, content_type, receiver);
  7253. });
  7254. }
  7255. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7256. #ifdef CPPHTTPLIB_SSL_ENABLED
  7257. using ClientT = SSLClient;
  7258. #else
  7259. using ClientT = Client;
  7260. #endif
  7261. TestWithHeadersAndContentReceiverError<ClientT>(
  7262. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7263. const std::string &body, const std::string &content_type,
  7264. ContentReceiver receiver) {
  7265. return cli.Put(path, headers, body, content_type, receiver);
  7266. });
  7267. }
  7268. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7269. #ifdef CPPHTTPLIB_SSL_ENABLED
  7270. using ClientT = SSLClient;
  7271. #else
  7272. using ClientT = Client;
  7273. #endif
  7274. TestWithHeadersAndContentReceiverError<ClientT>(
  7275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7276. const std::string &body, const std::string &content_type,
  7277. ContentReceiver receiver) {
  7278. return cli.Patch(path, headers, body, content_type, receiver);
  7279. });
  7280. }
  7281. TEST_F(ServerTest, PostQueryStringAndBody) {
  7282. auto res =
  7283. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. ASSERT_EQ(StatusCode::OK_200, res->status);
  7286. }
  7287. TEST_F(ServerTest, HTTP2Magic) {
  7288. Request req;
  7289. req.method = "PRI";
  7290. req.path = "*";
  7291. req.body = "SM";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7297. }
  7298. TEST_F(ServerTest, KeepAlive) {
  7299. auto res = cli_.Get("/hi");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_EQ("Hello World!", res->body);
  7304. res = cli_.Get("/hi");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7308. EXPECT_EQ("Hello World!", res->body);
  7309. res = cli_.Get("/hi");
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7313. EXPECT_EQ("Hello World!", res->body);
  7314. res = cli_.Get("/not-exist");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7317. res = cli_.Post("/empty", "", "text/plain");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7321. EXPECT_EQ("empty", res->body);
  7322. EXPECT_EQ("close", res->get_header_value("Connection"));
  7323. res = cli_.Post(
  7324. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7325. "text/plain");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7329. EXPECT_EQ("empty", res->body);
  7330. cli_.set_keep_alive(false);
  7331. res = cli_.Get("/last-request");
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. EXPECT_EQ("close", res->get_header_value("Connection"));
  7335. }
  7336. TEST_F(ServerTest, TooManyRedirect) {
  7337. cli_.set_follow_location(true);
  7338. auto res = cli_.Get("/redirect/0");
  7339. ASSERT_TRUE(!res);
  7340. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7341. }
  7342. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7343. Request req;
  7344. req.method = "FOOBAR";
  7345. req.path = "/hi";
  7346. cli_.set_keep_alive(true);
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7350. EXPECT_EQ("close", res->get_header_value("Connection"));
  7351. EXPECT_FALSE(cli_.is_socket_open());
  7352. }
  7353. TEST_F(ServerTest, CustomRouteReadsBody) {
  7354. const std::string xml =
  7355. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7356. Request req;
  7357. req.method = "PROPFIND";
  7358. req.path = "/dav/dir";
  7359. req.set_header("Depth", "1");
  7360. req.body = xml;
  7361. auto res = cli_.send(req);
  7362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7364. EXPECT_EQ(xml, res->body);
  7365. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7366. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7367. }
  7368. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7369. Request req;
  7370. req.method = "PROPFIND";
  7371. req.path = "/dav/42";
  7372. auto res = cli_.send(req);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7375. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7376. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7377. }
  7378. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7379. Request req;
  7380. req.method = "PROPFIND";
  7381. req.path = "/dav-re/123";
  7382. auto res = cli_.send(req);
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7385. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7388. Request req;
  7389. req.method = "MKCOL";
  7390. req.path = "/dav-mkcol";
  7391. auto res = cli_.send(req);
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::Created_201, res->status);
  7394. }
  7395. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7396. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7397. Request req;
  7398. req.method = "REPORT";
  7399. req.path = "/dav-report";
  7400. req.body = xml;
  7401. auto res = cli_.send(req);
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7404. EXPECT_EQ(xml, res->body);
  7405. }
  7406. // A content reader route must fire even when the request carries no body,
  7407. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7408. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7409. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7410. Request req;
  7411. req.method = "REPORT";
  7412. req.path = "/dav-report";
  7413. auto res = cli_.send(req);
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7416. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7417. }
  7418. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7419. Request req;
  7420. req.method = "PROPFIND";
  7421. req.path = "/not-dav";
  7422. auto res = cli_.send(req);
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7425. }
  7426. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7427. Request req;
  7428. req.method = "UNLOCK";
  7429. req.path = "/dav/dir";
  7430. cli_.set_keep_alive(true);
  7431. auto res = cli_.send(req);
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7434. EXPECT_EQ("close", res->get_header_value("Connection"));
  7435. EXPECT_FALSE(cli_.is_socket_open());
  7436. }
  7437. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7438. // The mount point serves this path, but only for GET and HEAD.
  7439. auto get_res = cli_.Get("/dir/index.html");
  7440. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7442. Request req;
  7443. req.method = "PROPFIND";
  7444. req.path = "/dir/index.html";
  7445. auto res = cli_.send(req);
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7448. }
  7449. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7450. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7451. cli_.set_keep_alive(true);
  7452. for (auto i = 0; i < 2; i++) {
  7453. Request req;
  7454. req.method = "PROPFIND";
  7455. req.path = "/dav/dir";
  7456. req.body = xml;
  7457. auto res = cli_.send(req);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7460. EXPECT_EQ(xml, res->body);
  7461. EXPECT_TRUE(cli_.is_socket_open());
  7462. }
  7463. // A built-in method must still be served on the same connection.
  7464. cli_.set_keep_alive(false);
  7465. auto res = cli_.Get("/hi");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("close", res->get_header_value("Connection"));
  7469. }
  7470. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7471. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7472. Request req;
  7473. req.method = "PROPFIND";
  7474. req.path = "/dav/dir";
  7475. req.set_header("Expect", "100-continue");
  7476. req.body = xml;
  7477. auto res = cli_.send(req);
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7480. EXPECT_EQ(xml, res->body);
  7481. }
  7482. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7484. TEST_F(ServerTest, Gzip) {
  7485. Headers headers;
  7486. headers.emplace("Accept-Encoding", "gzip, deflate");
  7487. auto res = cli_.Get("/compress", headers);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7491. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7493. "7890123456789012345678901234567890",
  7494. res->body);
  7495. EXPECT_EQ(StatusCode::OK_200, res->status);
  7496. }
  7497. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7498. Headers headers;
  7499. headers.emplace("Accept-Encoding", "gzip, deflate");
  7500. auto res = cli_.Get("/compress-with-charset", headers);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7503. EXPECT_EQ("application/json; charset=utf-8",
  7504. res->get_header_value("Content-Type"));
  7505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7506. "7890123456789012345678901234567890",
  7507. res->body);
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. }
  7510. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7511. Headers headers;
  7512. headers.emplace("Accept-Encoding", "");
  7513. auto res = cli_.Get("/compress", headers);
  7514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7516. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7517. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7518. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7519. "7890123456789012345678901234567890",
  7520. res->body);
  7521. EXPECT_EQ(StatusCode::OK_200, res->status);
  7522. }
  7523. TEST_F(ServerTest, GzipWithContentReceiver) {
  7524. Headers headers;
  7525. headers.emplace("Accept-Encoding", "gzip, deflate");
  7526. std::string body;
  7527. auto res = cli_.Get("/compress", headers,
  7528. [&](const char *data, uint64_t data_length) {
  7529. EXPECT_EQ(100U, data_length);
  7530. body.append(data, data_length);
  7531. return true;
  7532. });
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7536. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7537. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7538. "7890123456789012345678901234567890",
  7539. body);
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. }
  7542. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7543. Headers headers;
  7544. headers.emplace("Accept-Encoding", "gzip, deflate");
  7545. cli_.set_decompress(false);
  7546. auto res = cli_.Get("/compress", headers);
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7550. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7551. EXPECT_EQ(33U, res->body.size());
  7552. EXPECT_EQ(StatusCode::OK_200, res->status);
  7553. }
  7554. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7555. Headers headers;
  7556. headers.emplace("Accept-Encoding", "");
  7557. std::string body;
  7558. auto res = cli_.Get("/compress", headers,
  7559. [&](const char *data, uint64_t data_length) {
  7560. EXPECT_EQ(100U, data_length);
  7561. body.append(data, data_length);
  7562. return true;
  7563. });
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7567. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7569. "7890123456789012345678901234567890",
  7570. body);
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. }
  7573. TEST_F(ServerTest, NoGzip) {
  7574. Headers headers;
  7575. headers.emplace("Accept-Encoding", "gzip, deflate");
  7576. auto res = cli_.Get("/nocompress", headers);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7579. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7580. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7581. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7582. "7890123456789012345678901234567890",
  7583. res->body);
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. }
  7586. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7587. Headers headers;
  7588. headers.emplace("Accept-Encoding", "gzip, deflate");
  7589. std::string body;
  7590. auto res = cli_.Get("/nocompress", headers,
  7591. [&](const char *data, uint64_t data_length) {
  7592. EXPECT_EQ(100U, data_length);
  7593. body.append(data, data_length);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7597. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7601. "7890123456789012345678901234567890",
  7602. body);
  7603. EXPECT_EQ(StatusCode::OK_200, res->status);
  7604. }
  7605. TEST_F(ServerTest, MultipartFormDataGzip) {
  7606. UploadFormDataItems items = {
  7607. {"key1", "test", "", ""},
  7608. {"key2", "--abcdefg123", "", ""},
  7609. };
  7610. cli_.set_compress(true);
  7611. auto res = cli_.Post("/compress-multipart", items);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. }
  7615. #endif
  7616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7617. // Static file compression is opt-in, so these run their own server rather than
  7618. // flipping it on for the shared ServerTest fixture, which would silently
  7619. // rewrite what every other static file test is asserting.
  7620. class StaticFileCompressionTest : public ::testing::Test {
  7621. protected:
  7622. void TearDown() override {
  7623. if (t_.joinable()) {
  7624. svr_.stop();
  7625. t_.join();
  7626. }
  7627. }
  7628. int start(const std::function<void(Server &)> &configure = nullptr) {
  7629. // Serves the same tree as a directory of build-time compressed assets
  7630. // would be served: the mount point names the coding the files are already
  7631. // stored in. Registered before "/" so it is the one that matches.
  7632. svr_.set_mount_point("/pre-encoded", "./www",
  7633. {{"Content-Encoding", "gzip"}});
  7634. svr_.set_mount_point("/", "./www");
  7635. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7636. res.set_file_content("./www/dir/index.html", "text/html");
  7637. });
  7638. svr_.Get("/pre-encoded-file-content",
  7639. [](const Request & /*req*/, Response &res) {
  7640. res.set_header("Content-Encoding", "gzip");
  7641. res.set_file_content("./www/dir/index.html", "text/html");
  7642. });
  7643. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7644. res.set_content_provider(
  7645. 6, "text/plain",
  7646. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7647. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7648. return true;
  7649. });
  7650. });
  7651. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7652. res.set_content_provider(
  7653. 1000, "text/plain",
  7654. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7655. if (offset < 100) {
  7656. std::string data(100, 'A');
  7657. sink.write(data.data(), data.size());
  7658. return true;
  7659. }
  7660. std::this_thread::sleep_for(std::chrono::seconds(2));
  7661. std::string data(900, 'B');
  7662. sink.write(data.data(), data.size());
  7663. return true;
  7664. });
  7665. });
  7666. if (configure) { configure(svr_); }
  7667. auto port = svr_.bind_to_any_port(HOST);
  7668. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7669. svr_.wait_until_ready();
  7670. return port;
  7671. }
  7672. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7673. // Every file under ./www except 1MB.txt is smaller than the default
  7674. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7675. // it out of the way.
  7676. static void enable_without_floor(Server &svr) {
  7677. svr.set_static_file_compression(true);
  7678. svr.set_static_file_compression_min_length(0);
  7679. }
  7680. Server svr_;
  7681. std::thread t_;
  7682. };
  7683. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7684. auto port = start();
  7685. Client cli(HOST, port);
  7686. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7690. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7691. EXPECT_EQ(1048576U, res->body.size());
  7692. }
  7693. TEST_F(StaticFileCompressionTest, MountPoint) {
  7694. auto port = start(enable);
  7695. Client cli(HOST, port);
  7696. cli.set_decompress(false);
  7697. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7702. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7703. // The response stays self-delimiting: a length, not a chunked body.
  7704. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7705. EXPECT_EQ(std::to_string(res->body.size()),
  7706. res->get_header_value("Content-Length"));
  7707. EXPECT_LT(res->body.size(), 1048576U);
  7708. EXPECT_FALSE(res->body.empty());
  7709. }
  7710. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7711. auto port = start(enable);
  7712. Client cli(HOST, port);
  7713. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7717. EXPECT_EQ(1048576U, res->body.size());
  7718. }
  7719. TEST_F(StaticFileCompressionTest, FileContent) {
  7720. auto port = start(enable_without_floor);
  7721. Client cli(HOST, port);
  7722. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7726. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7727. EXPECT_EQ(104U, res->body.size());
  7728. }
  7729. // A handler that serves an already-encoded file names the coding itself. The
  7730. // file-backed path decided its coding from Accept-Encoding and the content
  7731. // type alone, so it compressed the stored bytes a second time and appended a
  7732. // second Content-Encoding field line.
  7733. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7734. auto port = start(enable_without_floor);
  7735. Client cli(HOST, port);
  7736. cli.set_decompress(false);
  7737. auto res = cli.Get("/pre-encoded-file-content",
  7738. Headers{{"Accept-Encoding", "gzip"}});
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::OK_200, res->status);
  7741. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7743. // Vary belongs to a coding the server chose, and it chose none here.
  7744. EXPECT_FALSE(res->has_header("Vary"));
  7745. // The file travels exactly as it is stored on disk.
  7746. EXPECT_EQ(104U, res->body.size());
  7747. }
  7748. // The 1MB file clears the default floor, so this one runs the configuration a
  7749. // deployment would actually have.
  7750. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7751. auto port = start(enable);
  7752. Client cli(HOST, port);
  7753. cli.set_decompress(false);
  7754. auto res =
  7755. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7760. EXPECT_FALSE(res->has_header("Vary"));
  7761. EXPECT_EQ(1048576U, res->body.size());
  7762. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7763. }
  7764. TEST_F(StaticFileCompressionTest, Head) {
  7765. auto port = start(enable);
  7766. Client cli(HOST, port);
  7767. cli.set_decompress(false);
  7768. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7769. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7770. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7774. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7775. // HEAD still reports the size a GET would return.
  7776. EXPECT_EQ(get->get_header_value("Content-Length"),
  7777. res->get_header_value("Content-Length"));
  7778. EXPECT_TRUE(res->body.empty());
  7779. }
  7780. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7781. auto port = start(enable);
  7782. Client cli(HOST, port);
  7783. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7784. {"Accept-Encoding", "gzip"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7787. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7788. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7790. EXPECT_EQ("cd", res->body);
  7791. }
  7792. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7793. auto port = start(enable);
  7794. Client cli(HOST, port);
  7795. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7799. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7800. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7801. }
  7802. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7803. auto port = start(enable);
  7804. Client cli(HOST, port);
  7805. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7810. EXPECT_TRUE(res->body.empty());
  7811. }
  7812. TEST_F(StaticFileCompressionTest, MinLength) {
  7813. auto port = start(enable);
  7814. Client cli(HOST, port);
  7815. // 104 bytes, well under the default floor. Compressing it would add the
  7816. // gzip header and trailer to a body that already fits in one packet.
  7817. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::OK_200, res->status);
  7820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7821. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7822. }
  7823. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7824. auto port = start([](Server &svr) {
  7825. svr.set_static_file_compression(true);
  7826. svr.set_static_file_compression_min_length(1);
  7827. });
  7828. Client cli(HOST, port);
  7829. cli.set_decompress(false);
  7830. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7833. // A 9-byte file comes back larger than it went in, because gzip's header and
  7834. // trailer outweigh anything deflate can save. That is the end of the range
  7835. // the floor exists to keep out.
  7836. EXPECT_GT(res->body.size(), 9U);
  7837. }
  7838. TEST_F(StaticFileCompressionTest, MaxLength) {
  7839. auto port = start([](Server &svr) {
  7840. svr.set_static_file_compression(true);
  7841. svr.set_static_file_compression_min_length(0);
  7842. svr.set_static_file_compression_max_length(1024);
  7843. });
  7844. Client cli(HOST, port);
  7845. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7846. // defines `small` as a macro on Windows.
  7847. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7848. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7849. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7850. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7851. // Under it: compressed.
  7852. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7853. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7854. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7855. }
  7856. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7857. auto port = start(enable_without_floor);
  7858. Client cli(HOST, port);
  7859. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7860. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7861. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7862. auto identity_etag = identity->get_header_value("ETag");
  7863. ASSERT_FALSE(identity_etag.empty());
  7864. auto gzipped =
  7865. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7866. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7867. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7868. auto gzip_etag = gzipped->get_header_value("ETag");
  7869. ASSERT_FALSE(gzip_etag.empty());
  7870. // Two representations, two validators.
  7871. EXPECT_NE(identity_etag, gzip_etag);
  7872. // Each one revalidates against the request that would produce it...
  7873. auto fresh =
  7874. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7875. {"If-None-Match", gzip_etag}});
  7876. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7877. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7878. auto fresh_identity =
  7879. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7880. {"If-None-Match", identity_etag}});
  7881. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7882. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7883. // ...and not against the other representation.
  7884. auto crossed =
  7885. cli.Get("/dir/index.html",
  7886. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7887. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7888. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7889. }
  7890. // The opt-in covers responses the server reads off disk itself. A caller's own
  7891. // known-length provider keeps its Content-Length and, more importantly, keeps
  7892. // delivering incrementally: routing it through a compressor would hold every
  7893. // write back until zlib's window filled.
  7894. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7895. auto port = start(enable);
  7896. Client cli(HOST, port);
  7897. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7901. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7902. EXPECT_EQ("aaabbb", res->body);
  7903. }
  7904. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7905. auto port = start(enable);
  7906. Client cli(HOST, port);
  7907. cli.set_read_timeout(1, 0);
  7908. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7909. Headers{{"Accept-Encoding", "gzip"}});
  7910. ASSERT_TRUE(handle.is_valid());
  7911. // The provider writes 100 bytes and then stalls for longer than the read
  7912. // timeout. Those first bytes have to arrive anyway: run the response through
  7913. // a compressor and zlib holds them until its window fills, so the read would
  7914. // come back empty instead.
  7915. char buf[256];
  7916. auto n = handle.read(buf, sizeof(buf));
  7917. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7918. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7919. }
  7920. #endif
  7921. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7922. TEST_F(ServerTest, Brotli) {
  7923. Headers headers;
  7924. headers.emplace("Accept-Encoding", "br");
  7925. auto res = cli_.Get("/compress", headers);
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. res->body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. #endif
  7936. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7937. TEST_F(ServerTest, Zstd) {
  7938. Headers headers;
  7939. headers.emplace("Accept-Encoding", "zstd");
  7940. auto res = cli_.Get("/compress", headers);
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7944. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7946. "7890123456789012345678901234567890",
  7947. res->body);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7951. Headers headers;
  7952. headers.emplace("Accept-Encoding", "");
  7953. auto res = cli_.Get("/compress", headers);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7958. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7959. "7890123456789012345678901234567890",
  7960. res->body);
  7961. EXPECT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "zstd");
  7966. std::string body;
  7967. auto res = cli_.Get("/compress", headers,
  7968. [&](const char *data, uint64_t data_length) {
  7969. EXPECT_EQ(100U, data_length);
  7970. body.append(data, data_length);
  7971. return true;
  7972. });
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7978. "7890123456789012345678901234567890",
  7979. body);
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7983. Headers headers;
  7984. headers.emplace("Accept-Encoding", "zstd");
  7985. cli_.set_decompress(false);
  7986. auto res = cli_.Get("/compress", headers);
  7987. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7988. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7989. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7990. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. ASSERT_EQ(26U, res->body.size());
  7997. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7998. 0);
  7999. }
  8000. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8001. Headers headers;
  8002. headers.emplace("Accept-Encoding", "");
  8003. std::string body;
  8004. auto res = cli_.Get("/compress", headers,
  8005. [&](const char *data, uint64_t data_length) {
  8006. EXPECT_EQ(100U, data_length);
  8007. body.append(data, data_length);
  8008. return true;
  8009. });
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8012. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8015. "7890123456789012345678901234567890",
  8016. body);
  8017. EXPECT_EQ(StatusCode::OK_200, res->status);
  8018. }
  8019. TEST_F(ServerTest, NoZstd) {
  8020. Headers headers;
  8021. headers.emplace("Accept-Encoding", "zstd");
  8022. auto res = cli_.Get("/nocompress", headers);
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8028. "7890123456789012345678901234567890",
  8029. res->body);
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. }
  8032. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8033. Headers headers;
  8034. headers.emplace("Accept-Encoding", "zstd");
  8035. std::string body;
  8036. auto res = cli_.Get("/nocompress", headers,
  8037. [&](const char *data, uint64_t data_length) {
  8038. EXPECT_EQ(100U, data_length);
  8039. body.append(data, data_length);
  8040. return true;
  8041. });
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8044. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8047. "7890123456789012345678901234567890",
  8048. body);
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. }
  8051. // TODO: How to enable zstd ??
  8052. TEST_F(ServerTest, MultipartFormDataZstd) {
  8053. UploadFormDataItems items = {
  8054. {"key1", "test", "", ""},
  8055. {"key2", "--abcdefg123", "", ""},
  8056. };
  8057. Headers headers;
  8058. headers.emplace("Accept-Encoding", "zstd");
  8059. cli_.set_compress(true);
  8060. auto res = cli_.Post("/compress-multipart", headers, items);
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. }
  8064. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8065. Headers headers;
  8066. headers.emplace("Accept-Encoding", "zstd");
  8067. cli_.set_compress(true);
  8068. auto res = cli_.Put(
  8069. "/put", headers, 3,
  8070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8071. sink.os << "PUT";
  8072. return true;
  8073. },
  8074. "text/plain");
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ(StatusCode::OK_200, res->status);
  8077. EXPECT_EQ("PUT", res->body);
  8078. }
  8079. // Pre-compression logging tests
  8080. TEST_F(ServerTest, PreCompressionLogging) {
  8081. // Test data for compression (matches the actual /compress endpoint content)
  8082. const std::string test_content =
  8083. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8084. "3456789012345678901234567890";
  8085. // Variables to capture logging data
  8086. std::string pre_compression_body;
  8087. std::string pre_compression_content_type;
  8088. std::string pre_compression_content_encoding;
  8089. std::string post_compression_body;
  8090. std::string post_compression_content_type;
  8091. std::string post_compression_content_encoding;
  8092. // Set up pre-compression logger
  8093. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8094. const Response &res) {
  8095. pre_compression_body = res.body;
  8096. pre_compression_content_type = res.get_header_value("Content-Type");
  8097. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8098. });
  8099. // Set up post-compression logger
  8100. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8101. post_compression_body = res.body;
  8102. post_compression_content_type = res.get_header_value("Content-Type");
  8103. post_compression_content_encoding =
  8104. res.get_header_value("Content-Encoding");
  8105. });
  8106. // Test with gzip compression
  8107. Headers headers;
  8108. headers.emplace("Accept-Encoding", "gzip");
  8109. auto res = cli_.Get("/compress", headers);
  8110. // Verify response was compressed
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8114. // Verify pre-compression logger captured uncompressed content
  8115. EXPECT_EQ(test_content, pre_compression_body);
  8116. EXPECT_EQ("text/plain", pre_compression_content_type);
  8117. EXPECT_TRUE(pre_compression_content_encoding
  8118. .empty()); // No encoding header before compression
  8119. // Verify post-compression logger captured compressed content
  8120. EXPECT_NE(test_content,
  8121. post_compression_body); // Should be different after compression
  8122. EXPECT_EQ("text/plain", post_compression_content_type);
  8123. EXPECT_EQ("gzip", post_compression_content_encoding);
  8124. // Verify compressed content is smaller
  8125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8126. }
  8127. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8128. const std::string test_content =
  8129. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8130. "3456789012345678901234567890";
  8131. std::string pre_compression_body;
  8132. std::string post_compression_body;
  8133. svr_.set_pre_compression_logger(
  8134. [&](const Request & /*req*/, const Response &res) {
  8135. pre_compression_body = res.body;
  8136. });
  8137. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8138. post_compression_body = res.body;
  8139. });
  8140. Headers headers;
  8141. headers.emplace("Accept-Encoding", "br");
  8142. auto res = cli_.Get("/compress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8146. // Verify pre-compression content is uncompressed
  8147. EXPECT_EQ(test_content, pre_compression_body);
  8148. // Verify post-compression content is compressed
  8149. EXPECT_NE(test_content, post_compression_body);
  8150. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8151. }
  8152. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8153. const std::string test_content =
  8154. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8155. "3456789012345678901234567890";
  8156. std::string pre_compression_body;
  8157. std::string post_compression_body;
  8158. svr_.set_pre_compression_logger(
  8159. [&](const Request & /*req*/, const Response &res) {
  8160. pre_compression_body = res.body;
  8161. });
  8162. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8163. post_compression_body = res.body;
  8164. });
  8165. // Request without compression (use /nocompress endpoint)
  8166. Headers headers;
  8167. auto res = cli_.Get("/nocompress", headers);
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8171. // Pre-compression logger should not be called when no compression is applied
  8172. EXPECT_TRUE(
  8173. pre_compression_body.empty()); // Pre-compression logger not called
  8174. EXPECT_EQ(
  8175. test_content,
  8176. post_compression_body); // Post-compression logger captures final content
  8177. }
  8178. TEST_F(ServerTest, LoggerSeesContentLength) {
  8179. size_t logged_content_length = 0;
  8180. std::string logged_content_length_header;
  8181. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8182. logged_content_length = res.content_length_;
  8183. logged_content_length_header = res.get_header_value("Content-Length");
  8184. });
  8185. auto res = cli_.Get("/nocompress");
  8186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8187. EXPECT_EQ(StatusCode::OK_200, res->status);
  8188. EXPECT_EQ(res->body.size(), logged_content_length);
  8189. EXPECT_EQ(std::to_string(logged_content_length),
  8190. logged_content_length_header);
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. bool pre_logger_called = false;
  8198. // Set only pre-compression logger
  8199. svr_.set_pre_compression_logger(
  8200. [&](const Request & /*req*/, const Response &res) {
  8201. pre_compression_body = res.body;
  8202. pre_logger_called = true;
  8203. });
  8204. Headers headers;
  8205. headers.emplace("Accept-Encoding", "gzip");
  8206. auto res = cli_.Get("/compress", headers);
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8210. // Verify pre-compression logger was called
  8211. EXPECT_TRUE(pre_logger_called);
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. }
  8214. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8215. {
  8216. // Test with Expect: 100-continue header - success case
  8217. // Server returns 100 Continue, client sends body, server returns 200 OK
  8218. Request req;
  8219. req.method = "POST";
  8220. req.path = "/post-large";
  8221. req.set_header("Expect", "100-continue");
  8222. req.body = LARGE_DATA;
  8223. Response res;
  8224. auto error = Error::Success;
  8225. cli_.set_keep_alive(true);
  8226. auto ret = cli_.send(req, res, error);
  8227. EXPECT_TRUE(ret);
  8228. EXPECT_EQ(StatusCode::OK_200, res.status);
  8229. EXPECT_EQ(LARGE_DATA, res.body);
  8230. }
  8231. {
  8232. // Test with Expect: 100-continue header - error case
  8233. // Client should not send the body when server returns an error
  8234. Request req;
  8235. req.method = "POST";
  8236. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8237. req.set_header("Expect", "100-continue");
  8238. req.body = LARGE_DATA;
  8239. Response res;
  8240. auto error = Error::Success;
  8241. auto start = std::chrono::high_resolution_clock::now();
  8242. cli_.set_keep_alive(true);
  8243. auto ret = cli_.send(req, res, error);
  8244. auto end = std::chrono::high_resolution_clock::now();
  8245. auto elapsed =
  8246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8247. .count();
  8248. // With Expect: 100-continue, request completes successfully but with error
  8249. EXPECT_TRUE(ret);
  8250. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8251. EXPECT_EQ("close", res.get_header_value("Connection"));
  8252. EXPECT_FALSE(cli_.is_socket_open());
  8253. EXPECT_LE(elapsed, 2000);
  8254. }
  8255. {
  8256. // Send an extra GET request to ensure error recovery without hanging
  8257. Request req;
  8258. req.method = "GET";
  8259. req.path = "/hi";
  8260. auto start = std::chrono::high_resolution_clock::now();
  8261. auto res = cli_.send(req);
  8262. auto end = std::chrono::high_resolution_clock::now();
  8263. auto elapsed =
  8264. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8265. .count();
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("Hello World!", res->body);
  8269. EXPECT_LE(elapsed, 500);
  8270. }
  8271. }
  8272. TEST(ZstdDecompressor, ChunkedDecompression) {
  8273. std::string data;
  8274. for (size_t i = 0; i < 32 * 1024; ++i) {
  8275. data.push_back(static_cast<char>('a' + i % 26));
  8276. }
  8277. std::string compressed_data;
  8278. {
  8279. httplib::detail::zstd_compressor compressor;
  8280. bool result = compressor.compress(
  8281. data.data(), data.size(),
  8282. /*last=*/true,
  8283. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8284. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8285. compressed_data_size);
  8286. return true;
  8287. });
  8288. ASSERT_TRUE(result);
  8289. }
  8290. std::string decompressed_data;
  8291. {
  8292. httplib::detail::zstd_decompressor decompressor;
  8293. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8294. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8295. size_t chunk_size = 130;
  8296. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8297. chunk_begin += chunk_size) {
  8298. size_t current_chunk_size =
  8299. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8300. bool result = decompressor.decompress(
  8301. compressed_data.data() + chunk_begin, current_chunk_size,
  8302. [&](const char *decompressed_data_chunk,
  8303. size_t decompressed_data_chunk_size) {
  8304. decompressed_data.insert(decompressed_data.size(),
  8305. decompressed_data_chunk,
  8306. decompressed_data_chunk_size);
  8307. return true;
  8308. });
  8309. ASSERT_TRUE(result);
  8310. }
  8311. }
  8312. ASSERT_EQ(data, decompressed_data);
  8313. }
  8314. TEST(ZstdDecompressor, Decompress) {
  8315. std::string original_text = "Compressed with ZSTD";
  8316. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8317. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8318. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8319. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8320. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8321. std::string decompressed_data;
  8322. {
  8323. httplib::detail::zstd_decompressor decompressor;
  8324. bool result = decompressor.decompress(
  8325. compressed_data.data(), compressed_data.size(),
  8326. [&](const char *decompressed_data_chunk,
  8327. size_t decompressed_data_chunk_size) {
  8328. decompressed_data.insert(decompressed_data.size(),
  8329. decompressed_data_chunk,
  8330. decompressed_data_chunk_size);
  8331. return true;
  8332. });
  8333. ASSERT_TRUE(result);
  8334. }
  8335. ASSERT_EQ(original_text, decompressed_data);
  8336. }
  8337. #endif
  8338. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8339. // separate chunks so that the server sees each part in its own read(). Used to
  8340. // place a read boundary at a specific offset of a request body.
  8341. static bool send_request_in_parts(time_t read_timeout_sec,
  8342. const std::vector<std::string> &parts,
  8343. std::string *resp = nullptr,
  8344. int port = PORT) {
  8345. auto error = Error::Success;
  8346. auto client_sock = detail::create_client_socket(
  8347. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8348. /*connection_timeout_sec=*/5, 0,
  8349. /*read_timeout_sec=*/5, 0,
  8350. /*write_timeout_sec=*/5, 0, std::string(), error);
  8351. if (client_sock == INVALID_SOCKET) { return false; }
  8352. auto ret = detail::process_client_socket(
  8353. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8354. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8355. for (size_t i = 0; i < parts.size(); i++) {
  8356. const auto &part = parts[i];
  8357. if (part.size() !=
  8358. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8359. return false;
  8360. }
  8361. if (i + 1 < parts.size()) {
  8362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8363. }
  8364. }
  8365. char buf[512];
  8366. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8367. while (line_reader.getline()) {
  8368. if (resp) { *resp += line_reader.ptr(); }
  8369. }
  8370. return true;
  8371. });
  8372. detail::close_socket(client_sock);
  8373. return ret;
  8374. }
  8375. // Sends a raw request to a server listening at HOST:PORT.
  8376. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8377. std::string *resp = nullptr, int port = PORT) {
  8378. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8379. }
  8380. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8381. Server svr;
  8382. std::string header_value;
  8383. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8384. header_value = req.get_header_value("foo");
  8385. res.set_content("ok", "text/plain");
  8386. });
  8387. thread t = thread([&] { svr.listen(HOST, PORT); });
  8388. auto se = detail::scope_exit([&] {
  8389. svr.stop();
  8390. t.join();
  8391. ASSERT_FALSE(svr.is_running());
  8392. });
  8393. svr.wait_until_ready();
  8394. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8395. // like characters are not treated the same - use vertical tab and escape.
  8396. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8397. "foo: \t \v bar \x1B\t \r\n"
  8398. "Connection: close\r\n"
  8399. "\r\n";
  8400. std::string res;
  8401. ASSERT_TRUE(send_request(5, req, &res));
  8402. EXPECT_EQ(header_value, "");
  8403. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8404. }
  8405. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8406. Server svr;
  8407. std::string received;
  8408. svr.Get("/order", [&](const Request &req, Response &res) {
  8409. received = entries_to_string(req.headers);
  8410. res.set_content("ok", "text/plain");
  8411. });
  8412. auto port = svr.bind_to_any_port(HOST);
  8413. thread t = thread([&] { svr.listen_after_bind(); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. const std::string req = "GET /order HTTP/1.1\r\n"
  8421. "X-First: 1\r\n"
  8422. "X-Dup: a\r\n"
  8423. "X-Second: 2\r\n"
  8424. "X-Dup: b\r\n"
  8425. "Connection: close\r\n"
  8426. "\r\n";
  8427. std::string res;
  8428. ASSERT_TRUE(send_request(5, req, &res, port));
  8429. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8430. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8431. }
  8432. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8433. Server svr;
  8434. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8435. res.set_header("Set-Cookie", "first=1");
  8436. res.set_header("X-Between", "y");
  8437. res.set_header("Set-Cookie", "second=2");
  8438. res.set_content("ok", "text/plain");
  8439. });
  8440. auto port = svr.bind_to_any_port(HOST);
  8441. thread t = thread([&] { svr.listen_after_bind(); });
  8442. auto se = detail::scope_exit([&] {
  8443. svr.stop();
  8444. t.join();
  8445. ASSERT_FALSE(svr.is_running());
  8446. });
  8447. svr.wait_until_ready();
  8448. Client cli(HOST, port);
  8449. auto res = cli.Get("/cookies");
  8450. ASSERT_TRUE(res);
  8451. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8452. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8453. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8454. }
  8455. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8456. Server svr;
  8457. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8458. auto i = new int(0);
  8459. res.set_header("Trailer", "X-Safe, X-Reflected");
  8460. res.set_chunked_content_provider(
  8461. "text/plain",
  8462. [i](size_t /*offset*/, DataSink &sink) {
  8463. if (*i == 0) {
  8464. sink.os << "body";
  8465. } else {
  8466. Headers trailer;
  8467. // A valid trailer that must survive.
  8468. trailer.emplace("X-Safe", "safe");
  8469. // Attacker-controlled value carrying CR/LF (response splitting).
  8470. trailer.emplace("X-Reflected",
  8471. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8472. // Attacker-controlled name carrying CR/LF.
  8473. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8474. sink.done_with_trailer(trailer);
  8475. }
  8476. (*i)++;
  8477. return true;
  8478. },
  8479. [i](bool /*success*/) { delete i; });
  8480. });
  8481. thread t = thread([&] { svr.listen(HOST, PORT); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8489. "Host: " + HOST +
  8490. "\r\n"
  8491. "Connection: close\r\n"
  8492. "\r\n";
  8493. std::string res;
  8494. ASSERT_TRUE(send_request(5, req, &res));
  8495. // The injected fields must not appear anywhere in the raw response.
  8496. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8497. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8498. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8499. // Invalid trailers are dropped entirely, matching set_header().
  8500. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8501. // The valid trailer still passes through.
  8502. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8503. }
  8504. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8505. Server svr;
  8506. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8507. // res.headers is a public field an application can populate directly,
  8508. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8509. // A valid header that must survive.
  8510. res.headers.emplace("X-Safe", "safe");
  8511. // Attacker-controlled value carrying CR/LF (response splitting).
  8512. res.headers.emplace("X-Reflected",
  8513. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8514. // Attacker-controlled name carrying CR/LF.
  8515. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8516. res.set_content("body", "text/plain");
  8517. });
  8518. thread t = thread([&] { svr.listen(HOST, PORT); });
  8519. auto se = detail::scope_exit([&] {
  8520. svr.stop();
  8521. t.join();
  8522. ASSERT_FALSE(svr.is_running());
  8523. });
  8524. svr.wait_until_ready();
  8525. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8526. "Host: " + HOST +
  8527. "\r\n"
  8528. "Connection: close\r\n"
  8529. "\r\n";
  8530. std::string res;
  8531. ASSERT_TRUE(send_request(5, req, &res));
  8532. // The injected fields must not appear anywhere in the raw response.
  8533. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8534. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8535. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8536. // Invalid headers are dropped entirely, matching set_header().
  8537. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8538. // The valid header still passes through.
  8539. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8540. }
  8541. // Forward declaration: in split builds split.py strips `inline` and moves the
  8542. // definition into httplib.cc, so detail::write_request_line is not visible from
  8543. // the public httplib.h. Re-declaring it here lets the tests link against the
  8544. // symbol in both header-only and split builds.
  8545. namespace httplib {
  8546. namespace detail {
  8547. ssize_t write_request_line(Stream &strm, const std::string &method,
  8548. const std::string &path);
  8549. } // namespace detail
  8550. } // namespace httplib
  8551. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8552. // A well-formed target is written verbatim.
  8553. {
  8554. detail::BufferStream strm;
  8555. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8556. EXPECT_GT(n, 0);
  8557. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8558. }
  8559. // A target carrying CR/LF, SP or other control octets must be rejected
  8560. // before anything reaches the wire, otherwise it splits the request line and
  8561. // injects a header or a whole request. This is what a decoded redirect
  8562. // Location ("%0D%0A") turns into when path encoding is disabled.
  8563. const std::string evil_targets[] = {
  8564. "/a\r\nInjected: pwned",
  8565. "/a\rInjected",
  8566. "/a\nInjected",
  8567. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8568. "/a b",
  8569. "/a\tb",
  8570. "/a\x7f",
  8571. };
  8572. for (const auto &evil : evil_targets) {
  8573. detail::BufferStream strm;
  8574. auto n = detail::write_request_line(strm, "GET", evil);
  8575. EXPECT_LT(n, 0);
  8576. EXPECT_TRUE(strm.get_buffer().empty());
  8577. }
  8578. }
  8579. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8580. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8581. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8582. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8583. // write_request. The client must fail cleanly with Error::Write instead of
  8584. // putting a request-line-less, header-injecting request on the wire.
  8585. Server svr;
  8586. svr.Get("/a", [](const Request &, Response &res) {
  8587. res.set_content("ok", "text/plain");
  8588. });
  8589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. thread.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. {
  8597. Client cli(HOST, PORT);
  8598. cli.set_path_encode(false);
  8599. // The request is rejected before anything is written, so the connection
  8600. // stays silent and the subsequent response read would otherwise block for
  8601. // the full default read timeout. Shorten it -- the assertion is on the
  8602. // error, not the timeout.
  8603. cli.set_read_timeout(1, 0);
  8604. auto res = cli.Get("/a\r\nInjected: pwned");
  8605. EXPECT_FALSE(res);
  8606. EXPECT_EQ(Error::Write, res.error());
  8607. }
  8608. }
  8609. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8610. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8611. // including extension methods.
  8612. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8613. for (const auto &method : good_methods) {
  8614. detail::BufferStream strm;
  8615. auto n = detail::write_request_line(strm, method, "/");
  8616. EXPECT_GT(n, 0);
  8617. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8618. }
  8619. // A method carrying CR/LF would split the request line and smuggle a whole
  8620. // request ahead of the real one. A space or an empty method corrupts the
  8621. // request line. All must be rejected before anything reaches the wire.
  8622. const std::string evil_methods[] = {
  8623. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8624. "GET\r\nInjected: pwned",
  8625. "GET\r",
  8626. "GET\n",
  8627. "GE T",
  8628. "",
  8629. };
  8630. for (const auto &evil : evil_methods) {
  8631. detail::BufferStream strm;
  8632. auto n = detail::write_request_line(strm, evil, "/");
  8633. EXPECT_LT(n, 0);
  8634. EXPECT_TRUE(strm.get_buffer().empty());
  8635. }
  8636. }
  8637. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8638. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8639. // through Client::send must fail with Error::Write and no request, neither
  8640. // the smuggled one nor the real one, may reach the server.
  8641. Server svr;
  8642. std::atomic<int> request_count(0);
  8643. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8644. request_count++;
  8645. res.status = StatusCode::OK_200;
  8646. return Server::HandlerResponse::Handled;
  8647. });
  8648. auto port = svr.bind_to_any_port(HOST);
  8649. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. thread.join();
  8653. ASSERT_FALSE(svr.is_running());
  8654. });
  8655. svr.wait_until_ready();
  8656. {
  8657. Client cli(HOST, port);
  8658. const std::string evil_methods[] = {
  8659. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8660. "GE T",
  8661. "",
  8662. };
  8663. for (const auto &evil : evil_methods) {
  8664. Request req;
  8665. req.method = evil;
  8666. req.path = "/";
  8667. auto res = cli.send(req);
  8668. EXPECT_FALSE(res);
  8669. EXPECT_EQ(Error::Write, res.error());
  8670. }
  8671. auto handle =
  8672. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8673. EXPECT_FALSE(handle.is_valid());
  8674. EXPECT_EQ(Error::Write, handle.error);
  8675. // A valid request on the same client still goes through.
  8676. auto res = cli.Get("/");
  8677. ASSERT_TRUE(res);
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. EXPECT_EQ(1, request_count.load());
  8681. }
  8682. // Sends a raw request and verifies that there isn't a crash or exception.
  8683. static void test_raw_request(const std::string &req,
  8684. std::string *out = nullptr) {
  8685. Server svr;
  8686. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8687. res.set_content("ok", "text/plain");
  8688. });
  8689. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8690. res.set_content("ok", "text/plain");
  8691. });
  8692. svr.Get("/header_field_value_check",
  8693. [&](const Request & /*req*/, Response &res) {
  8694. res.set_content("ok", "text/plain");
  8695. });
  8696. svr.CustomRoute("PROPFIND", "/dav",
  8697. [&](const Request & /*req*/, Response &res) {
  8698. res.status = StatusCode::MultiStatus_207;
  8699. });
  8700. // Server read timeout must be longer than the client read timeout for the
  8701. // bug to reproduce, probably to force the server to process a request
  8702. // without a trailing blank line.
  8703. const time_t client_read_timeout_sec = 1;
  8704. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8705. bool listen_thread_ok = false;
  8706. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8707. auto se = detail::scope_exit([&] {
  8708. svr.stop();
  8709. t.join();
  8710. ASSERT_FALSE(svr.is_running());
  8711. EXPECT_TRUE(listen_thread_ok);
  8712. });
  8713. svr.wait_until_ready();
  8714. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8715. }
  8716. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8717. // A certain header line causes an exception if the header property is parsed
  8718. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8719. test_raw_request(
  8720. "GET /hi HTTP/1.1\r\n"
  8721. " : "
  8722. " "
  8723. " ");
  8724. }
  8725. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8726. // A certain header line causes an exception if the header property *name* is
  8727. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8728. // greedy matcher and requires backtracking when there are a lot of ":"
  8729. // characters.
  8730. // This occurs with libc++ but not libstdc++.
  8731. test_raw_request(
  8732. "GET /hi HTTP/1.1\r\n"
  8733. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8734. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8735. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8736. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8737. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8738. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8739. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8740. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8741. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8742. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8743. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8744. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8745. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8746. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8747. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8748. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8749. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8750. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8751. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8752. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8753. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8754. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8755. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8756. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8757. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8758. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8759. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8760. "&&&%%%");
  8761. }
  8762. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8763. // Make sure this doesn't crash the server.
  8764. // In a previous version of the header line regex, the "\r" rendered the line
  8765. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8766. // a new position where the leading white space ended and the field value
  8767. // began.
  8768. // The crash occurs with libc++ but not libstdc++.
  8769. test_raw_request("GET /hi HTTP/1.1\r\n"
  8770. "a:" +
  8771. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8772. "\r\n"
  8773. "\r\n");
  8774. }
  8775. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8776. std::string out;
  8777. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8778. "Content-Type: text/plain\r\n"
  8779. "Transfer-Encoding: chunked\r\n"
  8780. "\r\n"
  8781. "nothex\r\n",
  8782. &out);
  8783. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8784. }
  8785. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8786. std::string out;
  8787. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8788. "Content-Type: text/plain\r\n"
  8789. "Transfer-Encoding: chunked\r\n"
  8790. "\r\n"
  8791. "3\r\n"
  8792. "xyz\r\n"
  8793. "NaN\r\n",
  8794. &out);
  8795. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8796. }
  8797. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8798. std::string out;
  8799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8800. "Content-Type: text/plain\r\n"
  8801. "Transfer-Encoding: chunked\r\n"
  8802. "\r\n"
  8803. // Length is too large for 64 bits.
  8804. "1ffffffffffffffff\r\n"
  8805. "xyz\r\n",
  8806. &out);
  8807. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8808. }
  8809. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8810. test_raw_request("GET /hi HTTP/1.1\r\n"
  8811. "Content-Type: text/plain\r\n\r");
  8812. }
  8813. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8814. std::string out;
  8815. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8817. }
  8818. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8819. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8820. std::string out;
  8821. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8822. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8823. }
  8824. }
  8825. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8826. std::string out;
  8827. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8828. "Connection: close\r\n\r\n",
  8829. &out);
  8830. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8831. }
  8832. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8833. Server svr;
  8834. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8835. EXPECT_TRUE(!req.remote_addr.empty());
  8836. });
  8837. thread t = thread([&] { svr.listen(HOST, PORT); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. // Send an invalid request line to trigger Bad Request
  8845. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8846. std::string out;
  8847. ASSERT_TRUE(send_request(5, bad_req, &out));
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8851. // answered right away rather than blocking on a read that waits for EOF.
  8852. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8853. std::string out;
  8854. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8855. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8856. }
  8857. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8858. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8859. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8860. for (const auto *method : methods) {
  8861. Server svr;
  8862. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8863. EXPECT_FALSE(svr.is_valid()) << method;
  8864. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8865. }
  8866. }
  8867. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8868. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8869. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8870. for (const auto *method : methods) {
  8871. Server svr;
  8872. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8873. EXPECT_FALSE(svr.is_valid()) << method;
  8874. }
  8875. }
  8876. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8877. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8878. "COPY", "MOVE", "LOCK",
  8879. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8880. Server svr;
  8881. for (const auto *method : methods) {
  8882. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8883. }
  8884. EXPECT_TRUE(svr.is_valid());
  8885. }
  8886. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8887. Server svr;
  8888. svr.CustomRoute("POST", "/x",
  8889. [](const Request &, Response &, const ContentReader &) {});
  8890. EXPECT_FALSE(svr.is_valid());
  8891. }
  8892. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8893. Server svr;
  8894. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8895. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8896. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8897. EXPECT_FALSE(svr.is_valid());
  8898. }
  8899. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8900. Server svr;
  8901. auto captured = Error::Success;
  8902. svr.set_error_logger(
  8903. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8904. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8905. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8906. }
  8907. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8908. std::string out;
  8909. std::string request(
  8910. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8911. test_raw_request(request, &out);
  8912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8913. }
  8914. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8915. std::string out;
  8916. std::string request(
  8917. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8918. test_raw_request(request, &out);
  8919. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8920. }
  8921. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8922. std::string out;
  8923. std::string request(
  8924. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8925. test_raw_request(request, &out);
  8926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8927. }
  8928. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8929. std::string out;
  8930. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8931. "Test: \r\n\r\n",
  8932. &out);
  8933. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8934. }
  8935. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8936. Server svr;
  8937. std::string x_custom;
  8938. std::string cookie;
  8939. std::string xff;
  8940. std::string x_unicode;
  8941. std::string x_iis;
  8942. svr.Get("/check", [&](const Request &req, Response &res) {
  8943. x_custom = req.get_header_value("X-Custom");
  8944. cookie = req.get_header_value("Cookie");
  8945. xff = req.get_header_value("X-Forwarded-For");
  8946. x_unicode = req.get_header_value("X-Unicode");
  8947. x_iis = req.get_header_value("X-IIS");
  8948. res.set_content("ok", "text/plain");
  8949. });
  8950. thread t = thread([&] { svr.listen(HOST, PORT); });
  8951. auto se = detail::scope_exit([&] {
  8952. svr.stop();
  8953. t.join();
  8954. ASSERT_FALSE(svr.is_running());
  8955. });
  8956. svr.wait_until_ready();
  8957. const std::string req = "GET /check HTTP/1.1\r\n"
  8958. "Host: localhost\r\n"
  8959. "X-Custom: a%0D%0AInjected: b\r\n"
  8960. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8961. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8962. "X-Unicode: %E3%81%82\r\n"
  8963. "X-IIS: %u00E9\r\n"
  8964. "Connection: close\r\n"
  8965. "\r\n";
  8966. std::string res;
  8967. ASSERT_TRUE(send_request(5, req, &res));
  8968. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8969. // Every value must be returned verbatim (wire form), with no decoding.
  8970. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8971. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8972. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8973. EXPECT_EQ("%E3%81%82", x_unicode);
  8974. EXPECT_EQ("%u00E9", x_iis);
  8975. }
  8976. // Applications that previously relied on automatic percent-decoding can
  8977. // reproduce the old behavior by explicitly calling decode_path_component()
  8978. // or, for RFC 3986 conformance, decode_uri_component().
  8979. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8980. Server svr;
  8981. std::string decoded;
  8982. svr.Get("/check", [&](const Request &req, Response &res) {
  8983. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8984. res.set_content("ok", "text/plain");
  8985. });
  8986. thread t = thread([&] { svr.listen(HOST, PORT); });
  8987. auto se = detail::scope_exit([&] {
  8988. svr.stop();
  8989. t.join();
  8990. ASSERT_FALSE(svr.is_running());
  8991. });
  8992. svr.wait_until_ready();
  8993. const std::string req = "GET /check HTTP/1.1\r\n"
  8994. "Host: localhost\r\n"
  8995. "X-Custom: hello%20world\r\n"
  8996. "Connection: close\r\n"
  8997. "\r\n";
  8998. std::string res;
  8999. ASSERT_TRUE(send_request(5, req, &res));
  9000. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9001. EXPECT_EQ("hello world", decoded);
  9002. }
  9003. // Regression test for #2033. Browsers send Referer values that include
  9004. // percent-encoded characters such as %0A inside the URL. Decoding the
  9005. // header value would either trip the post-decode CR/LF/NUL guard (the
  9006. // original bug, returning 400) or, after that guard was relaxed, silently
  9007. // store a literal LF — both unacceptable. The wire form must round-trip.
  9008. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9009. Server svr;
  9010. std::string referer;
  9011. svr.Get("/check", [&](const Request &req, Response &res) {
  9012. referer = req.get_header_value("Referer");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9025. "Connection: close\r\n"
  9026. "\r\n";
  9027. std::string res;
  9028. ASSERT_TRUE(send_request(5, req, &res));
  9029. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9030. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9031. }
  9032. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9033. Server svr;
  9034. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9035. res.set_header("Cache-Control", "no-cache");
  9036. res.set_chunked_content_provider(
  9037. "text/event-stream", [](size_t offset, DataSink &sink) {
  9038. std::string s = "data:";
  9039. s += std::to_string(offset);
  9040. s += "\n\n";
  9041. auto ret = sink.write(s.data(), s.size());
  9042. EXPECT_TRUE(ret);
  9043. std::this_thread::sleep_for(std::chrono::seconds(1));
  9044. return true;
  9045. });
  9046. });
  9047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9048. svr.wait_until_ready();
  9049. Client client(HOST, PORT);
  9050. const Headers headers = {{"Accept", "text/event-stream"}};
  9051. auto get_thread = std::thread([&client, &headers]() {
  9052. auto res = client.Get(
  9053. "/events", headers,
  9054. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9055. });
  9056. auto se = detail::scope_exit([&] {
  9057. svr.stop();
  9058. get_thread.join();
  9059. listen_thread.join();
  9060. ASSERT_FALSE(svr.is_running());
  9061. });
  9062. // Give GET time to get a few messages.
  9063. std::this_thread::sleep_for(std::chrono::seconds(2));
  9064. }
  9065. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9066. httplib::Server svr;
  9067. svr.Post("/hi",
  9068. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9069. res.status = StatusCode::OK_200;
  9070. });
  9071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9072. svr.wait_until_ready();
  9073. Client cli(HOST, PORT);
  9074. auto res = cli.Post("/hi", "data", "text/plain");
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. svr.stop();
  9078. thread.join();
  9079. ASSERT_FALSE(svr.is_running());
  9080. res = cli.Post("/hi", "data", "text/plain");
  9081. ASSERT_FALSE(res);
  9082. }
  9083. TEST(ServerStopTest, ListenFailure) {
  9084. Server svr;
  9085. auto t = thread([&]() {
  9086. auto ret = svr.listen("????", PORT);
  9087. EXPECT_FALSE(ret);
  9088. });
  9089. svr.wait_until_ready();
  9090. svr.stop();
  9091. t.join();
  9092. }
  9093. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9094. TEST(ServerStopTest, Decommision) {
  9095. Server svr;
  9096. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9097. for (int i = 0; i < 4; i++) {
  9098. auto is_even = !(i % 2);
  9099. std::thread t{[&] {
  9100. try {
  9101. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9102. if (is_even) {
  9103. throw std::runtime_error("Some thing that happens to go wrong.");
  9104. }
  9105. svr.listen(HOST, PORT);
  9106. } catch (...) { svr.decommission(); }
  9107. }};
  9108. svr.wait_until_ready();
  9109. // Server is up
  9110. {
  9111. Client cli(HOST, PORT);
  9112. auto res = cli.Get("/hi");
  9113. if (is_even) {
  9114. EXPECT_FALSE(res);
  9115. } else {
  9116. EXPECT_TRUE(res);
  9117. EXPECT_EQ("hi...", res->body);
  9118. }
  9119. }
  9120. svr.stop();
  9121. t.join();
  9122. // Server is down...
  9123. {
  9124. Client cli(HOST, PORT);
  9125. auto res = cli.Get("/hi");
  9126. EXPECT_FALSE(res);
  9127. }
  9128. }
  9129. }
  9130. #endif
  9131. // Helper function for string body upload progress tests
  9132. template <typename SetupHandler, typename ClientCall>
  9133. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9134. ClientCall &&client_call,
  9135. const string &body) {
  9136. Server svr;
  9137. setup_handler(svr);
  9138. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9139. auto se = detail::scope_exit([&] {
  9140. svr.stop();
  9141. t.join();
  9142. });
  9143. svr.wait_until_ready();
  9144. Client cli(HOST, PORT);
  9145. vector<uint64_t> progress_values;
  9146. bool progress_called = false;
  9147. auto res =
  9148. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9149. progress_values.push_back(current);
  9150. progress_called = true;
  9151. return true;
  9152. });
  9153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9154. EXPECT_EQ(200, res->status);
  9155. EXPECT_TRUE(progress_called);
  9156. }
  9157. TEST(UploadProgressTest, PostStringBodyBasic) {
  9158. TestStringBodyUploadProgress(
  9159. [](Server &svr) {
  9160. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9161. res.set_content("received", "text/plain");
  9162. });
  9163. },
  9164. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9165. return cli.Post("/test", body, "text/plain", progress_callback);
  9166. },
  9167. "test data for upload progress");
  9168. }
  9169. TEST(UploadProgressTest, PutStringBodyBasic) {
  9170. TestStringBodyUploadProgress(
  9171. [](Server &svr) {
  9172. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9173. res.set_content("put received", "text/plain");
  9174. });
  9175. },
  9176. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9177. return cli.Put("/test", body, "text/plain", progress_callback);
  9178. },
  9179. "put test data for upload progress");
  9180. }
  9181. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9182. TestStringBodyUploadProgress(
  9183. [](Server &svr) {
  9184. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9185. res.set_content("patch received", "text/plain");
  9186. });
  9187. },
  9188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9189. return cli.Patch("/test", body, "text/plain", progress_callback);
  9190. },
  9191. "patch test data for upload progress");
  9192. }
  9193. // Helper function for content provider upload progress tests
  9194. template <typename SetupHandler, typename ClientCall>
  9195. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9196. ClientCall &&client_call) {
  9197. Server svr;
  9198. setup_handler(svr);
  9199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9200. auto se = detail::scope_exit([&] {
  9201. svr.stop();
  9202. t.join();
  9203. });
  9204. svr.wait_until_ready();
  9205. Client cli(HOST, PORT);
  9206. vector<uint64_t> progress_values;
  9207. auto res =
  9208. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9209. progress_values.push_back(current);
  9210. return true;
  9211. });
  9212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9213. EXPECT_EQ(200, res->status);
  9214. EXPECT_FALSE(progress_values.empty());
  9215. }
  9216. TEST(UploadProgressTest, PostContentProviderProgress) {
  9217. TestContentProviderUploadProgress(
  9218. [](Server &svr) {
  9219. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9220. res.set_content("provider received", "text/plain");
  9221. });
  9222. },
  9223. [](Client &cli, UploadProgress progress_callback) {
  9224. return cli.Post(
  9225. "/test", 10,
  9226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9227. sink.os << "test data";
  9228. return true;
  9229. },
  9230. "text/plain", progress_callback);
  9231. });
  9232. }
  9233. // Helper function for multipart upload progress tests
  9234. template <typename SetupHandler, typename ClientCall>
  9235. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9236. ClientCall &&client_call,
  9237. const string &endpoint) {
  9238. Server svr;
  9239. setup_handler(svr);
  9240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9241. auto se = detail::scope_exit([&] {
  9242. svr.stop();
  9243. t.join();
  9244. });
  9245. svr.wait_until_ready();
  9246. Client cli(HOST, PORT);
  9247. vector<uint64_t> progress_values;
  9248. UploadFormDataItems items = {
  9249. {"field1", "value1", "", ""},
  9250. {"field2", "longer value for progress tracking test", "", ""},
  9251. {"file1", "file content data for upload progress", "test.txt",
  9252. "text/plain"}};
  9253. auto res = client_call(cli, endpoint, items,
  9254. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9255. progress_values.push_back(current);
  9256. return true;
  9257. });
  9258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9259. EXPECT_EQ(200, res->status);
  9260. EXPECT_FALSE(progress_values.empty());
  9261. }
  9262. TEST(UploadProgressTest, PostMultipartProgress) {
  9263. TestMultipartUploadProgress(
  9264. [](Server &svr) {
  9265. svr.Post("/multipart", [](const Request &req, Response &res) {
  9266. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9267. res.set_content("multipart received", "text/plain");
  9268. });
  9269. },
  9270. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9271. UploadProgress progress_callback) {
  9272. return cli.Post(endpoint, items, progress_callback);
  9273. },
  9274. "/multipart");
  9275. }
  9276. // Helper function for basic download progress tests
  9277. template <typename SetupHandler, typename ClientCall>
  9278. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9279. ClientCall &&client_call, const string &endpoint,
  9280. size_t expected_content_size) {
  9281. Server svr;
  9282. setup_handler(svr);
  9283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. });
  9288. svr.wait_until_ready();
  9289. Client cli(HOST, PORT);
  9290. vector<uint64_t> progress_values;
  9291. auto res = client_call(cli, endpoint,
  9292. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9293. progress_values.push_back(current);
  9294. return true;
  9295. });
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(200, res->status);
  9298. EXPECT_FALSE(progress_values.empty());
  9299. EXPECT_EQ(expected_content_size, res->body.size());
  9300. }
  9301. TEST(DownloadProgressTest, GetBasic) {
  9302. TestBasicDownloadProgress(
  9303. [](Server &svr) {
  9304. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9305. string content(1000, 'D');
  9306. res.set_content(content, "text/plain");
  9307. });
  9308. },
  9309. [](Client &cli, const string &endpoint,
  9310. DownloadProgress progress_callback) {
  9311. return cli.Get(endpoint, progress_callback);
  9312. },
  9313. "/download", 1000u);
  9314. }
  9315. // Helper function for content receiver download progress tests
  9316. template <typename SetupHandler, typename ClientCall>
  9317. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9318. ClientCall &&client_call,
  9319. const string &endpoint,
  9320. size_t expected_content_size) {
  9321. Server svr;
  9322. setup_handler(svr);
  9323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9324. auto se = detail::scope_exit([&] {
  9325. svr.stop();
  9326. t.join();
  9327. });
  9328. svr.wait_until_ready();
  9329. Client cli(HOST, PORT);
  9330. vector<uint64_t> progress_values;
  9331. string received_body;
  9332. auto res = client_call(
  9333. cli, endpoint,
  9334. [&](const char *data, size_t data_length) -> bool {
  9335. received_body.append(data, data_length);
  9336. return true;
  9337. },
  9338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9339. progress_values.push_back(current);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9343. EXPECT_EQ(200, res->status);
  9344. EXPECT_FALSE(progress_values.empty());
  9345. EXPECT_EQ(expected_content_size, received_body.size());
  9346. EXPECT_TRUE(res->body.empty());
  9347. }
  9348. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9349. TestContentReceiverDownloadProgress(
  9350. [](Server &svr) {
  9351. svr.Get("/download-receiver",
  9352. [](const Request & /*req*/, Response &res) {
  9353. string content(2000, 'R');
  9354. res.set_content(content, "text/plain");
  9355. });
  9356. },
  9357. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9358. DownloadProgress progress_callback) {
  9359. return cli.Get(endpoint, content_receiver, progress_callback);
  9360. },
  9361. "/download-receiver", 2000u);
  9362. }
  9363. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9364. // A provider reaching a pass with nothing to hand over - an empty buffer
  9365. // popped off a queue, say - must not be taken to mean the body is finished.
  9366. // It used to end the loop with the terminating chunk unwritten while the
  9367. // server still considered the response complete, so the peer waited for an
  9368. // end that never arrived.
  9369. Server svr;
  9370. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9371. auto step = std::make_shared<int>(0);
  9372. res.set_chunked_content_provider("text/plain",
  9373. [step](size_t /*offset*/, DataSink &sink) {
  9374. switch ((*step)++) {
  9375. case 0: sink.write("", 0); break;
  9376. case 1: sink.write("hello", 5); break;
  9377. default: sink.done(); break;
  9378. }
  9379. return true;
  9380. });
  9381. });
  9382. auto port = svr.bind_to_any_port(HOST);
  9383. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9384. auto listen_se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. listen_thread.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. Client cli(HOST, port);
  9391. // Without the fix the body is never terminated, so bound the wait rather
  9392. // than letting the test hang on the default read timeout.
  9393. cli.set_read_timeout(5, 0);
  9394. auto res = cli.Get("/stream");
  9395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9396. EXPECT_EQ(StatusCode::OK_200, res->status);
  9397. EXPECT_EQ("hello", res->body);
  9398. }
  9399. TEST(StreamingTest, NoContentLengthStreaming) {
  9400. Server svr;
  9401. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9402. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9403. if (offset < 6) {
  9404. sink.os << (offset < 3 ? "a" : "b");
  9405. } else {
  9406. sink.done();
  9407. }
  9408. return true;
  9409. });
  9410. });
  9411. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9412. auto listen_se = detail::scope_exit([&] {
  9413. svr.stop();
  9414. listen_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. svr.wait_until_ready();
  9418. Client client(HOST, PORT);
  9419. auto get_thread = std::thread([&client]() {
  9420. std::string s;
  9421. auto res =
  9422. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9423. s += std::string(data, len);
  9424. return true;
  9425. });
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. EXPECT_EQ("aaabbb", s);
  9429. });
  9430. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9431. // Give GET time to get a few messages.
  9432. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9433. }
  9434. TEST(MountTest, Unmount) {
  9435. Server svr;
  9436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. listen_thread.join();
  9440. ASSERT_FALSE(svr.is_running());
  9441. });
  9442. svr.wait_until_ready();
  9443. Client cli("localhost", PORT);
  9444. svr.set_mount_point("/mount2", "./www2");
  9445. auto res = cli.Get("/");
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9448. res = cli.Get("/mount2/dir/test.html");
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. svr.set_mount_point("/", "./www");
  9452. res = cli.Get("/dir/");
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ(StatusCode::OK_200, res->status);
  9455. svr.remove_mount_point("/");
  9456. res = cli.Get("/dir/");
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9459. svr.remove_mount_point("/mount2");
  9460. res = cli.Get("/mount2/dir/test.html");
  9461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9463. }
  9464. TEST(MountTest, PathSegmentBoundary) {
  9465. Server svr;
  9466. svr.set_mount_point("/mount2", "./www2");
  9467. svr.set_mount_point("/", "./www");
  9468. auto port = svr.bind_to_any_port(HOST);
  9469. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. listen_thread.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. Client cli(HOST, port);
  9477. auto res = cli.Get("/mount2/dir/test.html");
  9478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9479. EXPECT_EQ(StatusCode::OK_200, res->status);
  9480. // "/mount2" must not match part-way through a path segment.
  9481. res = cli.Get("/mount2dir/test.html");
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9484. // A mount point ending in '/' keeps matching every path below it.
  9485. res = cli.Get("/dir/test.html");
  9486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9487. EXPECT_EQ(StatusCode::OK_200, res->status);
  9488. }
  9489. TEST(MountTest, Redicect) {
  9490. Server svr;
  9491. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. listen_thread.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.set_mount_point("/", "./www");
  9498. svr.wait_until_ready();
  9499. Client cli("localhost", PORT);
  9500. auto res = cli.Get("/dir/");
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. res = cli.Get("/dir");
  9504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9505. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9506. res = cli.Get("/file");
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. res = cli.Get("/file/");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9512. cli.set_follow_location(true);
  9513. res = cli.Get("/dir");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. }
  9517. TEST(MountTest, MultibytesPathName) {
  9518. Server svr;
  9519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9520. auto se = detail::scope_exit([&] {
  9521. svr.stop();
  9522. listen_thread.join();
  9523. ASSERT_FALSE(svr.is_running());
  9524. });
  9525. svr.set_mount_point("/", "./www");
  9526. svr.wait_until_ready();
  9527. Client cli("localhost", PORT);
  9528. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9530. EXPECT_EQ(StatusCode::OK_200, res->status);
  9531. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9532. }
  9533. #ifdef _WIN32
  9534. // Issue #2435: mmap::open() must succeed even when another handle holds
  9535. // the file open for writing (e.g. an active log file).
  9536. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9537. const char *path = "mmap_concurrent_writer_test.txt";
  9538. const char *content = "hello";
  9539. {
  9540. std::ofstream f(path, std::ios::binary);
  9541. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9542. }
  9543. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9544. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9545. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9546. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9547. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9548. detail::mmap m(path);
  9549. ASSERT_TRUE(m.is_open());
  9550. EXPECT_EQ(strlen(content), m.size());
  9551. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9552. }
  9553. #endif
  9554. #ifndef _WIN32
  9555. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9556. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9557. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9558. TEST(MmapTest, FailedMappingIsNotOpen) {
  9559. const char *path = "./mmap_failed_mapping_test_dir";
  9560. ASSERT_EQ(0, ::mkdir(path, 0755));
  9561. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9562. detail::mmap m(path);
  9563. EXPECT_FALSE(m.is_open());
  9564. EXPECT_EQ(0U, m.size());
  9565. EXPECT_NE(static_cast<const void *>(m.data()),
  9566. static_cast<const void *>(MAP_FAILED));
  9567. }
  9568. #endif
  9569. TEST(KeepAliveTest, ReadTimeout) {
  9570. Server svr;
  9571. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9572. std::this_thread::sleep_for(std::chrono::seconds(2));
  9573. res.set_content("a", "text/plain");
  9574. });
  9575. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9576. res.set_content("b", "text/plain");
  9577. });
  9578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. listen_thread.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. Client cli("localhost", PORT);
  9586. cli.set_keep_alive(true);
  9587. cli.set_read_timeout(std::chrono::seconds(1));
  9588. auto resa = cli.Get("/a");
  9589. ASSERT_FALSE(resa);
  9590. EXPECT_EQ(Error::Read, resa.error());
  9591. auto resb = cli.Get("/b");
  9592. ASSERT_TRUE(resb);
  9593. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9594. EXPECT_EQ("b", resb->body);
  9595. }
  9596. TEST(KeepAliveTest, MaxCount) {
  9597. size_t keep_alive_max_count = 3;
  9598. Server svr;
  9599. svr.set_keep_alive_max_count(keep_alive_max_count);
  9600. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9601. res.set_content("Hello World!", "text/plain");
  9602. });
  9603. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. listen_thread.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. Client cli(HOST, PORT);
  9611. cli.set_keep_alive(true);
  9612. for (size_t i = 0; i < 5; i++) {
  9613. auto result = cli.Get("/hi");
  9614. ASSERT_TRUE(result);
  9615. EXPECT_EQ(StatusCode::OK_200, result->status);
  9616. if (i == keep_alive_max_count - 1) {
  9617. EXPECT_EQ("close", result->get_header_value("Connection"));
  9618. } else {
  9619. EXPECT_FALSE(result->has_header("Connection"));
  9620. }
  9621. }
  9622. }
  9623. TEST(KeepAliveTest, Issue1041) {
  9624. Server svr;
  9625. svr.set_keep_alive_timeout(3);
  9626. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9627. res.set_content("Hello World!", "text/plain");
  9628. });
  9629. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9630. auto se = detail::scope_exit([&] {
  9631. svr.stop();
  9632. listen_thread.join();
  9633. ASSERT_FALSE(svr.is_running());
  9634. });
  9635. svr.wait_until_ready();
  9636. Client cli(HOST, PORT);
  9637. cli.set_keep_alive(true);
  9638. auto result = cli.Get("/hi");
  9639. ASSERT_TRUE(result);
  9640. EXPECT_EQ(StatusCode::OK_200, result->status);
  9641. std::this_thread::sleep_for(std::chrono::seconds(5));
  9642. result = cli.Get("/hi");
  9643. ASSERT_TRUE(result);
  9644. EXPECT_EQ(StatusCode::OK_200, result->status);
  9645. }
  9646. TEST(KeepAliveTest, Issue1959) {
  9647. Server svr;
  9648. svr.set_keep_alive_timeout(5);
  9649. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9650. res.set_content("a", "text/plain");
  9651. });
  9652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. if (!svr.is_running()) return;
  9655. svr.stop();
  9656. listen_thread.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. Client cli("localhost", PORT);
  9661. cli.set_keep_alive(true);
  9662. using namespace std::chrono;
  9663. auto start = steady_clock::now();
  9664. cli.Get("/a");
  9665. svr.stop();
  9666. listen_thread.join();
  9667. auto end = steady_clock::now();
  9668. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9669. EXPECT_LT(elapsed, 5000);
  9670. }
  9671. #ifdef CPPHTTPLIB_SSL_ENABLED
  9672. TEST(KeepAliveTest, SSLClientReconnection) {
  9673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9674. ASSERT_TRUE(svr.is_valid());
  9675. svr.set_keep_alive_timeout(1);
  9676. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9677. res.set_content("Hello World!", "text/plain");
  9678. });
  9679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9680. auto se = detail::scope_exit([&] {
  9681. svr.stop();
  9682. listen_thread.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. svr.wait_until_ready();
  9686. SSLClient cli(HOST, PORT);
  9687. cli.enable_server_certificate_verification(false);
  9688. cli.set_keep_alive(true);
  9689. auto result = cli.Get("/hi");
  9690. ASSERT_TRUE(result);
  9691. EXPECT_EQ(StatusCode::OK_200, result->status);
  9692. result = cli.Get("/hi");
  9693. ASSERT_TRUE(result);
  9694. EXPECT_EQ(StatusCode::OK_200, result->status);
  9695. std::this_thread::sleep_for(std::chrono::seconds(2));
  9696. // Recoonect
  9697. result = cli.Get("/hi");
  9698. ASSERT_TRUE(result);
  9699. EXPECT_EQ(StatusCode::OK_200, result->status);
  9700. result = cli.Get("/hi");
  9701. ASSERT_TRUE(result);
  9702. EXPECT_EQ(StatusCode::OK_200, result->status);
  9703. }
  9704. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9706. ASSERT_TRUE(svr.is_valid());
  9707. svr.set_keep_alive_timeout(1);
  9708. std::string content = "reconnect";
  9709. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9710. res.set_content("Hello World!", "text/plain");
  9711. });
  9712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9713. auto se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. listen_thread.join();
  9716. ASSERT_FALSE(svr.is_running());
  9717. });
  9718. svr.wait_until_ready();
  9719. SSLClient cli(HOST, PORT);
  9720. cli.enable_server_certificate_verification(false);
  9721. cli.set_keep_alive(true);
  9722. auto result = cli.Post(
  9723. "/hi", content.size(),
  9724. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9725. sink.write(content.c_str(), content.size());
  9726. return true;
  9727. },
  9728. "text/plain");
  9729. ASSERT_TRUE(result);
  9730. EXPECT_EQ(200, result->status);
  9731. std::this_thread::sleep_for(std::chrono::seconds(2));
  9732. // Recoonect
  9733. result = cli.Post(
  9734. "/hi", content.size(),
  9735. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9736. sink.write(content.c_str(), content.size());
  9737. return true;
  9738. },
  9739. "text/plain");
  9740. ASSERT_TRUE(result);
  9741. EXPECT_EQ(200, result->status);
  9742. result = cli.Post(
  9743. "/hi", content.size(),
  9744. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9745. sink.write(content.c_str(), content.size());
  9746. return true;
  9747. },
  9748. "text/plain");
  9749. ASSERT_TRUE(result);
  9750. EXPECT_EQ(200, result->status);
  9751. }
  9752. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9753. using namespace httplib::tls;
  9754. {
  9755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9756. ASSERT_TRUE(svr.is_valid());
  9757. svr.Get("/sni", [&](const Request &req, Response &res) {
  9758. std::string expected = req.sni();
  9759. EXPECT_EQ(expected, req.get_param_value("expected"));
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. listen_thread.join();
  9766. ASSERT_FALSE(svr.is_running());
  9767. });
  9768. svr.wait_until_ready();
  9769. {
  9770. SSLClient cli("localhost", PORT);
  9771. cli.enable_server_certificate_verification(false);
  9772. auto res = cli.Get("/sni?expected=localhost");
  9773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9774. }
  9775. {
  9776. SSLClient cli("::1", PORT);
  9777. cli.enable_server_certificate_verification(false);
  9778. auto res = cli.Get("/sni?expected=");
  9779. // NOTE: This may fail if the server is listening on IPv4 only
  9780. // (e.g., when localhost resolves to 127.0.0.1 only)
  9781. if (res) {
  9782. EXPECT_EQ(StatusCode::OK_200, res->status);
  9783. } else {
  9784. EXPECT_EQ(Error::Connection, res.error());
  9785. }
  9786. }
  9787. }
  9788. }
  9789. #endif
  9790. TEST(ClientProblemDetectionTest, ContentProvider) {
  9791. Server svr;
  9792. size_t content_length = 1024 * 1024;
  9793. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9794. res.set_content_provider(
  9795. content_length, "text/plain",
  9796. [&](size_t offset, size_t length, DataSink &sink) {
  9797. auto out_len = std::min(length, static_cast<size_t>(1024));
  9798. std::string out(out_len, '@');
  9799. sink.write(out.data(), out_len);
  9800. return offset < 4096;
  9801. },
  9802. [](bool success) { ASSERT_FALSE(success); });
  9803. });
  9804. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9805. res.set_content_provider(
  9806. 0, "text/plain",
  9807. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9808. EXPECT_TRUE(false);
  9809. return true;
  9810. },
  9811. [](bool success) { ASSERT_FALSE(success); });
  9812. });
  9813. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9814. auto se = detail::scope_exit([&] {
  9815. svr.stop();
  9816. listen_thread.join();
  9817. ASSERT_FALSE(svr.is_running());
  9818. });
  9819. svr.wait_until_ready();
  9820. Client cli("localhost", PORT);
  9821. {
  9822. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9823. size_t /*data_length*/) { return false; });
  9824. ASSERT_FALSE(res);
  9825. }
  9826. {
  9827. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9828. size_t /*data_length*/) { return false; });
  9829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9830. }
  9831. }
  9832. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9833. // A provider that reports success without writing anything and without
  9834. // calling done() used to be handed the same offset and length again on every
  9835. // pass, so it spun for as long as the peer stayed connected.
  9836. Server svr;
  9837. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9838. res.set_content("ok", "text/plain");
  9839. });
  9840. auto port = svr.bind_to_any_port(HOST);
  9841. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9842. auto se = detail::scope_exit([&] {
  9843. svr.stop();
  9844. listen_thread.join();
  9845. ASSERT_FALSE(svr.is_running());
  9846. });
  9847. svr.wait_until_ready();
  9848. std::atomic<int> call_count{0};
  9849. Client cli(HOST, port);
  9850. auto res = cli.Post(
  9851. "/", 1024,
  9852. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9853. // Give up after enough passes to show the spin, so that losing the
  9854. // check below fails this test instead of hanging it.
  9855. return ++call_count < 100;
  9856. },
  9857. "text/plain");
  9858. ASSERT_FALSE(res);
  9859. EXPECT_EQ(Error::Write, res.error());
  9860. EXPECT_EQ(1, call_count.load());
  9861. }
  9862. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9863. // A writer only has to assign `write`. The other three used to be left as
  9864. // empty std::functions, so a provider calling one threw
  9865. // std::bad_function_call out of the thread running it and took the whole
  9866. // process down.
  9867. DataSink sink;
  9868. std::string written;
  9869. sink.write = [&](const char *data, size_t data_len) {
  9870. written.append(data, data_len);
  9871. return true;
  9872. };
  9873. EXPECT_TRUE(sink.is_writable());
  9874. sink.done();
  9875. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9876. EXPECT_TRUE(written.empty());
  9877. }
  9878. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9879. // A sink that cannot carry trailers still has to finish.
  9880. DataSink sink;
  9881. auto done_count = 0;
  9882. sink.done = [&]() { done_count++; };
  9883. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9884. EXPECT_EQ(1, done_count);
  9885. }
  9886. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9887. Server svr;
  9888. const std::string body(4096, 'x');
  9889. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9890. res.set_content_provider(body.size(), "text/plain",
  9891. [&](size_t offset, size_t length, DataSink &sink) {
  9892. sink.write(body.data() + offset, length);
  9893. sink.done();
  9894. return true;
  9895. });
  9896. });
  9897. auto port = svr.bind_to_any_port(HOST);
  9898. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. listen_thread.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli(HOST, port);
  9906. auto res = cli.Get("/");
  9907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9908. EXPECT_EQ(StatusCode::OK_200, res->status);
  9909. EXPECT_EQ(body, res->body);
  9910. }
  9911. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9912. Server svr;
  9913. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9914. res.set_content_provider(
  9915. 1024, "text/plain",
  9916. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9917. sink.write("hello", 5);
  9918. sink.done(); // short of the 1024 bytes the response promised
  9919. return true;
  9920. });
  9921. });
  9922. auto port = svr.bind_to_any_port(HOST);
  9923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9924. auto se = detail::scope_exit([&] {
  9925. svr.stop();
  9926. listen_thread.join();
  9927. ASSERT_FALSE(svr.is_running());
  9928. });
  9929. svr.wait_until_ready();
  9930. Client cli(HOST, port);
  9931. cli.set_read_timeout(5, 0);
  9932. // The response is short of its Content-Length, so the client cannot read a
  9933. // complete body. What matters is that this returns at all: a no-op done()
  9934. // would leave the writer looping over a provider that never makes progress.
  9935. auto res = cli.Get("/");
  9936. EXPECT_FALSE(res);
  9937. }
  9938. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9939. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9940. // The compressed path builds the whole body before connecting, so this
  9941. // fails client-side and never reaches a server.
  9942. Client cli(HOST, PORT);
  9943. cli.set_compress(true);
  9944. auto res = cli.Post(
  9945. "/", 1024,
  9946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9947. sink.write("hello", 5);
  9948. sink.done(); // short of the 1024 bytes the request announced
  9949. return true;
  9950. },
  9951. "text/plain");
  9952. ASSERT_FALSE(res);
  9953. EXPECT_EQ(Error::Write, res.error());
  9954. }
  9955. #endif
  9956. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9957. Server svr;
  9958. svr.set_error_handler([](Request const &, Response &res) -> void {
  9959. res.set_chunked_content_provider(
  9960. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9961. sink.os << "hello";
  9962. sink.os << "world";
  9963. sink.done();
  9964. return true;
  9965. });
  9966. });
  9967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. listen_thread.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. Client cli("localhost", PORT);
  9975. auto res = cli.Get("/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. EXPECT_EQ("helloworld", res->body);
  9979. }
  9980. TEST(LongPollingTest, ClientCloseDetection) {
  9981. Server svr;
  9982. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9983. res.set_chunked_content_provider(
  9984. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9985. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9986. sink.os << "hello";
  9987. auto count = 10;
  9988. while (count > 0 && sink.is_writable()) {
  9989. this_thread::sleep_for(chrono::milliseconds(10));
  9990. count--;
  9991. }
  9992. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9993. return true;
  9994. });
  9995. });
  9996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9997. auto se = detail::scope_exit([&] {
  9998. svr.stop();
  9999. listen_thread.join();
  10000. ASSERT_FALSE(svr.is_running());
  10001. });
  10002. svr.wait_until_ready();
  10003. Client cli("localhost", PORT);
  10004. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10005. EXPECT_EQ("hello", string(data, data_length));
  10006. return false; // close the socket immediately.
  10007. });
  10008. ASSERT_FALSE(res);
  10009. }
  10010. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10011. Server svr;
  10012. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10013. res.set_chunked_content_provider(
  10014. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10015. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10016. sink.os << "hello";
  10017. EXPECT_TRUE(sink.os.good());
  10018. // Wait for the client to close the connection
  10019. auto count = 10;
  10020. while (count > 0 && sink.is_writable()) {
  10021. this_thread::sleep_for(chrono::milliseconds(10));
  10022. count--;
  10023. }
  10024. // After client disconnect, write repeatedly until the socket
  10025. // write actually fails (small writes may be absorbed by the
  10026. // kernel buffer)
  10027. std::string chunk(1024, 'x');
  10028. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10029. sink.os << chunk;
  10030. }
  10031. EXPECT_TRUE(sink.os.fail());
  10032. return true;
  10033. });
  10034. });
  10035. auto port = svr.bind_to_any_port("localhost");
  10036. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. listen_thread.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. Client cli("localhost", port);
  10044. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10045. EXPECT_EQ("hello", string(data, data_length));
  10046. return false; // close the socket immediately.
  10047. });
  10048. ASSERT_FALSE(res);
  10049. }
  10050. TEST(GetWithParametersTest, GetWithParameters) {
  10051. Server svr;
  10052. svr.Get("/", [&](const Request &req, Response &) {
  10053. EXPECT_EQ("world", req.get_param_value("hello"));
  10054. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10055. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10056. });
  10057. svr.Get("/params", [&](const Request &req, Response &) {
  10058. EXPECT_EQ("world", req.get_param_value("hello"));
  10059. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10060. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10061. });
  10062. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10063. EXPECT_EQ("resource-id", req.matches[1]);
  10064. EXPECT_EQ("foo", req.get_param_value("param1"));
  10065. EXPECT_EQ("bar", req.get_param_value("param2"));
  10066. });
  10067. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10068. EXPECT_EQ("user-id", req.path_params.at("id"));
  10069. EXPECT_EQ("foo", req.get_param_value("param1"));
  10070. EXPECT_EQ("bar", req.get_param_value("param2"));
  10071. });
  10072. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. listen_thread.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. {
  10080. Client cli(HOST, PORT);
  10081. Params params;
  10082. params.emplace("hello", "world");
  10083. params.emplace("hello2", "world2");
  10084. params.emplace("hello3", "world3");
  10085. auto res = cli.Get("/", params, Headers{});
  10086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. }
  10089. {
  10090. Client cli(HOST, PORT);
  10091. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. }
  10095. {
  10096. Client cli(HOST, PORT);
  10097. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10099. EXPECT_EQ(StatusCode::OK_200, res->status);
  10100. }
  10101. {
  10102. Client cli(HOST, PORT);
  10103. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10105. EXPECT_EQ(StatusCode::OK_200, res->status);
  10106. }
  10107. }
  10108. TEST(GetWithParametersTest, GetWithParameters2) {
  10109. Server svr;
  10110. svr.Get("/", [&](const Request &req, Response &res) {
  10111. auto text = req.get_param_value("hello");
  10112. res.set_content(text, "text/plain");
  10113. });
  10114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. listen_thread.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. });
  10120. svr.wait_until_ready();
  10121. Client cli("localhost", PORT);
  10122. Params params;
  10123. params.emplace("hello", "world");
  10124. std::string body;
  10125. auto res = cli.Get("/", params, Headers{},
  10126. [&](const char *data, size_t data_length) {
  10127. body.append(data, data_length);
  10128. return true;
  10129. });
  10130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10131. EXPECT_EQ(StatusCode::OK_200, res->status);
  10132. EXPECT_EQ("world", body);
  10133. }
  10134. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10135. Server svr;
  10136. svr.Get("/search", [&](const Request &req, Response &res) {
  10137. auto q = req.get_param_value("q");
  10138. res.set_content(q, "text/plain");
  10139. });
  10140. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10141. auto se = detail::scope_exit([&] {
  10142. svr.stop();
  10143. listen_thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. });
  10146. svr.wait_until_ready();
  10147. Client cli("localhost", PORT);
  10148. // Verify that Get(path, params) works without requiring Headers argument
  10149. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10151. EXPECT_EQ(StatusCode::OK_200, res->status);
  10152. EXPECT_EQ("cpp-httplib", res->body);
  10153. }
  10154. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10155. auto host = "httpbingo.org";
  10156. auto path = std::string{"/range/32"};
  10157. #ifdef CPPHTTPLIB_SSL_ENABLED
  10158. SSLClient cli(host);
  10159. #else
  10160. Client cli(host);
  10161. #endif
  10162. cli.set_default_headers({make_range_header({{1, 10}})});
  10163. cli.set_connection_timeout(5);
  10164. {
  10165. auto res = cli.Get(path);
  10166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10167. EXPECT_EQ("bcdefghijk", res->body);
  10168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10169. }
  10170. {
  10171. auto res = cli.Get(path);
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ("bcdefghijk", res->body);
  10174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10175. }
  10176. }
  10177. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10178. Server svr;
  10179. svr.set_default_headers({{"Hello", "World"}});
  10180. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10181. res.set_content("ok", "text/plain");
  10182. });
  10183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. listen_thread.join();
  10187. ASSERT_FALSE(svr.is_running());
  10188. });
  10189. svr.wait_until_ready();
  10190. Client cli("localhost", PORT);
  10191. auto res = cli.Get("/");
  10192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10193. EXPECT_EQ(StatusCode::OK_200, res->status);
  10194. EXPECT_EQ("ok", res->body);
  10195. EXPECT_EQ("World", res->get_header_value("Hello"));
  10196. }
  10197. #ifdef CPPHTTPLIB_SSL_ENABLED
  10198. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(svr.is_valid());
  10201. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10202. std::this_thread::sleep_for(std::chrono::seconds(2));
  10203. res.set_content("a", "text/plain");
  10204. });
  10205. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10206. res.set_content("b", "text/plain");
  10207. });
  10208. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10209. auto se = detail::scope_exit([&] {
  10210. svr.stop();
  10211. listen_thread.join();
  10212. ASSERT_FALSE(svr.is_running());
  10213. });
  10214. svr.wait_until_ready();
  10215. SSLClient cli("localhost", PORT);
  10216. cli.enable_server_certificate_verification(false);
  10217. cli.set_keep_alive(true);
  10218. cli.set_read_timeout(std::chrono::seconds(1));
  10219. auto resa = cli.Get("/a");
  10220. ASSERT_TRUE(!resa);
  10221. EXPECT_EQ(Error::Read, resa.error());
  10222. auto resb = cli.Get("/b");
  10223. ASSERT_TRUE(resb);
  10224. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10225. EXPECT_EQ("b", resb->body);
  10226. }
  10227. // Closing an idle keep-alive connection sends close_notify and returns. The
  10228. // server must not wait for the client's close_notify: an idle client never
  10229. // sends one, so the worker would be held until the read timeout expires, and
  10230. // stop() would wait for it.
  10231. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10233. ASSERT_TRUE(svr.is_valid());
  10234. svr.set_keep_alive_timeout(1);
  10235. svr.set_read_timeout(10, 0);
  10236. svr.Get("/", [](const Request &, Response &res) {
  10237. res.set_content("ok", "text/plain");
  10238. });
  10239. auto port = svr.bind_to_any_port(HOST);
  10240. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10241. auto se = detail::scope_exit([&] {
  10242. if (listen_thread.joinable()) {
  10243. svr.stop();
  10244. listen_thread.join();
  10245. }
  10246. });
  10247. svr.wait_until_ready();
  10248. SSLClient cli(HOST, port);
  10249. cli.enable_server_certificate_verification(false);
  10250. cli.set_keep_alive(true);
  10251. auto res = cli.Get("/");
  10252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10253. EXPECT_EQ(StatusCode::OK_200, res->status);
  10254. // Stay idle past the keep-alive timeout so the server closes the connection.
  10255. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10256. auto start = std::chrono::steady_clock::now();
  10257. svr.stop();
  10258. listen_thread.join();
  10259. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10260. std::chrono::steady_clock::now() - start)
  10261. .count();
  10262. EXPECT_LT(elapsed, 3000);
  10263. }
  10264. #endif
  10265. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10266. protected:
  10267. ServerTestWithAI_PASSIVE()
  10268. : cli_(HOST, PORT)
  10269. #ifdef CPPHTTPLIB_SSL_ENABLED
  10270. ,
  10271. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10272. #endif
  10273. {
  10274. #ifdef CPPHTTPLIB_SSL_ENABLED
  10275. cli_.enable_server_certificate_verification(false);
  10276. #endif
  10277. }
  10278. virtual void SetUp() {
  10279. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10280. res.set_content("Hello World!", "text/plain");
  10281. });
  10282. t_ = thread(
  10283. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10284. svr_.wait_until_ready();
  10285. }
  10286. virtual void TearDown() {
  10287. svr_.stop();
  10288. t_.join();
  10289. }
  10290. #ifdef CPPHTTPLIB_SSL_ENABLED
  10291. SSLClient cli_;
  10292. SSLServer svr_;
  10293. #else
  10294. Client cli_;
  10295. Server svr_;
  10296. #endif
  10297. thread t_;
  10298. };
  10299. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10300. auto res = cli_.Get("/hi");
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. EXPECT_EQ(StatusCode::OK_200, res->status);
  10303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10304. EXPECT_EQ("Hello World!", res->body);
  10305. }
  10306. class ServerUpDownTest : public ::testing::Test {
  10307. protected:
  10308. ServerUpDownTest() : cli_(HOST, PORT) {}
  10309. virtual void SetUp() {
  10310. t_ = thread([&]() {
  10311. svr_.bind_to_any_port(HOST);
  10312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10313. ASSERT_TRUE(svr_.listen_after_bind());
  10314. });
  10315. svr_.wait_until_ready();
  10316. }
  10317. virtual void TearDown() {
  10318. svr_.stop();
  10319. t_.join();
  10320. }
  10321. Client cli_;
  10322. Server svr_;
  10323. thread t_;
  10324. };
  10325. TEST_F(ServerUpDownTest, QuickStartStop) {
  10326. // Should not crash, especially when run with
  10327. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10328. }
  10329. class PayloadMaxLengthTest : public ::testing::Test {
  10330. protected:
  10331. PayloadMaxLengthTest()
  10332. : cli_(HOST, PORT)
  10333. #ifdef CPPHTTPLIB_SSL_ENABLED
  10334. ,
  10335. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10336. #endif
  10337. {
  10338. #ifdef CPPHTTPLIB_SSL_ENABLED
  10339. cli_.enable_server_certificate_verification(false);
  10340. #endif
  10341. }
  10342. virtual void SetUp() {
  10343. svr_.set_payload_max_length(8);
  10344. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10345. res.set_content("test", "text/plain");
  10346. });
  10347. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10348. svr_.wait_until_ready();
  10349. }
  10350. virtual void TearDown() {
  10351. svr_.stop();
  10352. t_.join();
  10353. }
  10354. #ifdef CPPHTTPLIB_SSL_ENABLED
  10355. SSLClient cli_;
  10356. SSLServer svr_;
  10357. #else
  10358. Client cli_;
  10359. Server svr_;
  10360. #endif
  10361. thread t_;
  10362. };
  10363. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10364. auto res = cli_.Post("/test", "123456789", "text/plain");
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10367. res = cli_.Post("/test", "12345678", "text/plain");
  10368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10369. EXPECT_EQ(StatusCode::OK_200, res->status);
  10370. }
  10371. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10372. // Test chunked encoding with payload exceeding the 8-byte limit
  10373. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10374. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10377. }
  10378. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10379. // Test chunked encoding with payload within the 8-byte limit
  10380. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10381. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(StatusCode::OK_200, res->status);
  10384. }
  10385. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10386. // Test using send_request to send chunked data exceeding payload limit
  10387. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10388. "Host: " +
  10389. std::string(HOST) + ":" + std::to_string(PORT) +
  10390. "\r\n"
  10391. "Transfer-Encoding: chunked\r\n"
  10392. "Connection: close\r\n"
  10393. "\r\n"
  10394. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10395. "0123456789\r\n"
  10396. "0\r\n" // End chunk
  10397. "\r\n";
  10398. std::string response;
  10399. bool result = send_request(1, chunked_request, &response);
  10400. if (!result) {
  10401. // If send_request fails, it might be because the server closed the
  10402. // connection due to payload limit enforcement, which is acceptable
  10403. SUCCEED()
  10404. << "Server rejected oversized chunked request (connection closed)";
  10405. } else {
  10406. // If we got a response, check if it's an error response or connection was
  10407. // closed early Short response length indicates connection was closed due to
  10408. // payload limit
  10409. if (response.length() <= 10) {
  10410. SUCCEED() << "Server closed connection for oversized chunked request";
  10411. } else {
  10412. // Check for error status codes
  10413. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10414. response.find("Payload Too Large") != std::string::npos ||
  10415. response.find("400") != std::string::npos);
  10416. }
  10417. }
  10418. }
  10419. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10420. // Test request without Content-Length header exceeding payload limit
  10421. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10422. "Host: " +
  10423. std::string(HOST) + ":" +
  10424. std::to_string(PORT) +
  10425. "\r\n"
  10426. "Connection: close\r\n"
  10427. "\r\n";
  10428. // Add payload exceeding the 8-byte limit
  10429. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10430. request_without_content_length += large_payload;
  10431. std::string response;
  10432. bool result = send_request(1, request_without_content_length, &response);
  10433. if (!result) {
  10434. // If send_request fails, server likely closed connection due to payload
  10435. // limit
  10436. SUCCEED() << "Server rejected oversized request without Content-Length "
  10437. "(connection closed)";
  10438. } else {
  10439. // Check if server responded with error or closed connection early
  10440. if (response.length() <= 10) {
  10441. SUCCEED() << "Server closed connection for oversized request without "
  10442. "Content-Length";
  10443. } else {
  10444. // Check for error status codes
  10445. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10446. response.find("Payload Too Large") != std::string::npos ||
  10447. response.find("400") != std::string::npos);
  10448. }
  10449. }
  10450. }
  10451. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10452. // Test request without Content-Length header within payload limit
  10453. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10454. "Host: " +
  10455. std::string(HOST) + ":" +
  10456. std::to_string(PORT) +
  10457. "\r\n"
  10458. "Connection: close\r\n"
  10459. "\r\n";
  10460. // Add payload within the 8-byte limit
  10461. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10462. request_without_content_length += small_payload;
  10463. std::string response;
  10464. bool result = send_request(1, request_without_content_length, &response);
  10465. // For requests without Content-Length, the server may have different behavior
  10466. // The key is that it should not reject due to payload limit for small
  10467. // payloads
  10468. if (result) {
  10469. // Check for any HTTP response (success or error, but not connection closed)
  10470. if (response.length() > 10) {
  10471. SUCCEED()
  10472. << "Server processed request without Content-Length within limit";
  10473. } else {
  10474. // Short response might indicate connection closed, which is acceptable
  10475. SUCCEED() << "Server closed connection for request without "
  10476. "Content-Length (acceptable behavior)";
  10477. }
  10478. } else {
  10479. // Connection failure might be due to protocol requirements
  10480. SUCCEED() << "Connection issue with request without Content-Length "
  10481. "(environment-specific)";
  10482. }
  10483. }
  10484. class LargePayloadMaxLengthTest : public ::testing::Test {
  10485. protected:
  10486. LargePayloadMaxLengthTest()
  10487. : cli_(HOST, PORT)
  10488. #ifdef CPPHTTPLIB_SSL_ENABLED
  10489. ,
  10490. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10491. #endif
  10492. {
  10493. #ifdef CPPHTTPLIB_SSL_ENABLED
  10494. cli_.enable_server_certificate_verification(false);
  10495. #endif
  10496. }
  10497. virtual void SetUp() {
  10498. // Set 10MB payload limit
  10499. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10500. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10501. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10502. res.set_content("Large payload test", "text/plain");
  10503. });
  10504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10505. svr_.wait_until_ready();
  10506. }
  10507. virtual void TearDown() {
  10508. svr_.stop();
  10509. t_.join();
  10510. }
  10511. #ifdef CPPHTTPLIB_SSL_ENABLED
  10512. SSLClient cli_;
  10513. SSLServer svr_;
  10514. #else
  10515. Client cli_;
  10516. Server svr_;
  10517. #endif
  10518. thread t_;
  10519. };
  10520. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10521. // Test chunked encoding with payload within 10MB limit
  10522. std::string medium_payload(5 * 1024 * 1024,
  10523. 'A'); // 5MB payload, within 10MB limit
  10524. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::OK_200, res->status);
  10527. }
  10528. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10529. // Test chunked encoding with payload exceeding 10MB limit
  10530. std::string large_payload(12 * 1024 * 1024,
  10531. 'B'); // 12MB payload, exceeds 10MB limit
  10532. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10533. // Server may either return 413 or close the connection
  10534. if (res) {
  10535. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10536. } else {
  10537. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10538. }
  10539. }
  10540. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10541. // Test request without Content-Length header within 10MB limit
  10542. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10543. "Host: " +
  10544. std::string(HOST) + ":" +
  10545. std::to_string(PORT) +
  10546. "\r\n"
  10547. "Connection: close\r\n"
  10548. "\r\n";
  10549. // Add 1MB payload (within 10MB limit)
  10550. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10551. request_without_content_length += medium_payload;
  10552. std::string response;
  10553. bool result = send_request(5, request_without_content_length, &response);
  10554. if (result) {
  10555. // Should get a proper HTTP response for payloads within limit
  10556. if (response.length() > 10) {
  10557. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10558. "10MB limit";
  10559. } else {
  10560. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10561. "Content-Length)";
  10562. }
  10563. } else {
  10564. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10565. }
  10566. }
  10567. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10568. // Test request without Content-Length header exceeding 10MB limit
  10569. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10570. "Host: " +
  10571. std::string(HOST) + ":" +
  10572. std::to_string(PORT) +
  10573. "\r\n"
  10574. "Connection: close\r\n"
  10575. "\r\n";
  10576. // Add 12MB payload (exceeds 10MB limit)
  10577. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10578. request_without_content_length += large_payload;
  10579. std::string response;
  10580. bool result = send_request(10, request_without_content_length, &response);
  10581. if (!result) {
  10582. // Server should close connection due to payload limit
  10583. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10584. "(connection closed)";
  10585. } else {
  10586. // Check for error response
  10587. if (response.length() <= 10) {
  10588. SUCCEED()
  10589. << "Server closed connection for 12MB request exceeding 10MB limit";
  10590. } else {
  10591. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10592. response.find("Payload Too Large") != std::string::npos ||
  10593. response.find("400") != std::string::npos);
  10594. }
  10595. }
  10596. }
  10597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10598. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10599. // path.
  10600. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10601. Server svr;
  10602. const size_t LIMIT = 64 * 1024; // 64KB
  10603. svr.set_payload_max_length(LIMIT);
  10604. size_t total = 0;
  10605. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10606. const ContentReader &content_reader) {
  10607. content_reader([&](const char * /*data*/, size_t len) {
  10608. total += len;
  10609. return true;
  10610. });
  10611. res.status = 200;
  10612. res.set_content("stream_ok", "text/plain");
  10613. });
  10614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. thread.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. });
  10620. svr.wait_until_ready();
  10621. // Prepare 256KB raw data and gzip-compress it
  10622. std::string raw(256 * 1024, 'A');
  10623. std::string gz;
  10624. {
  10625. z_stream zs{};
  10626. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10627. Z_DEFAULT_STRATEGY);
  10628. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10629. zs.avail_in = static_cast<uInt>(raw.size());
  10630. char outbuf[4096];
  10631. int ret;
  10632. do {
  10633. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10634. zs.avail_out = sizeof(outbuf);
  10635. ret = deflate(&zs, Z_FINISH);
  10636. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10637. } while (ret != Z_STREAM_END);
  10638. deflateEnd(&zs);
  10639. }
  10640. Client cli(HOST, PORT);
  10641. cli.set_connection_timeout(std::chrono::seconds(5));
  10642. Headers headers = {{"Content-Encoding", "gzip"}};
  10643. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10644. "application/octet-stream");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. // Server must reject oversized decompressed payloads with 413.
  10647. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10648. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10649. EXPECT_LE(total, LIMIT);
  10650. }
  10651. #ifndef CPPHTTPLIB_SSL_ENABLED
  10652. // For a request with neither Content-Length nor Transfer-Encoding, the
  10653. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10654. // compressed wire bytes straight to the ContentReader without ever routing
  10655. // them through the decompressor, so payload_max_length_ only bounded the
  10656. // compressed size on the wire, not the decompressed size.
  10657. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10658. Server svr;
  10659. const size_t LIMIT = 64 * 1024; // 64KB
  10660. svr.set_payload_max_length(LIMIT);
  10661. size_t total = 0;
  10662. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10663. const ContentReader &content_reader) {
  10664. content_reader([&](const char * /*data*/, size_t len) {
  10665. total += len;
  10666. return true;
  10667. });
  10668. res.status = 200;
  10669. res.set_content("stream_ok", "text/plain");
  10670. });
  10671. auto port = svr.bind_to_any_port(HOST);
  10672. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10673. auto se = detail::scope_exit([&] {
  10674. svr.stop();
  10675. thread.join();
  10676. ASSERT_FALSE(svr.is_running());
  10677. });
  10678. svr.wait_until_ready();
  10679. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10680. // StreamingGzipDecompression test above.
  10681. std::string raw(256 * 1024, 'A');
  10682. std::string gz;
  10683. {
  10684. httplib::detail::gzip_compressor compressor;
  10685. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10686. [&](const char *chunk, size_t len) {
  10687. gz.append(chunk, len);
  10688. return true;
  10689. });
  10690. ASSERT_TRUE(result);
  10691. }
  10692. // Send the gzip body over raw TCP with neither Content-Length nor
  10693. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10694. // kicks in.
  10695. std::string req = "POST /stream HTTP/1.1\r\n"
  10696. "Host: " +
  10697. std::string(HOST) + ":" + std::to_string(port) +
  10698. "\r\n"
  10699. "Content-Encoding: gzip\r\n"
  10700. "Connection: close\r\n"
  10701. "\r\n" +
  10702. gz;
  10703. std::string response;
  10704. ASSERT_TRUE(send_request(5, req, &response, port));
  10705. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10706. EXPECT_LE(total, LIMIT);
  10707. }
  10708. #endif
  10709. #endif
  10710. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10711. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10712. // the payload must be passed through untouched instead of being rejected.
  10713. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10714. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10715. Server svr;
  10716. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10717. res.set_content(body, "image/jpeg");
  10718. res.set_header("Content-Encoding", "UTF-8");
  10719. });
  10720. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10721. res.set_content(body, "image/jpeg");
  10722. res.set_header("Content-Encoding", "identity");
  10723. });
  10724. svr.Post("/echo", [](const Request &req, Response &res) {
  10725. res.set_content(req.body, "image/jpeg");
  10726. });
  10727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, PORT);
  10735. {
  10736. auto res = cli.Get("/image");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. EXPECT_EQ(body, res->body);
  10740. }
  10741. {
  10742. auto res = cli.Get("/identity");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::OK_200, res->status);
  10745. EXPECT_EQ(body, res->body);
  10746. }
  10747. {
  10748. // The same applies to a request body reaching the server.
  10749. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10750. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res->status);
  10753. EXPECT_EQ(body, res->body);
  10754. }
  10755. }
  10756. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10757. // gzip-encoded response even when the build has no zlib support.
  10758. static const char GZIPPED_HELLO_WORLD[] = {
  10759. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10760. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10761. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10762. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10763. // A content coding is a whole token, not something the field value merely
  10764. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10765. // as "fibre" look like Brotli, and turned a multi-coding value like
  10766. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10767. // it was never meant to see.
  10768. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10769. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10770. Server svr;
  10771. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10772. res.set_content(body, "image/jpeg");
  10773. res.set_header("Content-Encoding", "fibre");
  10774. });
  10775. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10776. res.set_content(body, "image/jpeg");
  10777. res.set_header("Content-Encoding", "gzip, br");
  10778. });
  10779. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10780. res.set_content(body, "image/jpeg");
  10781. res.set_header("Content-Encoding", "x-zstd-ish");
  10782. });
  10783. auto port = svr.bind_to_any_port(HOST);
  10784. thread t = thread([&]() { svr.listen_after_bind(); });
  10785. auto se = detail::scope_exit([&] {
  10786. svr.stop();
  10787. t.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. svr.wait_until_ready();
  10791. Client cli(HOST, port);
  10792. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10793. auto res = cli.Get(path);
  10794. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10796. // Not a coding we recognize, so the payload comes back untouched
  10797. EXPECT_EQ(body, res->body) << path;
  10798. }
  10799. }
  10800. // A content coding cpp-httplib recognizes but was not built with must be
  10801. // reported as such. Handing the still-compressed payload back to the caller
  10802. // would silently corrupt it.
  10803. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10804. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10805. Server svr;
  10806. // "image/jpeg" keeps the server from applying a content coding of its own,
  10807. // so the hand-crafted Content-Encoding below survives.
  10808. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10809. res.set_content(gzipped, "image/jpeg");
  10810. res.set_header("Content-Encoding", "gzip");
  10811. });
  10812. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10813. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10814. res.set_content(gzipped, "image/jpeg");
  10815. res.set_header("Content-Encoding", "GZIP");
  10816. });
  10817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. ASSERT_FALSE(svr.is_running());
  10822. });
  10823. svr.wait_until_ready();
  10824. Client cli(HOST, PORT);
  10825. {
  10826. auto res = cli.Get("/gzipped");
  10827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ("Hello World!", res->body);
  10830. #else
  10831. ASSERT_FALSE(res);
  10832. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10833. #endif
  10834. }
  10835. {
  10836. // open_stream() must behave the same way.
  10837. auto handle = cli.open_stream("GET", "/gzipped");
  10838. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10839. ASSERT_TRUE(handle.is_valid());
  10840. std::string received;
  10841. char buf[256];
  10842. ssize_t n;
  10843. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10844. received.append(buf, static_cast<size_t>(n));
  10845. }
  10846. EXPECT_EQ("Hello World!", received);
  10847. #else
  10848. EXPECT_FALSE(handle.is_valid());
  10849. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10850. #endif
  10851. }
  10852. {
  10853. // A differently-cased coding must not be mistaken for an unknown one, or
  10854. // the body would be handed back still compressed.
  10855. auto res = cli.Get("/gzipped-uppercase");
  10856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10858. EXPECT_EQ("Hello World!", res->body);
  10859. #else
  10860. ASSERT_FALSE(res);
  10861. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10862. #endif
  10863. }
  10864. }
  10865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10866. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10867. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10868. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10869. // body a second time and appending a second Content-Encoding field line, so
  10870. // clients that decode one coding per listed value handed back raw gzip bytes.
  10871. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10872. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10873. Server svr;
  10874. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10875. // keeps the server from applying a coding of its own.
  10876. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10877. res.set_content(gzipped, "text/plain");
  10878. res.set_header("Content-Encoding", "gzip");
  10879. });
  10880. auto port = svr.bind_to_any_port(HOST);
  10881. thread t = thread([&]() { svr.listen_after_bind(); });
  10882. auto se = detail::scope_exit([&] {
  10883. svr.stop();
  10884. t.join();
  10885. ASSERT_FALSE(svr.is_running());
  10886. });
  10887. svr.wait_until_ready();
  10888. Client cli(HOST, port);
  10889. Headers headers = {{"Accept-Encoding", "gzip"}};
  10890. auto res = cli.Get("/pre-gzipped", headers);
  10891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10892. EXPECT_EQ(StatusCode::OK_200, res->status);
  10893. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10894. EXPECT_EQ("Hello World!", res->body);
  10895. }
  10896. // A chunked provider settles its coding where the headers are written and
  10897. // reuses it at write time. Both ends of that have to hold: a handler's own
  10898. // Content-Encoding suppresses the coding, and a response without one is still
  10899. // compressed as it always was.
  10900. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10901. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10902. const std::string plain = "Hello World! Hello World! Hello World!";
  10903. Server svr;
  10904. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10905. res.set_header("Content-Encoding", "gzip");
  10906. res.set_chunked_content_provider(
  10907. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10908. sink.write(gzipped.data(), gzipped.size());
  10909. sink.done();
  10910. return true;
  10911. });
  10912. });
  10913. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10914. res.set_chunked_content_provider(
  10915. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10916. sink.write(plain.data(), plain.size());
  10917. sink.done();
  10918. return true;
  10919. });
  10920. });
  10921. auto port = svr.bind_to_any_port(HOST);
  10922. thread t = thread([&]() { svr.listen_after_bind(); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, port);
  10930. Headers headers = {{"Accept-Encoding", "gzip"}};
  10931. {
  10932. auto res = cli.Get("/pre-gzipped", headers);
  10933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10934. EXPECT_EQ(StatusCode::OK_200, res->status);
  10935. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10936. EXPECT_EQ("Hello World!", res->body);
  10937. }
  10938. {
  10939. auto res = cli.Get("/negotiated", headers);
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(StatusCode::OK_200, res->status);
  10942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10943. EXPECT_EQ(plain, res->body);
  10944. }
  10945. }
  10946. #endif
  10947. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10948. // the same message as the comma-joined one, so both have to be read the same
  10949. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10950. // single gzip coding, and a body the sender says was encoded twice was handed
  10951. // back after one pass, still compressed but presented as decoded.
  10952. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10953. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10954. Server svr;
  10955. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10956. res.set_content(body, "image/jpeg");
  10957. res.headers.emplace("Content-Encoding", "gzip");
  10958. res.headers.emplace("Content-Encoding", "gzip");
  10959. });
  10960. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10961. res.set_content(body, "image/jpeg");
  10962. res.set_header("Content-Encoding", "gzip, gzip");
  10963. });
  10964. auto port = svr.bind_to_any_port(HOST);
  10965. thread t = thread([&]() { svr.listen_after_bind(); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. });
  10971. svr.wait_until_ready();
  10972. Client cli(HOST, port);
  10973. // Two codings is not something cpp-httplib decodes, so both representations
  10974. // take the pass-through path rather than one of them being gunzipped once.
  10975. for (const char *path : {"/split", "/joined"}) {
  10976. auto res = cli.Get(path);
  10977. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10978. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10979. EXPECT_EQ(body, res->body) << path;
  10980. }
  10981. }
  10982. // Regression test for DoS vulnerability: a malicious server sending a response
  10983. // without Content-Length header must not cause unbounded memory consumption on
  10984. // the client side. The client should stop reading after a reasonable limit,
  10985. // similar to the server-side set_payload_max_length protection.
  10986. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10987. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10988. #ifndef _WIN32
  10989. signal(SIGPIPE, SIG_IGN);
  10990. #endif
  10991. auto server_thread = std::thread([] {
  10992. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10994. default_socket_options(srv);
  10995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10997. sockaddr_in addr{};
  10998. addr.sin_family = AF_INET;
  10999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11001. int opt = 1;
  11002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11003. #ifdef _WIN32
  11004. reinterpret_cast<const char *>(&opt),
  11005. #else
  11006. &opt,
  11007. #endif
  11008. sizeof(opt));
  11009. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11010. ::listen(srv, 1);
  11011. sockaddr_in cli_addr{};
  11012. socklen_t cli_len = sizeof(cli_addr);
  11013. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11014. if (cli != INVALID_SOCKET) {
  11015. char buf[4096];
  11016. ::recv(cli, buf, sizeof(buf), 0);
  11017. // Malicious response: no Content-Length, no chunked encoding
  11018. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11019. "Connection: close\r\n"
  11020. "\r\n";
  11021. ::send(cli,
  11022. #ifdef _WIN32
  11023. static_cast<const char *>(response_header.c_str()),
  11024. static_cast<int>(response_header.size()),
  11025. #else
  11026. response_header.c_str(), response_header.size(),
  11027. #endif
  11028. 0);
  11029. // Send 10MB of data
  11030. std::string chunk(64 * 1024, 'A');
  11031. size_t total_sent = 0;
  11032. while (total_sent < MALICIOUS_DATA_SIZE) {
  11033. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11034. auto sent = ::send(cli,
  11035. #ifdef _WIN32
  11036. static_cast<const char *>(chunk.c_str()),
  11037. static_cast<int>(to_send),
  11038. #else
  11039. chunk.c_str(), to_send,
  11040. #endif
  11041. 0);
  11042. if (sent <= 0) break;
  11043. total_sent += static_cast<size_t>(sent);
  11044. }
  11045. detail::close_socket(cli);
  11046. }
  11047. detail::close_socket(srv);
  11048. });
  11049. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11050. size_t total_read = 0;
  11051. {
  11052. Client cli("127.0.0.1", PORT + 2);
  11053. cli.set_read_timeout(5, 0);
  11054. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11055. auto stream = cli.open_stream("GET", "/malicious");
  11056. ASSERT_TRUE(stream.is_valid());
  11057. char buffer[64 * 1024];
  11058. ssize_t n;
  11059. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11060. total_read += static_cast<size_t>(n);
  11061. }
  11062. } // StreamHandle and Client destroyed here, closing the socket
  11063. server_thread.join();
  11064. // With set_payload_max_length, the client must stop reading before consuming
  11065. // all 10MB. The read loop should be cut off at or near the configured limit.
  11066. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11067. << "Client read " << total_read << " bytes, exceeding the configured "
  11068. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11069. }
  11070. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11071. // the entire response body without truncation.
  11072. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11073. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11074. #ifndef _WIN32
  11075. signal(SIGPIPE, SIG_IGN);
  11076. #endif
  11077. auto server_thread = std::thread([] {
  11078. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11079. default_socket_options(srv);
  11080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11081. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11082. sockaddr_in addr{};
  11083. addr.sin_family = AF_INET;
  11084. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11085. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11086. int opt = 1;
  11087. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11088. #ifdef _WIN32
  11089. reinterpret_cast<const char *>(&opt),
  11090. #else
  11091. &opt,
  11092. #endif
  11093. sizeof(opt));
  11094. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11095. ::listen(srv, 1);
  11096. sockaddr_in cli_addr{};
  11097. socklen_t cli_len = sizeof(cli_addr);
  11098. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11099. if (cli != INVALID_SOCKET) {
  11100. char buf[4096];
  11101. ::recv(cli, buf, sizeof(buf), 0);
  11102. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11103. "Connection: close\r\n"
  11104. "\r\n";
  11105. ::send(cli,
  11106. #ifdef _WIN32
  11107. static_cast<const char *>(response_header.c_str()),
  11108. static_cast<int>(response_header.size()),
  11109. #else
  11110. response_header.c_str(), response_header.size(),
  11111. #endif
  11112. 0);
  11113. std::string chunk(64 * 1024, 'A');
  11114. size_t total_sent = 0;
  11115. while (total_sent < DATA_SIZE) {
  11116. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11117. auto sent = ::send(cli,
  11118. #ifdef _WIN32
  11119. static_cast<const char *>(chunk.c_str()),
  11120. static_cast<int>(to_send),
  11121. #else
  11122. chunk.c_str(), to_send,
  11123. #endif
  11124. 0);
  11125. if (sent <= 0) break;
  11126. total_sent += static_cast<size_t>(sent);
  11127. }
  11128. #ifdef _WIN32
  11129. ::shutdown(cli, SD_SEND);
  11130. #else
  11131. ::shutdown(cli, SHUT_WR);
  11132. #endif
  11133. // Drain until the client closes its end, ensuring all data is delivered
  11134. char drain[1024];
  11135. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11136. detail::close_socket(cli);
  11137. }
  11138. detail::close_socket(srv);
  11139. });
  11140. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11141. size_t total_read = 0;
  11142. {
  11143. Client cli("127.0.0.1", PORT + 2);
  11144. cli.set_read_timeout(5, 0);
  11145. cli.set_payload_max_length(0); // 0 means no limit
  11146. auto stream = cli.open_stream("GET", "/data");
  11147. ASSERT_TRUE(stream.is_valid());
  11148. char buffer[64 * 1024];
  11149. ssize_t n;
  11150. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11151. total_read += static_cast<size_t>(n);
  11152. }
  11153. }
  11154. server_thread.join();
  11155. EXPECT_EQ(total_read, DATA_SIZE)
  11156. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11157. << " bytes without truncation, but only read " << total_read << " bytes.";
  11158. }
  11159. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11160. // enormous Content-Length must not cause the client to pre-allocate a huge
  11161. // response body buffer. The reservation is capped at payload_max_length_, and
  11162. // the read itself fails when the body exceeds the limit.
  11163. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11164. #ifndef _WIN32
  11165. signal(SIGPIPE, SIG_IGN);
  11166. #endif
  11167. auto server_thread = std::thread([] {
  11168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11169. default_socket_options(srv);
  11170. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11171. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11172. sockaddr_in addr{};
  11173. addr.sin_family = AF_INET;
  11174. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11176. int opt = 1;
  11177. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11178. #ifdef _WIN32
  11179. reinterpret_cast<const char *>(&opt),
  11180. #else
  11181. &opt,
  11182. #endif
  11183. sizeof(opt));
  11184. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11185. ::listen(srv, 1);
  11186. sockaddr_in cli_addr{};
  11187. socklen_t cli_len = sizeof(cli_addr);
  11188. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11189. if (cli != INVALID_SOCKET) {
  11190. char buf[4096];
  11191. ::recv(cli, buf, sizeof(buf), 0);
  11192. // Malicious response: claim a 20GB body but send only a tiny payload.
  11193. std::string response = "HTTP/1.1 200 OK\r\n"
  11194. "Content-Length: 20000000000\r\n"
  11195. "\r\n"
  11196. "abc";
  11197. ::send(cli,
  11198. #ifdef _WIN32
  11199. static_cast<const char *>(response.c_str()),
  11200. static_cast<int>(response.size()),
  11201. #else
  11202. response.c_str(), response.size(),
  11203. #endif
  11204. 0);
  11205. detail::close_socket(cli);
  11206. }
  11207. detail::close_socket(srv);
  11208. });
  11209. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11210. {
  11211. Client cli("127.0.0.1", PORT + 2);
  11212. cli.set_read_timeout(5, 0);
  11213. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11214. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11215. // (server claims more bytes than payload_max_length permits), but it must
  11216. // not exhaust memory before getting there.
  11217. auto res = cli.Get("/malicious");
  11218. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11219. }
  11220. server_thread.join();
  11221. }
  11222. // Verify that content_receiver bypasses the default payload_max_length,
  11223. // allowing streaming downloads larger than 100MB without requiring an explicit
  11224. // set_payload_max_length call.
  11225. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11226. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11227. #ifndef _WIN32
  11228. signal(SIGPIPE, SIG_IGN);
  11229. #endif
  11230. auto server_thread = std::thread([] {
  11231. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11232. default_socket_options(srv);
  11233. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11234. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11235. sockaddr_in addr{};
  11236. addr.sin_family = AF_INET;
  11237. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11238. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11239. int opt = 1;
  11240. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11241. #ifdef _WIN32
  11242. reinterpret_cast<const char *>(&opt),
  11243. #else
  11244. &opt,
  11245. #endif
  11246. sizeof(opt));
  11247. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11248. ::listen(srv, 1);
  11249. sockaddr_in cli_addr{};
  11250. socklen_t cli_len = sizeof(cli_addr);
  11251. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11252. if (cli != INVALID_SOCKET) {
  11253. char buf[4096];
  11254. ::recv(cli, buf, sizeof(buf), 0);
  11255. // Response with Content-Length larger than default 100MB limit
  11256. auto content_length = std::to_string(DATA_SIZE);
  11257. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11258. "Content-Length: " +
  11259. content_length +
  11260. "\r\n"
  11261. "Connection: close\r\n"
  11262. "\r\n";
  11263. ::send(cli,
  11264. #ifdef _WIN32
  11265. static_cast<const char *>(response_header.c_str()),
  11266. static_cast<int>(response_header.size()),
  11267. #else
  11268. response_header.c_str(), response_header.size(),
  11269. #endif
  11270. 0);
  11271. std::string chunk(64 * 1024, 'A');
  11272. size_t total_sent = 0;
  11273. while (total_sent < DATA_SIZE) {
  11274. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11275. auto sent = ::send(cli,
  11276. #ifdef _WIN32
  11277. static_cast<const char *>(chunk.c_str()),
  11278. static_cast<int>(to_send),
  11279. #else
  11280. chunk.c_str(), to_send,
  11281. #endif
  11282. 0);
  11283. if (sent <= 0) break;
  11284. total_sent += static_cast<size_t>(sent);
  11285. }
  11286. detail::close_socket(cli);
  11287. }
  11288. detail::close_socket(srv);
  11289. });
  11290. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11291. size_t total_received = 0;
  11292. {
  11293. Client cli("127.0.0.1", PORT + 2);
  11294. cli.set_read_timeout(10, 0);
  11295. // Do NOT call set_payload_max_length — use the default 100MB limit
  11296. auto res =
  11297. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11298. total_received += data_length;
  11299. return true;
  11300. });
  11301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11302. EXPECT_EQ(StatusCode::OK_200, res->status);
  11303. }
  11304. server_thread.join();
  11305. EXPECT_EQ(total_received, DATA_SIZE)
  11306. << "With content_receiver, the client should read all " << DATA_SIZE
  11307. << " bytes despite the default 100MB payload_max_length, but only read "
  11308. << total_received << " bytes.";
  11309. }
  11310. // Verify that an explicit set_payload_max_length smaller than the response is
  11311. // enforced even when a content_receiver is used.
  11312. TEST(ClientVulnerabilityTest,
  11313. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11314. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11315. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11316. #ifndef _WIN32
  11317. signal(SIGPIPE, SIG_IGN);
  11318. #endif
  11319. auto server_thread = std::thread([] {
  11320. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11321. default_socket_options(srv);
  11322. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11323. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11324. sockaddr_in addr{};
  11325. addr.sin_family = AF_INET;
  11326. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11327. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11328. int opt = 1;
  11329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11330. #ifdef _WIN32
  11331. reinterpret_cast<const char *>(&opt),
  11332. #else
  11333. &opt,
  11334. #endif
  11335. sizeof(opt));
  11336. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11337. ::listen(srv, 1);
  11338. sockaddr_in cli_addr{};
  11339. socklen_t cli_len = sizeof(cli_addr);
  11340. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11341. if (cli != INVALID_SOCKET) {
  11342. char buf[4096];
  11343. ::recv(cli, buf, sizeof(buf), 0);
  11344. auto content_length = std::to_string(DATA_SIZE);
  11345. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11346. "Content-Length: " +
  11347. content_length +
  11348. "\r\n"
  11349. "Connection: close\r\n"
  11350. "\r\n";
  11351. ::send(cli,
  11352. #ifdef _WIN32
  11353. static_cast<const char *>(response_header.c_str()),
  11354. static_cast<int>(response_header.size()),
  11355. #else
  11356. response_header.c_str(), response_header.size(),
  11357. #endif
  11358. 0);
  11359. std::string chunk(64 * 1024, 'A');
  11360. size_t total_sent = 0;
  11361. while (total_sent < DATA_SIZE) {
  11362. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11363. auto sent = ::send(cli,
  11364. #ifdef _WIN32
  11365. static_cast<const char *>(chunk.c_str()),
  11366. static_cast<int>(to_send),
  11367. #else
  11368. chunk.c_str(), to_send,
  11369. #endif
  11370. 0);
  11371. if (sent <= 0) break;
  11372. total_sent += static_cast<size_t>(sent);
  11373. }
  11374. detail::close_socket(cli);
  11375. }
  11376. detail::close_socket(srv);
  11377. });
  11378. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11379. size_t total_received = 0;
  11380. {
  11381. Client cli("127.0.0.1", PORT + 2);
  11382. cli.set_read_timeout(10, 0);
  11383. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11384. auto res =
  11385. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11386. total_received += data_length;
  11387. return true;
  11388. });
  11389. // Should fail because 200MB exceeds the explicit 150MB limit
  11390. EXPECT_FALSE(res);
  11391. }
  11392. server_thread.join();
  11393. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11394. << "Client with content_receiver should respect the explicit "
  11395. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11396. << total_received << " bytes.";
  11397. }
  11398. // Verify that an explicit set_payload_max_length larger than the response
  11399. // allows the content_receiver to read all data successfully.
  11400. TEST(ClientVulnerabilityTest,
  11401. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11402. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11403. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11404. #ifndef _WIN32
  11405. signal(SIGPIPE, SIG_IGN);
  11406. #endif
  11407. auto server_thread = std::thread([] {
  11408. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11409. default_socket_options(srv);
  11410. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11411. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11412. sockaddr_in addr{};
  11413. addr.sin_family = AF_INET;
  11414. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11415. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11416. int opt = 1;
  11417. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11418. #ifdef _WIN32
  11419. reinterpret_cast<const char *>(&opt),
  11420. #else
  11421. &opt,
  11422. #endif
  11423. sizeof(opt));
  11424. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11425. ::listen(srv, 1);
  11426. sockaddr_in cli_addr{};
  11427. socklen_t cli_len = sizeof(cli_addr);
  11428. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11429. if (cli != INVALID_SOCKET) {
  11430. char buf[4096];
  11431. ::recv(cli, buf, sizeof(buf), 0);
  11432. auto content_length = std::to_string(DATA_SIZE);
  11433. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11434. "Content-Length: " +
  11435. content_length +
  11436. "\r\n"
  11437. "Connection: close\r\n"
  11438. "\r\n";
  11439. ::send(cli,
  11440. #ifdef _WIN32
  11441. static_cast<const char *>(response_header.c_str()),
  11442. static_cast<int>(response_header.size()),
  11443. #else
  11444. response_header.c_str(), response_header.size(),
  11445. #endif
  11446. 0);
  11447. std::string chunk(64 * 1024, 'A');
  11448. size_t total_sent = 0;
  11449. while (total_sent < DATA_SIZE) {
  11450. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11451. auto sent = ::send(cli,
  11452. #ifdef _WIN32
  11453. static_cast<const char *>(chunk.c_str()),
  11454. static_cast<int>(to_send),
  11455. #else
  11456. chunk.c_str(), to_send,
  11457. #endif
  11458. 0);
  11459. if (sent <= 0) break;
  11460. total_sent += static_cast<size_t>(sent);
  11461. }
  11462. #ifdef _WIN32
  11463. ::shutdown(cli, SD_SEND);
  11464. #else
  11465. ::shutdown(cli, SHUT_WR);
  11466. #endif
  11467. char drain[1024];
  11468. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11469. detail::close_socket(cli);
  11470. }
  11471. detail::close_socket(srv);
  11472. });
  11473. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11474. size_t total_received = 0;
  11475. {
  11476. Client cli("127.0.0.1", PORT + 2);
  11477. cli.set_read_timeout(10, 0);
  11478. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11479. auto res =
  11480. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11481. total_received += data_length;
  11482. return true;
  11483. });
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. }
  11487. server_thread.join();
  11488. EXPECT_EQ(total_received, DATA_SIZE)
  11489. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11490. << " bytes (larger than " << DATA_SIZE
  11491. << " bytes response), content_receiver should read all data, but only "
  11492. "read "
  11493. << total_received << " bytes.";
  11494. }
  11495. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11496. // Regression test for "zip bomb" attack on the client side: a malicious server
  11497. // sends a small gzip-compressed response that decompresses to a huge payload.
  11498. // The client must enforce payload_max_length on the decompressed size.
  11499. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11500. constexpr size_t DECOMPRESSED_SIZE =
  11501. 10 * 1024 * 1024; // 10MB after decompression
  11502. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11503. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11504. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11505. std::string compressed;
  11506. {
  11507. httplib::detail::gzip_compressor compressor;
  11508. bool ok =
  11509. compressor.compress(uncompressed.data(), uncompressed.size(),
  11510. /*last=*/true, [&](const char *buf, size_t len) {
  11511. compressed.append(buf, len);
  11512. return true;
  11513. });
  11514. ASSERT_TRUE(ok);
  11515. }
  11516. // Sanity: compressed data should be much smaller than the decompressed size
  11517. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11518. #ifndef _WIN32
  11519. signal(SIGPIPE, SIG_IGN);
  11520. #endif
  11521. // Set up the listening socket in the main thread so the server is guaranteed
  11522. // to be ready before the client connects (eliminates race condition).
  11523. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11524. default_socket_options(srv);
  11525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11526. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11527. sockaddr_in addr{};
  11528. addr.sin_family = AF_INET;
  11529. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11530. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11531. int opt = 1;
  11532. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11533. #ifdef _WIN32
  11534. reinterpret_cast<const char *>(&opt),
  11535. #else
  11536. &opt,
  11537. #endif
  11538. sizeof(opt));
  11539. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11540. ASSERT_EQ(0, ::listen(srv, 1));
  11541. auto server_thread = std::thread([&compressed, srv] {
  11542. sockaddr_in cli_addr{};
  11543. socklen_t cli_len = sizeof(cli_addr);
  11544. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11545. if (cli != INVALID_SOCKET) {
  11546. // Read the full HTTP request (until \r\n\r\n)
  11547. char buf[4096];
  11548. size_t total = 0;
  11549. while (total < sizeof(buf)) {
  11550. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11551. if (n <= 0) break;
  11552. total += static_cast<size_t>(n);
  11553. // Check for end of headers
  11554. if (total >= 4) {
  11555. std::string req(buf, total);
  11556. if (req.find("\r\n\r\n") != std::string::npos) break;
  11557. }
  11558. }
  11559. // Malicious response: gzip-compressed body, no Content-Length
  11560. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11561. "Content-Encoding: gzip\r\n"
  11562. "Connection: close\r\n"
  11563. "\r\n";
  11564. ::send(cli,
  11565. #ifdef _WIN32
  11566. static_cast<const char *>(response_header.c_str()),
  11567. static_cast<int>(response_header.size()),
  11568. #else
  11569. response_header.c_str(), response_header.size(),
  11570. #endif
  11571. 0);
  11572. // Send the compressed payload (small on the wire, huge when decompressed)
  11573. size_t total_sent = 0;
  11574. while (total_sent < compressed.size()) {
  11575. auto to_send = std::min(compressed.size() - total_sent,
  11576. static_cast<size_t>(64 * 1024));
  11577. auto sent =
  11578. ::send(cli,
  11579. #ifdef _WIN32
  11580. static_cast<const char *>(compressed.c_str() + total_sent),
  11581. static_cast<int>(to_send),
  11582. #else
  11583. compressed.c_str() + total_sent, to_send,
  11584. #endif
  11585. 0);
  11586. if (sent <= 0) break;
  11587. total_sent += static_cast<size_t>(sent);
  11588. }
  11589. detail::close_socket(cli);
  11590. }
  11591. });
  11592. auto se = detail::scope_exit([&] {
  11593. detail::close_socket(srv);
  11594. server_thread.join();
  11595. });
  11596. size_t total_decompressed = 0;
  11597. {
  11598. Client cli("127.0.0.1", PORT + 3);
  11599. cli.set_read_timeout(5, 0);
  11600. cli.set_decompress(true);
  11601. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11602. auto stream = cli.open_stream("GET", "/zipbomb");
  11603. ASSERT_TRUE(stream.is_valid());
  11604. char buffer[64 * 1024];
  11605. ssize_t n;
  11606. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11607. total_decompressed += static_cast<size_t>(n);
  11608. }
  11609. }
  11610. // The decompressed size must be capped by payload_max_length. Without
  11611. // protection, the client would decompress the full 10MB from a tiny
  11612. // compressed payload, enabling a zip bomb DoS attack.
  11613. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11614. << "Client decompressed " << total_decompressed
  11615. << " bytes from a gzip response. The decompressed size should be "
  11616. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11617. }
  11618. #endif
  11619. TEST(HostAndPortPropertiesTest, NoSSL) {
  11620. httplib::Client cli("www.google.com", 1234);
  11621. ASSERT_EQ("www.google.com", cli.host());
  11622. ASSERT_EQ(1234, cli.port());
  11623. }
  11624. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11625. httplib::Client cli("www.google.com:1234");
  11626. ASSERT_EQ("www.google.com", cli.host());
  11627. ASSERT_EQ(1234, cli.port());
  11628. }
  11629. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11630. // Port number that overflows int — should not crash, client becomes invalid
  11631. httplib::Client cli("http://www.google.com:99999999999999999999");
  11632. ASSERT_FALSE(cli.is_valid());
  11633. }
  11634. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11635. // Port 99999 exceeds valid range (1-65535) — should not crash
  11636. httplib::Client cli("http://www.google.com:99999");
  11637. ASSERT_FALSE(cli.is_valid());
  11638. }
  11639. #ifdef CPPHTTPLIB_SSL_ENABLED
  11640. TEST(HostAndPortPropertiesTest, SSL) {
  11641. httplib::SSLClient cli("www.google.com");
  11642. ASSERT_EQ("www.google.com", cli.host());
  11643. ASSERT_EQ(443, cli.port());
  11644. }
  11645. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11646. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11647. std::string cert;
  11648. read_file(CA_CERT_FILE, cert);
  11649. httplib::SSLClient httplib_client("www.google.com");
  11650. // Load CA store first time
  11651. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11652. // Load CA store second time (update)
  11653. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11654. // Verify client is still valid and can make connections
  11655. httplib_client.enable_server_certificate_verification(true);
  11656. auto res = httplib_client.Get("/");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. // Google may return 200 or 301 depending on various factors
  11659. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11660. res->status == StatusCode::MovedPermanently_301);
  11661. }
  11662. TEST(SSLClientTest, ServerNameIndication_Online) {
  11663. auto host = "httpbingo.org";
  11664. auto path = std::string{"/get"};
  11665. SSLClient cli(host, 443);
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. ASSERT_EQ(StatusCode::OK_200, res->status);
  11669. }
  11670. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11671. // Use a site that will cause SSL verification failure due to self-signed cert
  11672. SSLClient cli("self-signed.badssl.com", 443);
  11673. cli.enable_server_certificate_verification(true);
  11674. auto res = cli.Get("/");
  11675. ASSERT_TRUE(!res);
  11676. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11677. // Verify backend error is captured for SSLServerVerification
  11678. // This occurs when certificate verification fails
  11679. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11680. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11681. EXPECT_NE(0UL, res.ssl_backend_error());
  11682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11683. // For OpenSSL, ssl_error is 0 for verification errors
  11684. EXPECT_EQ(0, res.ssl_error());
  11685. #if !defined(_WIN32) || \
  11686. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11687. // On non-Windows or when Windows Schannel is disabled, the error comes
  11688. // from OpenSSL's verification
  11689. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11690. res.ssl_backend_error());
  11691. #endif
  11692. #endif
  11693. }
  11694. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11695. // Use a site where hostname doesn't match the certificate
  11696. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11697. SSLClient cli("wrong.host.badssl.com", 443);
  11698. cli.enable_server_certificate_verification(true);
  11699. cli.enable_server_hostname_verification(true);
  11700. auto res = cli.Get("/");
  11701. ASSERT_TRUE(!res);
  11702. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11703. // Verify backend error is captured for hostname verification failure
  11704. EXPECT_NE(0UL, res.ssl_backend_error());
  11705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11706. // For OpenSSL, ssl_error is 0 for verification errors
  11707. EXPECT_EQ(0, res.ssl_error());
  11708. #if !defined(_WIN32) || \
  11709. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11710. // On non-Windows or when Windows Schannel is disabled, the error comes
  11711. // from OpenSSL's hostname verification
  11712. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11713. res.ssl_backend_error());
  11714. #endif
  11715. #endif
  11716. }
  11717. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11718. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11719. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11720. SSLClient cli("www.google.com", 443);
  11721. cli.enable_server_certificate_verification(true);
  11722. auto res = cli.Get("/");
  11723. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11724. }
  11725. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11726. SSLClient cli("www.google.com", 443);
  11727. cli.enable_server_certificate_verification(true);
  11728. cli.enable_windows_certificate_verification(false);
  11729. auto res = cli.Get("/");
  11730. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11731. }
  11732. #endif
  11733. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11734. Client cli("https://google.com");
  11735. auto res = cli.Get("/");
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11738. }
  11739. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11740. SSLClient cli("google.com");
  11741. cli.set_ca_cert_path(CA_CERT_FILE);
  11742. auto res = cli.Get("/");
  11743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11744. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11745. }
  11746. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11747. SSLClient cli("google.com");
  11748. cli.enable_server_certificate_verification(true);
  11749. cli.set_ca_cert_path("hello");
  11750. auto res = cli.Get("/");
  11751. ASSERT_TRUE(!res);
  11752. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11753. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11754. // should be set
  11755. EXPECT_EQ(0, res.ssl_error());
  11756. // Verify backend error is captured for SSLLoadingCerts
  11757. // This error occurs when loading CA certificates fails
  11758. EXPECT_NE(0UL, res.ssl_backend_error());
  11759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11760. // OpenSSL specific error codes:
  11761. // > openssl errstr 0x80000002
  11762. // error:80000002:system library::No such file or directory
  11763. // > openssl errstr 0xA000126
  11764. // error:0A000126:SSL routines::unexpected eof while reading
  11765. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11766. res.ssl_backend_error() == 0xA000126);
  11767. #endif
  11768. }
  11769. TEST(SSLClientTest, ServerCertificateVerification4) {
  11770. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11771. ASSERT_TRUE(svr.is_valid());
  11772. svr.Get("/test", [&](const Request &, Response &res) {
  11773. res.set_content("test", "text/plain");
  11774. svr.stop();
  11775. ASSERT_TRUE(true);
  11776. });
  11777. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11778. auto se = detail::scope_exit([&] {
  11779. t.join();
  11780. ASSERT_FALSE(svr.is_running());
  11781. });
  11782. svr.wait_until_ready();
  11783. SSLClient cli("127.0.0.1", PORT);
  11784. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11785. cli.enable_server_certificate_verification(true);
  11786. cli.set_connection_timeout(30);
  11787. auto res = cli.Get("/test");
  11788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11789. ASSERT_EQ(StatusCode::OK_200, res->status);
  11790. }
  11791. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11792. std::string cert;
  11793. read_file(CA_CERT_FILE, cert);
  11794. SSLClient cli("google.com");
  11795. cli.load_ca_cert_store(cert.data(), cert.size());
  11796. const auto res = cli.Get("/");
  11797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11798. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11799. }
  11800. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11801. // clang-format off
  11802. static constexpr char cert[] =
  11803. "GlobalSign Root CA\n"
  11804. "==================\n"
  11805. "-----BEGIN CERTIFICATE-----\n"
  11806. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11807. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11808. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11809. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11810. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11811. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11812. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11813. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11814. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11815. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11816. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11817. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11818. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11819. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11820. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11821. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11822. "-----END CERTIFICATE-----\n";
  11823. // clang-format on
  11824. SSLClient cli("google.com");
  11825. cli.load_ca_cert_store(cert, sizeof(cert));
  11826. const auto res = cli.Get("/");
  11827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11829. }
  11830. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11831. SSLClient cli("www.youtube.com");
  11832. cli.set_ca_cert_path(CA_CERT_FILE);
  11833. cli.enable_server_certificate_verification(true);
  11834. cli.set_follow_location(true);
  11835. auto res = cli.Get("/");
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. ASSERT_EQ(StatusCode::OK_200, res->status);
  11838. }
  11839. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11840. SSLClient cli("wWw.YouTube.Com");
  11841. cli.set_ca_cert_path(CA_CERT_FILE);
  11842. cli.enable_server_certificate_verification(true);
  11843. cli.enable_server_hostname_verification(true);
  11844. cli.set_follow_location(true);
  11845. auto res = cli.Get("/");
  11846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11847. ASSERT_EQ(StatusCode::OK_200, res->status);
  11848. }
  11849. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11850. SSLClient cli("gOoGlE.COm");
  11851. cli.enable_server_certificate_verification(true);
  11852. cli.enable_server_hostname_verification(true);
  11853. cli.set_follow_location(true);
  11854. auto res = cli.Get("/");
  11855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11856. ASSERT_EQ(StatusCode::OK_200, res->status);
  11857. }
  11858. TEST(SSLClientTest, Issue2004_Online) {
  11859. Client client("https://google.com");
  11860. client.set_follow_location(true);
  11861. auto res = client.Get("/");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. ASSERT_EQ(StatusCode::OK_200, res->status);
  11864. auto body = res->body;
  11865. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11866. }
  11867. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11868. // Create SSLClient with invalid cert/key to make is_valid() return false
  11869. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11870. "nonexistent_key.pem");
  11871. // is_valid() should be false due to cert loading failure
  11872. ASSERT_FALSE(cli.is_valid());
  11873. auto res = cli.Get("/");
  11874. ASSERT_FALSE(res);
  11875. EXPECT_EQ(Error::SSLConnection, res.error());
  11876. }
  11877. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11878. // Test for Issue #2251: SSL error not properly reported when client cert
  11879. // and key paths are swapped or mismatched
  11880. // This simulates the scenario where user accidentally swaps the cert and key
  11881. // files
  11882. // Using client cert file as private key and vice versa (completely wrong)
  11883. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11884. // Should fail validation due to cert/key mismatch
  11885. ASSERT_FALSE(cli.is_valid());
  11886. // Attempt to make a request should fail with proper error
  11887. auto res = cli.Get("/");
  11888. ASSERT_FALSE(res);
  11889. EXPECT_EQ(Error::SSLConnection, res.error());
  11890. // SSL error should be recorded in the Result object (this is the key fix for
  11891. // Issue #2251)
  11892. auto backend_error = res.ssl_backend_error();
  11893. EXPECT_NE(0u, backend_error);
  11894. }
  11895. // Tests cert/key mismatch detection at the TLS context level
  11896. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11897. // Test that using mismatched cert/key causes connection failure.
  11898. // We verify this at the SSLClient level rather than through internal
  11899. // TLS API functions.
  11900. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11901. cli.enable_server_certificate_verification(false);
  11902. cli.set_connection_timeout(2);
  11903. // The mismatch should cause a connection or handshake error
  11904. auto res = cli.Get("/test");
  11905. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11906. // Either way, the request should fail
  11907. EXPECT_FALSE(res);
  11908. }
  11909. #endif
  11910. #if 0
  11911. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11912. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11913. ASSERT_TRUE(cli != nullptr);
  11914. cli->set_address_family(AF_INET6);
  11915. cli->set_interface("en0");
  11916. auto res = cli->Get("/get");
  11917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11918. ASSERT_EQ(StatusCode::OK_200, res->status);
  11919. }
  11920. #endif
  11921. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11922. #ifdef CPPHTTPLIB_SSL_ENABLED
  11923. void ClientCertPresent(
  11924. const std::string &client_cert_file,
  11925. const std::string &client_private_key_file,
  11926. const std::string &client_encrypted_private_key_pass = std::string()) {
  11927. using namespace httplib::tls;
  11928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11929. CLIENT_CA_CERT_DIR);
  11930. ASSERT_TRUE(svr.is_valid());
  11931. svr.Get("/test", [&](const Request &req, Response &res) {
  11932. res.set_content("test", "text/plain");
  11933. auto cert = req.peer_cert();
  11934. ASSERT_TRUE(static_cast<bool>(cert));
  11935. std::string common_name = cert.subject_cn();
  11936. EXPECT_EQ("Common Name", common_name);
  11937. });
  11938. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11939. auto se = detail::scope_exit([&] {
  11940. svr.stop();
  11941. t.join();
  11942. ASSERT_FALSE(svr.is_running());
  11943. });
  11944. svr.wait_until_ready();
  11945. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11946. client_encrypted_private_key_pass);
  11947. cli.enable_server_certificate_verification(false);
  11948. cli.set_connection_timeout(30);
  11949. auto res = cli.Get("/test");
  11950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11951. ASSERT_EQ(StatusCode::OK_200, res->status);
  11952. }
  11953. TEST(SSLClientServerTest, ClientCertPresent) {
  11954. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11955. }
  11956. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11957. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11958. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11959. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11960. }
  11961. // PEM memory-based constructor tests (works with all TLS backends)
  11962. void PemMemoryClientCertPresent(
  11963. const std::string &client_cert_file,
  11964. const std::string &client_private_key_file,
  11965. const std::string &client_encrypted_private_key_pass = std::string()) {
  11966. // Read PEM files into memory
  11967. std::string server_cert_pem, server_key_pem;
  11968. std::string client_ca_pem;
  11969. std::string client_cert_pem, client_key_pem;
  11970. read_file(SERVER_CERT_FILE, server_cert_pem);
  11971. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11972. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11973. read_file(client_cert_file, client_cert_pem);
  11974. read_file(client_private_key_file, client_key_pem);
  11975. // Create server with PEM memory
  11976. SSLServer::PemMemory server_pem = {
  11977. server_cert_pem.c_str(),
  11978. server_cert_pem.size(),
  11979. server_key_pem.c_str(),
  11980. server_key_pem.size(),
  11981. client_ca_pem.c_str(),
  11982. client_ca_pem.size(),
  11983. nullptr // no password for server key
  11984. };
  11985. SSLServer svr(server_pem);
  11986. ASSERT_TRUE(svr.is_valid());
  11987. svr.Get("/test", [&](const Request &, Response &res) {
  11988. res.set_content("test", "text/plain");
  11989. });
  11990. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11991. auto se = detail::scope_exit([&] {
  11992. svr.stop();
  11993. t.join();
  11994. ASSERT_FALSE(svr.is_running());
  11995. });
  11996. svr.wait_until_ready();
  11997. // Create client with PEM memory
  11998. const char *password = client_encrypted_private_key_pass.empty()
  11999. ? nullptr
  12000. : client_encrypted_private_key_pass.c_str();
  12001. SSLClient::PemMemory client_pem = {
  12002. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12003. client_key_pem.size(), password};
  12004. SSLClient cli(HOST, PORT, client_pem);
  12005. cli.enable_server_certificate_verification(false);
  12006. cli.set_connection_timeout(30);
  12007. auto res = cli.Get("/test");
  12008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12009. ASSERT_EQ(StatusCode::OK_200, res->status);
  12010. }
  12011. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12012. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12013. }
  12014. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12015. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12016. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12017. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12018. }
  12019. TEST(SSLClientServerTest, ClientCertMissing) {
  12020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12021. CLIENT_CA_CERT_DIR);
  12022. ASSERT_TRUE(svr.is_valid());
  12023. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12024. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12025. auto se = detail::scope_exit([&] {
  12026. svr.stop();
  12027. t.join();
  12028. ASSERT_FALSE(svr.is_running());
  12029. });
  12030. svr.wait_until_ready();
  12031. SSLClient cli(HOST, PORT);
  12032. cli.set_connection_timeout(30);
  12033. auto res = cli.Get("/test");
  12034. ASSERT_TRUE(!res);
  12035. // When client cert is missing and server requires it, connection fails
  12036. // Error type depends on backend implementation
  12037. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12038. res.error() == Error::SSLConnection);
  12039. // Verify backend error is captured
  12040. // Note: This test may have different error codes depending on the exact
  12041. // verification failure
  12042. EXPECT_NE(0UL, res.ssl_backend_error());
  12043. }
  12044. TEST(SSLClientServerTest, TrustDirOptional) {
  12045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12046. ASSERT_TRUE(svr.is_valid());
  12047. svr.Get("/test", [&](const Request &, Response &res) {
  12048. res.set_content("test", "text/plain");
  12049. });
  12050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12051. auto se = detail::scope_exit([&] {
  12052. svr.stop();
  12053. t.join();
  12054. ASSERT_FALSE(svr.is_running());
  12055. });
  12056. svr.wait_until_ready();
  12057. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12058. cli.enable_server_certificate_verification(false);
  12059. cli.set_connection_timeout(30);
  12060. auto res = cli.Get("/test");
  12061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12062. ASSERT_EQ(StatusCode::OK_200, res->status);
  12063. }
  12064. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12065. class NoListenSSLServer : public SSLServer {
  12066. public:
  12067. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12068. const char *client_ca_cert_file_path,
  12069. const char *client_ca_cert_dir_path = nullptr)
  12070. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12071. client_ca_cert_dir_path),
  12072. stop_(false) {}
  12073. std::atomic_bool stop_;
  12074. private:
  12075. bool process_and_close_socket(socket_t /*sock*/) override {
  12076. // Don't create SSL context
  12077. while (!stop_.load()) {
  12078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12079. }
  12080. return true;
  12081. }
  12082. };
  12083. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12084. CLIENT_CA_CERT_FILE);
  12085. ASSERT_TRUE(svr.is_valid());
  12086. svr.Get("/test", [&](const Request &, Response &res) {
  12087. res.set_content("test", "text/plain");
  12088. });
  12089. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12090. auto se = detail::scope_exit([&] {
  12091. svr.stop_ = true;
  12092. svr.stop();
  12093. t.join();
  12094. ASSERT_FALSE(svr.is_running());
  12095. });
  12096. svr.wait_until_ready();
  12097. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12098. cli.enable_server_certificate_verification(false);
  12099. cli.set_connection_timeout(1);
  12100. auto res = cli.Get("/test");
  12101. ASSERT_TRUE(!res);
  12102. EXPECT_EQ(Error::SSLConnection, res.error());
  12103. // Timeout results in WantRead error code (maps to backend-specific value)
  12104. EXPECT_NE(0, res.ssl_error());
  12105. }
  12106. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12107. // Test SSLServer with client certificate verification using the standard
  12108. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12110. CLIENT_CA_CERT_DIR);
  12111. ASSERT_TRUE(svr.is_valid());
  12112. svr.Get("/test", [&](const Request &req, Response &res) {
  12113. res.set_content("test", "text/plain");
  12114. auto cert = req.peer_cert();
  12115. ASSERT_TRUE(static_cast<bool>(cert));
  12116. auto common_name = cert.subject_cn();
  12117. EXPECT_EQ("Common Name", common_name);
  12118. });
  12119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12120. auto se = detail::scope_exit([&] {
  12121. svr.stop();
  12122. t.join();
  12123. ASSERT_FALSE(svr.is_running());
  12124. });
  12125. svr.wait_until_ready();
  12126. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12127. cli.enable_server_certificate_verification(false);
  12128. cli.set_connection_timeout(30);
  12129. auto res = cli.Get("/test");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12134. // Verifies that wildcard matching and exact matching work consistently
  12135. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12136. using namespace httplib::tls;
  12137. // We need a running server to test against
  12138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12139. ASSERT_TRUE(svr.is_valid());
  12140. svr.Get("/test", [](const Request &, Response &res) {
  12141. res.set_content("ok", "text/plain");
  12142. });
  12143. thread t([&]() { svr.listen(HOST, PORT); });
  12144. auto se = detail::scope_exit([&] {
  12145. svr.stop();
  12146. t.join();
  12147. });
  12148. svr.wait_until_ready();
  12149. bool verify_callback_called = false;
  12150. bool verify_result_wrong = false;
  12151. SSLClient cli(HOST, PORT);
  12152. cli.enable_server_certificate_verification(true);
  12153. cli.set_ca_cert_path(CA_CERT_FILE);
  12154. cli.set_connection_timeout(5);
  12155. // Note: Test certificate has CN="Common Name", not "localhost"
  12156. bool verify_result_cn = false;
  12157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12158. verify_callback_called = true;
  12159. if (!ctx.cert) return false;
  12160. // Test 1: "Common Name" should match (our test server cert CN)
  12161. verify_result_cn = ctx.check_hostname("Common Name");
  12162. // Test 2: wrong hostname should not match
  12163. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12164. return true; // Accept for the purpose of this test
  12165. });
  12166. auto res = cli.Get("/test");
  12167. // The request may succeed or fail depending on cert configuration
  12168. // but the callback should have been called
  12169. ASSERT_TRUE(verify_callback_called)
  12170. << "Verify callback should have been called";
  12171. // CN="Common Name" should match our test certificate
  12172. //
  12173. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12174. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12175. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12176. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12177. // <openssl/base.h>, which is included transitively when
  12178. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12179. #if defined(OPENSSL_IS_BORINGSSL)
  12180. EXPECT_FALSE(verify_result_cn)
  12181. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12182. #else
  12183. EXPECT_TRUE(verify_result_cn)
  12184. << "verify_hostname should match 'Common Name' (certificate CN)";
  12185. #endif
  12186. // Wrong hostname should not match
  12187. EXPECT_FALSE(verify_result_wrong)
  12188. << "verify_hostname should not match 'wronghost.example.com'";
  12189. }
  12190. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12191. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12192. // X509_check_ip behavior and must hold for every backend.
  12193. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12194. using namespace httplib::tls;
  12195. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12196. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12197. ASSERT_TRUE(svr.is_valid());
  12198. svr.Get("/test", [](const Request &, Response &res) {
  12199. res.set_content("ok", "text/plain");
  12200. });
  12201. thread t([&]() { svr.listen(HOST, PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. t.join();
  12205. });
  12206. svr.wait_until_ready();
  12207. bool verify_callback_called = false;
  12208. bool ip_matched_via_cn = true;
  12209. SSLClient cli(HOST, PORT);
  12210. cli.enable_server_certificate_verification(true);
  12211. cli.set_ca_cert_path(CA_CERT_FILE);
  12212. cli.set_connection_timeout(5);
  12213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12214. verify_callback_called = true;
  12215. if (!ctx.cert) return false;
  12216. // The IP appears only in the CN, so it must NOT be accepted.
  12217. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12218. return true; // Accept for the purpose of this test
  12219. });
  12220. cli.Get("/test");
  12221. ASSERT_TRUE(verify_callback_called)
  12222. << "Verify callback should have been called";
  12223. EXPECT_FALSE(ip_matched_via_cn)
  12224. << "An IP host must not be authenticated via the certificate CN";
  12225. }
  12226. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12227. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12228. using namespace httplib::tls;
  12229. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12230. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12231. ASSERT_TRUE(svr.is_valid());
  12232. svr.Get("/test", [](const Request &, Response &res) {
  12233. res.set_content("ok", "text/plain");
  12234. });
  12235. thread t([&]() { svr.listen(HOST, PORT); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. t.join();
  12239. });
  12240. svr.wait_until_ready();
  12241. bool verify_callback_called = false;
  12242. bool san_matched = false;
  12243. bool wrong_ipv6_matched = true;
  12244. bool cn_ipv6_matched = true;
  12245. SSLClient cli(HOST, PORT);
  12246. cli.enable_server_certificate_verification(true);
  12247. cli.set_ca_cert_path(CA_CERT_FILE);
  12248. cli.set_connection_timeout(5);
  12249. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12250. verify_callback_called = true;
  12251. if (!ctx.cert) return false;
  12252. // Matches the IPv6 iPAddress SAN.
  12253. san_matched = ctx.check_hostname("2001:db8::1");
  12254. // A different IPv6 address must not match.
  12255. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12256. // "::1" lives only in the CN, so it must not be accepted.
  12257. cn_ipv6_matched = ctx.check_hostname("::1");
  12258. return true; // Accept for the purpose of this test
  12259. });
  12260. cli.Get("/test");
  12261. ASSERT_TRUE(verify_callback_called)
  12262. << "Verify callback should have been called";
  12263. EXPECT_TRUE(san_matched)
  12264. << "verify_hostname should match an IPv6 iPAddress SAN";
  12265. EXPECT_FALSE(wrong_ipv6_matched)
  12266. << "verify_hostname should not match a non-matching IPv6 address";
  12267. EXPECT_FALSE(cn_ipv6_matched)
  12268. << "An IPv6 host must not be authenticated via the certificate CN";
  12269. }
  12270. #endif
  12271. // mbedTLS-specific callback constructor test
  12272. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12273. #ifdef CPPHTTPLIB_SSL_ENABLED
  12274. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12276. ASSERT_TRUE(svr.is_valid());
  12277. // Set up a handler to verify client certificate is present
  12278. bool client_cert_verified = false;
  12279. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12280. // Verify that client certificate was provided
  12281. client_cert_verified = true;
  12282. res.set_content("success", "text/plain");
  12283. });
  12284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12285. auto se = detail::scope_exit([&] {
  12286. svr.stop();
  12287. t.join();
  12288. ASSERT_FALSE(svr.is_running());
  12289. });
  12290. svr.wait_until_ready();
  12291. // Client with certificate
  12292. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12293. cli.enable_server_certificate_verification(false);
  12294. cli.set_connection_timeout(30);
  12295. auto res = cli.Get("/test");
  12296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12297. ASSERT_EQ(StatusCode::OK_200, res->status);
  12298. ASSERT_TRUE(client_cert_verified);
  12299. EXPECT_EQ("success", res->body);
  12300. }
  12301. #endif
  12302. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12303. // backends
  12304. #ifdef CPPHTTPLIB_SSL_ENABLED
  12305. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12306. using namespace httplib::tls;
  12307. // Test that when client CA cert file is provided,
  12308. // the server properly requests and validates client certificates
  12309. // Create a server with client authentication
  12310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12311. ASSERT_TRUE(svr.is_valid());
  12312. bool handler_called = false;
  12313. svr.Get("/test", [&](const Request &req, Response &res) {
  12314. handler_called = true;
  12315. // Verify that a client certificate was provided
  12316. auto cert = req.peer_cert();
  12317. ASSERT_TRUE(static_cast<bool>(cert));
  12318. // Get the issuer name
  12319. std::string issuer_str = cert.issuer_name();
  12320. ASSERT_FALSE(issuer_str.empty());
  12321. // The client certificate should be issued by our test CA
  12322. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12323. res.set_content("authenticated", "text/plain");
  12324. });
  12325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12326. auto se = detail::scope_exit([&] {
  12327. svr.stop();
  12328. t.join();
  12329. ASSERT_FALSE(svr.is_running());
  12330. });
  12331. svr.wait_until_ready();
  12332. // Connect with a client certificate issued by the CA
  12333. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12334. cli.enable_server_certificate_verification(false);
  12335. cli.set_connection_timeout(30);
  12336. auto res = cli.Get("/test");
  12337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12338. ASSERT_EQ(StatusCode::OK_200, res->status);
  12339. ASSERT_TRUE(handler_called);
  12340. EXPECT_EQ("authenticated", res->body);
  12341. }
  12342. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12343. using namespace httplib::tls;
  12344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12345. ASSERT_TRUE(svr.is_valid());
  12346. svr.Get("/test", [](const Request &, Response &res) {
  12347. res.set_content("ok", "text/plain");
  12348. });
  12349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12350. auto se = detail::scope_exit([&] {
  12351. svr.stop();
  12352. t.join();
  12353. });
  12354. svr.wait_until_ready();
  12355. SSLClient cli(HOST, PORT);
  12356. cli.enable_server_certificate_verification(false);
  12357. cli.set_connection_timeout(30);
  12358. bool cert_checked = false;
  12359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12360. if (ctx.cert) {
  12361. auto sans = ctx.sans();
  12362. // Test certificate may or may not have SANs - just verify the API
  12363. // works If SANs exist, verify the types are valid
  12364. for (const auto &san : sans) {
  12365. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12366. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12367. san.type == SanType::OTHER);
  12368. EXPECT_FALSE(san.value.empty());
  12369. }
  12370. cert_checked = true;
  12371. }
  12372. return true;
  12373. });
  12374. auto res = cli.Get("/test");
  12375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12376. EXPECT_TRUE(cert_checked);
  12377. }
  12378. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12379. using namespace httplib::tls;
  12380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12381. ASSERT_TRUE(svr.is_valid());
  12382. svr.Get("/test", [](const Request &, Response &res) {
  12383. res.set_content("ok", "text/plain");
  12384. });
  12385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. t.join();
  12389. });
  12390. svr.wait_until_ready();
  12391. SSLClient cli(HOST, PORT);
  12392. cli.enable_server_certificate_verification(false);
  12393. cli.set_connection_timeout(30);
  12394. bool validity_checked = false;
  12395. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12396. if (ctx.cert) {
  12397. time_t not_before = 0, not_after = 0;
  12398. bool result = ctx.validity(not_before, not_after);
  12399. EXPECT_TRUE(result);
  12400. // Verify that not_before < now < not_after for a valid cert
  12401. time_t now = time(nullptr);
  12402. EXPECT_LT(not_before, now);
  12403. EXPECT_GT(not_after, now);
  12404. validity_checked = true;
  12405. }
  12406. return true;
  12407. });
  12408. auto res = cli.Get("/test");
  12409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12410. EXPECT_TRUE(validity_checked);
  12411. }
  12412. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12413. using namespace httplib::tls;
  12414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12415. ASSERT_TRUE(svr.is_valid());
  12416. svr.Get("/test", [](const Request &, Response &res) {
  12417. res.set_content("ok", "text/plain");
  12418. });
  12419. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12420. auto se = detail::scope_exit([&] {
  12421. svr.stop();
  12422. t.join();
  12423. });
  12424. svr.wait_until_ready();
  12425. SSLClient cli(HOST, PORT);
  12426. cli.enable_server_certificate_verification(false);
  12427. cli.set_connection_timeout(30);
  12428. bool serial_checked = false;
  12429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12430. if (ctx.cert) {
  12431. std::string serial = ctx.serial();
  12432. EXPECT_FALSE(serial.empty());
  12433. // Serial should be a hex string
  12434. for (char c : serial) {
  12435. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12436. (c >= 'a' && c <= 'f'));
  12437. }
  12438. serial_checked = true;
  12439. }
  12440. return true;
  12441. });
  12442. auto res = cli.Get("/test");
  12443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12444. EXPECT_TRUE(serial_checked);
  12445. }
  12446. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12447. // Test 1: Valid CA file - no error should be recorded
  12448. {
  12449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12450. CLIENT_CA_CERT_FILE);
  12451. ASSERT_TRUE(svr.is_valid());
  12452. // With valid setup, last_ssl_error should be 0
  12453. EXPECT_EQ(0, svr.ssl_last_error());
  12454. }
  12455. // Test 2: Invalid CA file content
  12456. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12457. {
  12458. // Create a temporary file with completely invalid content
  12459. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12460. {
  12461. std::ofstream ofs(temp_invalid_ca);
  12462. ofs << "This is not a certificate file at all\n";
  12463. ofs << "Just plain text content\n";
  12464. }
  12465. // Create server with invalid CA file
  12466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12467. // Clean up temporary file
  12468. std::remove(temp_invalid_ca);
  12469. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12470. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12471. // Note: SSL_CTX_load_verify_locations typically fails first,
  12472. // but our error handling code path is still exercised
  12473. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12474. }
  12475. }
  12476. TEST(VerifyCallbackTest, VerifyContextFields) {
  12477. using namespace httplib::tls;
  12478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12479. ASSERT_TRUE(svr.is_valid());
  12480. svr.Get("/test", [](const Request &, Response &res) {
  12481. res.set_content("ok", "text/plain");
  12482. });
  12483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12484. auto se = detail::scope_exit([&] {
  12485. svr.stop();
  12486. t.join();
  12487. });
  12488. svr.wait_until_ready();
  12489. SSLClient cli(HOST, PORT);
  12490. cli.enable_server_certificate_verification(false);
  12491. cli.set_connection_timeout(30);
  12492. int callback_count = 0;
  12493. bool saw_leaf_cert = false;
  12494. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12495. if (ctx.cert) {
  12496. callback_count++;
  12497. // We should see at least one certificate (the leaf)
  12498. std::string cn = ctx.subject_cn();
  12499. if (!cn.empty()) { saw_leaf_cert = true; }
  12500. // Verify context fields are populated
  12501. EXPECT_NE(ctx.session, nullptr);
  12502. EXPECT_GE(ctx.depth, 0);
  12503. }
  12504. return true;
  12505. });
  12506. auto res = cli.Get("/test");
  12507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12508. EXPECT_GT(callback_count, 0);
  12509. EXPECT_TRUE(saw_leaf_cert);
  12510. }
  12511. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12512. using httplib::tls::TlsError;
  12513. // Test that verify_error_to_string returns empty for success
  12514. std::string success_str = TlsError::verify_error_to_string(0);
  12515. EXPECT_TRUE(success_str.empty());
  12516. // Test that verify_error_to_string returns non-empty for error codes
  12517. // Using a common error code (certificate expired)
  12518. std::string error_str =
  12519. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12520. EXPECT_FALSE(error_str.empty());
  12521. }
  12522. TEST(SessionVerifierTest, CertificateAccepted) {
  12523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12524. ASSERT_TRUE(svr.is_valid());
  12525. svr.Get("/test", [](const Request &, Response &res) {
  12526. res.set_content("ok", "text/plain");
  12527. });
  12528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12529. auto se = detail::scope_exit([&] {
  12530. svr.stop();
  12531. t.join();
  12532. });
  12533. svr.wait_until_ready();
  12534. SSLClient cli(HOST, PORT);
  12535. cli.enable_server_certificate_verification(false);
  12536. cli.set_connection_timeout(30);
  12537. bool callback_called = false;
  12538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12539. EXPECT_NE(session, nullptr);
  12540. callback_called = true;
  12541. return SSLVerifierResponse::CertificateAccepted;
  12542. });
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_EQ(200, res->status);
  12546. EXPECT_TRUE(callback_called);
  12547. }
  12548. TEST(SessionVerifierTest, CertificateRejected) {
  12549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12550. ASSERT_TRUE(svr.is_valid());
  12551. svr.Get("/test", [](const Request &, Response &res) {
  12552. res.set_content("ok", "text/plain");
  12553. });
  12554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. });
  12559. svr.wait_until_ready();
  12560. SSLClient cli(HOST, PORT);
  12561. cli.enable_server_certificate_verification(false);
  12562. cli.set_connection_timeout(30);
  12563. bool callback_called = false;
  12564. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12565. EXPECT_NE(session, nullptr);
  12566. callback_called = true;
  12567. return SSLVerifierResponse::CertificateRejected;
  12568. });
  12569. auto res = cli.Get("/test");
  12570. EXPECT_FALSE(res);
  12571. EXPECT_TRUE(callback_called);
  12572. }
  12573. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12575. ASSERT_TRUE(svr.is_valid());
  12576. svr.Get("/test", [](const Request &, Response &res) {
  12577. res.set_content("ok", "text/plain");
  12578. });
  12579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12580. auto se = detail::scope_exit([&] {
  12581. svr.stop();
  12582. t.join();
  12583. });
  12584. svr.wait_until_ready();
  12585. // NoDecisionMade with verification disabled should succeed (no default check)
  12586. SSLClient cli(HOST, PORT);
  12587. cli.enable_server_certificate_verification(false);
  12588. cli.set_connection_timeout(30);
  12589. bool callback_called = false;
  12590. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12591. EXPECT_NE(session, nullptr);
  12592. callback_called = true;
  12593. return SSLVerifierResponse::NoDecisionMade;
  12594. });
  12595. auto res = cli.Get("/test");
  12596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12597. EXPECT_EQ(200, res->status);
  12598. EXPECT_TRUE(callback_called);
  12599. }
  12600. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12602. ASSERT_TRUE(svr.is_valid());
  12603. svr.Get("/test", [](const Request &, Response &res) {
  12604. res.set_content("ok", "text/plain");
  12605. });
  12606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12607. auto se = detail::scope_exit([&] {
  12608. svr.stop();
  12609. t.join();
  12610. });
  12611. svr.wait_until_ready();
  12612. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12613. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12614. // so we only check that the request fails, not whether the callback was
  12615. // called.
  12616. SSLClient cli(HOST, PORT);
  12617. cli.enable_server_certificate_verification(true);
  12618. cli.set_connection_timeout(30);
  12619. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12620. EXPECT_NE(session, nullptr);
  12621. return SSLVerifierResponse::NoDecisionMade;
  12622. });
  12623. auto res = cli.Get("/test");
  12624. EXPECT_FALSE(res);
  12625. }
  12626. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12627. // Test SSL server using PemMemory constructor with client CA certificates
  12628. // Read PEM files
  12629. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12630. read_file(SERVER_CERT_FILE, server_cert_pem);
  12631. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12632. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12633. // Create SSLServer with PemMemory constructor including client CA
  12634. SSLServer::PemMemory server_pem = {
  12635. server_cert_pem.c_str(),
  12636. server_cert_pem.size(),
  12637. server_key_pem.c_str(),
  12638. server_key_pem.size(),
  12639. client_ca_pem.c_str(),
  12640. client_ca_pem.size(),
  12641. nullptr // no password for server key
  12642. };
  12643. SSLServer svr(server_pem);
  12644. ASSERT_TRUE(svr.is_valid());
  12645. // No SSL error should be recorded for valid setup
  12646. EXPECT_EQ(0, svr.ssl_last_error());
  12647. // Set up server endpoints
  12648. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12649. res.set_content("ok", "text/plain");
  12650. });
  12651. // Start server in a thread
  12652. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12653. svr.wait_until_ready();
  12654. // Connect with client certificate (using constructor with paths)
  12655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12656. cli.enable_server_certificate_verification(false);
  12657. auto res = cli.Get("/test-pem-ca");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(200, res->status);
  12660. EXPECT_EQ("ok", res->body);
  12661. svr.stop();
  12662. server_thread.join();
  12663. }
  12664. #endif
  12665. #ifdef _WIN32
  12666. TEST(CleanupTest, WSACleanup) {
  12667. int ret = WSACleanup();
  12668. ASSERT_EQ(0, ret);
  12669. }
  12670. #endif
  12671. #ifndef CPPHTTPLIB_SSL_ENABLED
  12672. TEST(NoSSLSupport, SimpleInterface) {
  12673. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12674. }
  12675. #endif
  12676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12677. TEST(InvalidScheme, SimpleInterface) {
  12678. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12679. }
  12680. #endif
  12681. TEST(NoScheme, SimpleInterface) {
  12682. Client cli("yahoo.com:80");
  12683. ASSERT_TRUE(cli.is_valid());
  12684. }
  12685. TEST(SendAPI, SimpleInterface_Online) {
  12686. Client cli("http://yahoo.com");
  12687. Request req;
  12688. req.method = "GET";
  12689. req.path = "/";
  12690. auto res = cli.send(req);
  12691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12693. }
  12694. TEST(SendAPI, WithParamsInRequest) {
  12695. Server svr;
  12696. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12697. EXPECT_TRUE(req.has_param("test"));
  12698. EXPECT_EQ("test_value", req.get_param_value("test"));
  12699. });
  12700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12701. auto se = detail::scope_exit([&] {
  12702. svr.stop();
  12703. t.join();
  12704. ASSERT_FALSE(svr.is_running());
  12705. });
  12706. svr.wait_until_ready();
  12707. Client cli(HOST, PORT);
  12708. {
  12709. Request req;
  12710. req.method = "GET";
  12711. req.path = "/";
  12712. req.params.emplace("test", "test_value");
  12713. auto res = cli.send(req);
  12714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12715. }
  12716. {
  12717. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12719. }
  12720. }
  12721. TEST(ClientImplMethods, GetSocketTest) {
  12722. httplib::Server svr;
  12723. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12724. res.status = StatusCode::OK_200;
  12725. });
  12726. auto port = svr.bind_to_any_port("127.0.0.1");
  12727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12728. auto se = detail::scope_exit([&] {
  12729. svr.stop();
  12730. thread.join();
  12731. ASSERT_FALSE(svr.is_running());
  12732. });
  12733. svr.wait_until_ready();
  12734. {
  12735. httplib::Client cli("127.0.0.1", port);
  12736. cli.set_keep_alive(true);
  12737. // Use the behavior of cpp-httplib of opening the connection
  12738. // only when the first request happens. If that changes,
  12739. // this test would be obsolete.
  12740. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12741. // This also implicitly tests the server. But other tests would fail much
  12742. // earlier than this one to be considered.
  12743. auto res = cli.Get("/");
  12744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12745. EXPECT_EQ(StatusCode::OK_200, res->status);
  12746. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12747. }
  12748. }
  12749. #ifdef CPPHTTPLIB_SSL_ENABLED
  12750. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12751. Client cli("http://yahoo.com");
  12752. auto res = cli.Get("/");
  12753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12754. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12755. cli.set_follow_location(true);
  12756. res = cli.Get("/");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. EXPECT_EQ(StatusCode::OK_200, res->status);
  12759. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12760. }
  12761. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12762. Client cli("https://yahoo.com");
  12763. auto res = cli.Get("/");
  12764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12766. cli.set_follow_location(true);
  12767. res = cli.Get("/");
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12769. EXPECT_EQ(StatusCode::OK_200, res->status);
  12770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12771. }
  12772. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12773. Client cli("https://yahoo.com");
  12774. auto res = cli.Get("/");
  12775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12776. ASSERT_FALSE(!res);
  12777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12778. ASSERT_FALSE(res == nullptr);
  12779. ASSERT_TRUE(res != nullptr);
  12780. EXPECT_EQ(Error::Success, res.error());
  12781. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12782. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12784. cli.set_follow_location(true);
  12785. res = cli.Get("/");
  12786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12787. EXPECT_EQ(Error::Success, res.error());
  12788. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12789. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12790. EXPECT_EQ(StatusCode::OK_200, res->status);
  12791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12792. }
  12793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12794. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12795. Client cli("https://cdnjs.cloudflare.com");
  12796. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12797. Headers{{"Accept-Encoding", "br"}});
  12798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12799. EXPECT_EQ(StatusCode::OK_200, res->status);
  12800. EXPECT_EQ(287630U, res->body.size());
  12801. EXPECT_EQ("application/javascript; charset=utf-8",
  12802. res->get_header_value("Content-Type"));
  12803. }
  12804. #endif
  12805. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12806. #undef REDIR_HOST // Silence compiler warning
  12807. #define REDIR_HOST "https://httpbingo.org"
  12808. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12809. Client cli(REDIR_HOST);
  12810. cli.set_follow_location(true);
  12811. auto res =
  12812. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12814. EXPECT_EQ(StatusCode::OK_200, res->status);
  12815. }
  12816. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12817. Client cli(REDIR_HOST);
  12818. cli.set_follow_location(true);
  12819. Params params;
  12820. params.emplace("url", "http://example.com");
  12821. params.emplace("status_code", "302");
  12822. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12824. EXPECT_EQ(StatusCode::OK_200, res->status);
  12825. }
  12826. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12827. Client cli(REDIR_HOST);
  12828. cli.set_follow_location(true);
  12829. Params params;
  12830. params.emplace("url", "http://example.com");
  12831. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12833. EXPECT_EQ(StatusCode::OK_200, res->status);
  12834. }
  12835. TEST(HttpToHttpsRedirectTest, CertFile) {
  12836. auto ssl_port = PORT + 1;
  12837. Server svr;
  12838. ASSERT_TRUE(svr.is_valid());
  12839. svr.Get("/index", [&](const Request &, Response &res) {
  12840. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12841. "/index");
  12842. svr.stop();
  12843. });
  12844. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. ASSERT_TRUE(ssl_svr.is_valid());
  12846. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12847. res.set_content("test", "text/plain");
  12848. ssl_svr.stop();
  12849. });
  12850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12851. thread t2 =
  12852. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12853. auto se = detail::scope_exit([&] {
  12854. t2.join();
  12855. t.join();
  12856. ASSERT_FALSE(svr.is_running());
  12857. });
  12858. svr.wait_until_ready();
  12859. ssl_svr.wait_until_ready();
  12860. Client cli("127.0.0.1", PORT);
  12861. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12862. cli.enable_server_certificate_verification(true);
  12863. cli.set_follow_location(true);
  12864. cli.set_connection_timeout(30);
  12865. auto res = cli.Get("/index");
  12866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12867. ASSERT_EQ(StatusCode::OK_200, res->status);
  12868. }
  12869. TEST(SSLClientRedirectTest, CertFile) {
  12870. auto ssl_port = PORT + 1;
  12871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12872. ASSERT_TRUE(ssl_svr1.is_valid());
  12873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12875. "/index");
  12876. ssl_svr1.stop();
  12877. });
  12878. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12879. ASSERT_TRUE(ssl_svr2.is_valid());
  12880. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12881. res.set_content("test", "text/plain");
  12882. ssl_svr2.stop();
  12883. });
  12884. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12885. thread t2 =
  12886. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12887. auto se = detail::scope_exit([&] {
  12888. t2.join();
  12889. t.join();
  12890. ASSERT_FALSE(ssl_svr1.is_running());
  12891. });
  12892. ssl_svr1.wait_until_ready();
  12893. ssl_svr2.wait_until_ready();
  12894. SSLClient cli("127.0.0.1", PORT);
  12895. std::string cert;
  12896. read_file(SERVER_CERT2_FILE, cert);
  12897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12898. cli.enable_server_certificate_verification(true);
  12899. cli.set_follow_location(true);
  12900. cli.set_connection_timeout(30);
  12901. auto res = cli.Get("/index");
  12902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12903. ASSERT_EQ(StatusCode::OK_200, res->status);
  12904. }
  12905. #endif
  12906. #ifdef CPPHTTPLIB_SSL_ENABLED
  12907. // Test that set_ca_cert_store() skips system certs (consistent with
  12908. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12909. // should be trusted - system certs should NOT be loaded.
  12910. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12911. // Load a specific cert that is NOT a system CA cert
  12912. std::string cert;
  12913. read_file(SERVER_CERT2_FILE, cert);
  12914. SSLClient cli("google.com");
  12915. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12916. cli.enable_server_certificate_verification(true);
  12917. // This should FAIL because:
  12918. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12919. // 2. System certs should NOT be loaded when custom store is set
  12920. // If system certs WERE loaded, this would succeed
  12921. auto res = cli.Get("/");
  12922. ASSERT_FALSE(res);
  12923. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12924. }
  12925. // Same as above, but through the native store handle path. Regression test:
  12926. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12927. // merged system certs into the user-provided store.
  12928. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12929. std::string cert;
  12930. read_file(SERVER_CERT2_FILE, cert);
  12931. SSLClient cli("google.com");
  12932. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12933. cli.enable_server_certificate_verification(true);
  12934. auto res = cli.Get("/");
  12935. ASSERT_FALSE(res);
  12936. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12937. }
  12938. // A custom store set via the native handle must still verify a server whose
  12939. // cert it does contain.
  12940. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12941. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12942. ASSERT_TRUE(svr.is_valid());
  12943. svr.Get("/test", [&](const Request &, Response &res) {
  12944. res.set_content("test", "text/plain");
  12945. });
  12946. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12947. auto se = detail::scope_exit([&] {
  12948. svr.stop();
  12949. t.join();
  12950. ASSERT_FALSE(svr.is_running());
  12951. });
  12952. svr.wait_until_ready();
  12953. SSLClient cli("127.0.0.1", PORT);
  12954. std::string cert;
  12955. read_file(SERVER_CERT2_FILE, cert);
  12956. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12957. cli.enable_server_certificate_verification(true);
  12958. cli.set_connection_timeout(30);
  12959. auto res = cli.Get("/test");
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. ASSERT_EQ(StatusCode::OK_200, res->status);
  12962. }
  12963. // CA certs loaded through the universal Client must be transferred to the
  12964. // client created internally for following an HTTPS redirect. Regression test:
  12965. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12966. // the CA data for redirect transfer.
  12967. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12968. auto ssl_port = PORT + 1;
  12969. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12970. ASSERT_TRUE(ssl_svr1.is_valid());
  12971. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12972. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12973. "/index");
  12974. });
  12975. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12976. ASSERT_TRUE(ssl_svr2.is_valid());
  12977. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12978. res.set_content("test", "text/plain");
  12979. });
  12980. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12981. thread t2 =
  12982. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12983. auto se = detail::scope_exit([&] {
  12984. ssl_svr2.stop();
  12985. ssl_svr1.stop();
  12986. t2.join();
  12987. t.join();
  12988. ASSERT_FALSE(ssl_svr1.is_running());
  12989. });
  12990. ssl_svr1.wait_until_ready();
  12991. ssl_svr2.wait_until_ready();
  12992. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12993. std::string cert;
  12994. read_file(SERVER_CERT2_FILE, cert);
  12995. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12996. cli.enable_server_certificate_verification(true);
  12997. cli.set_follow_location(true);
  12998. cli.set_connection_timeout(30);
  12999. auto res = cli.Get("/index");
  13000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13001. ASSERT_EQ(StatusCode::OK_200, res->status);
  13002. }
  13003. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13004. // so a host signed by a system CA verifies even though a custom CA is set
  13005. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13006. std::string cert;
  13007. read_file(SERVER_CERT2_FILE, cert);
  13008. SSLClient cli("google.com");
  13009. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13010. cli.enable_system_ca(true);
  13011. cli.enable_server_certificate_verification(true);
  13012. auto res = cli.Get("/");
  13013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13014. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13015. }
  13016. // The custom CA remains effective when combined with the system CA
  13017. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13018. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13019. ASSERT_TRUE(svr.is_valid());
  13020. svr.Get("/test", [&](const Request &, Response &res) {
  13021. res.set_content("test", "text/plain");
  13022. });
  13023. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  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. SSLClient cli("127.0.0.1", PORT);
  13031. std::string cert;
  13032. read_file(SERVER_CERT2_FILE, cert);
  13033. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13034. cli.enable_system_ca(true);
  13035. cli.enable_server_certificate_verification(true);
  13036. cli.set_connection_timeout(30);
  13037. auto res = cli.Get("/test");
  13038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13039. ASSERT_EQ(StatusCode::OK_200, res->status);
  13040. }
  13041. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13042. // skip chain verification entirely (only the certificate identity was
  13043. // checked), so a server presenting an untrusted certificate with a matching
  13044. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13045. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13046. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13047. ASSERT_TRUE(svr.is_valid());
  13048. svr.Get("/test", [&](const Request &, Response &res) {
  13049. res.set_content("test", "text/plain");
  13050. });
  13051. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. ASSERT_FALSE(svr.is_running());
  13056. });
  13057. svr.wait_until_ready();
  13058. SSLClient cli("127.0.0.1", PORT);
  13059. std::string cert;
  13060. // A trusted CA that did not sign the server certificate. The server cert
  13061. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13062. // this connection.
  13063. read_file(CLIENT_CA_CERT_FILE, cert);
  13064. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13065. cli.enable_server_certificate_verification(true);
  13066. cli.set_connection_timeout(30);
  13067. auto res = cli.Get("/test");
  13068. ASSERT_FALSE(res);
  13069. }
  13070. // enable_system_ca(false) prevents system CA loading entirely
  13071. TEST(SSLClientTest, DisableSystemCa_Online) {
  13072. SSLClient cli("google.com");
  13073. cli.enable_system_ca(false);
  13074. cli.enable_server_certificate_verification(true);
  13075. auto res = cli.Get("/");
  13076. ASSERT_FALSE(res);
  13077. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13078. // itself when the CA chain is empty
  13079. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13080. res.error() == Error::SSLConnection);
  13081. }
  13082. // The universal Client forwards enable_system_ca()
  13083. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13084. std::string cert;
  13085. read_file(SERVER_CERT2_FILE, cert);
  13086. Client cli("https://google.com");
  13087. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13088. cli.enable_system_ca(true);
  13089. cli.enable_server_certificate_verification(true);
  13090. auto res = cli.Get("/");
  13091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13093. }
  13094. // The system CA policy must carry over to the client created internally for
  13095. // following a cross-host HTTPS redirect
  13096. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13097. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13098. ASSERT_TRUE(svr.is_valid());
  13099. svr.Get("/index", [&](const Request &, Response &res) {
  13100. res.set_redirect("https://www.google.com/");
  13101. });
  13102. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13110. std::string cert;
  13111. read_file(SERVER_CERT2_FILE, cert);
  13112. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13113. cli.enable_system_ca(true);
  13114. cli.enable_server_certificate_verification(true);
  13115. cli.set_follow_location(true);
  13116. cli.set_connection_timeout(30);
  13117. // Receiving any response proves the redirect client completed the TLS
  13118. // handshake with a system-CA-signed host
  13119. auto res = cli.Get("/index");
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. }
  13122. TEST(MultipartFormDataTest, LargeData) {
  13123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13124. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13125. const ContentReader &content_reader) {
  13126. if (req.is_multipart_form_data()) {
  13127. std::vector<FormData> items;
  13128. content_reader(
  13129. [&](const FormData &file) {
  13130. items.push_back(file);
  13131. return true;
  13132. },
  13133. [&](const char *data, size_t data_length) {
  13134. items.back().content.append(data, data_length);
  13135. return true;
  13136. });
  13137. EXPECT_TRUE(std::string(items[0].name) == "document");
  13138. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13139. EXPECT_TRUE(items[0].filename == "2MB_data");
  13140. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13141. EXPECT_TRUE(items[1].name == "hello");
  13142. EXPECT_TRUE(items[1].content == "world");
  13143. EXPECT_TRUE(items[1].filename == "");
  13144. EXPECT_TRUE(items[1].content_type == "");
  13145. } else {
  13146. std::string body;
  13147. content_reader([&](const char *data, size_t data_length) {
  13148. body.append(data, data_length);
  13149. return true;
  13150. });
  13151. }
  13152. });
  13153. auto port = svr.bind_to_any_port(HOST);
  13154. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13155. auto se = detail::scope_exit([&] {
  13156. svr.stop();
  13157. t.join();
  13158. ASSERT_FALSE(svr.is_running());
  13159. });
  13160. svr.wait_until_ready();
  13161. {
  13162. std::string data(1024 * 1024 * 2, '.');
  13163. std::stringstream buffer;
  13164. buffer << data;
  13165. SSLClient cli(HOST, port);
  13166. cli.enable_server_certificate_verification(false);
  13167. UploadFormDataItems items{
  13168. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13169. {"hello", "world", "", ""},
  13170. };
  13171. auto res = cli.Post("/post", items);
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. ASSERT_EQ(StatusCode::OK_200, res->status);
  13174. }
  13175. }
  13176. TEST(MultipartFormDataTest, DataProviderItems) {
  13177. std::random_device seed_gen;
  13178. std::mt19937 random(seed_gen());
  13179. std::string rand1;
  13180. rand1.resize(1000);
  13181. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13182. std::string rand2;
  13183. rand2.resize(3000);
  13184. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13186. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13187. const ContentReader &content_reader) {
  13188. ASSERT_FALSE(req.is_multipart_form_data());
  13189. std::string body;
  13190. content_reader([&](const char *data, size_t data_length) {
  13191. body.append(data, data_length);
  13192. return true;
  13193. });
  13194. EXPECT_EQ(body, "");
  13195. });
  13196. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13197. const ContentReader &content_reader) {
  13198. ASSERT_TRUE(req.is_multipart_form_data());
  13199. std::vector<FormData> items;
  13200. content_reader(
  13201. [&](const FormData &file) {
  13202. items.push_back(file);
  13203. return true;
  13204. },
  13205. [&](const char *data, size_t data_length) {
  13206. items.back().content.append(data, data_length);
  13207. return true;
  13208. });
  13209. ASSERT_TRUE(items.size() == 2);
  13210. EXPECT_EQ(std::string(items[0].name), "name1");
  13211. EXPECT_EQ(items[0].content, "Testing123");
  13212. EXPECT_EQ(items[0].filename, "filename1");
  13213. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13214. EXPECT_EQ(items[1].name, "name2");
  13215. EXPECT_EQ(items[1].content, "Testing456");
  13216. EXPECT_EQ(items[1].filename, "");
  13217. EXPECT_EQ(items[1].content_type, "");
  13218. });
  13219. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13220. const ContentReader &content_reader) {
  13221. ASSERT_TRUE(req.is_multipart_form_data());
  13222. std::vector<FormData> items;
  13223. content_reader(
  13224. [&](const FormData &file) {
  13225. items.push_back(file);
  13226. return true;
  13227. },
  13228. [&](const char *data, size_t data_length) {
  13229. items.back().content.append(data, data_length);
  13230. return true;
  13231. });
  13232. ASSERT_TRUE(items.size() == 2);
  13233. EXPECT_EQ(items[0].name, "name3");
  13234. EXPECT_EQ(items[0].content, rand1);
  13235. EXPECT_EQ(items[0].filename, "filename3");
  13236. EXPECT_EQ(items[0].content_type, "");
  13237. EXPECT_EQ(items[1].name, "name4");
  13238. EXPECT_EQ(items[1].content, rand2);
  13239. EXPECT_EQ(items[1].filename, "filename4");
  13240. EXPECT_EQ(items[1].content_type, "");
  13241. });
  13242. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13243. const ContentReader &content_reader) {
  13244. ASSERT_TRUE(req.is_multipart_form_data());
  13245. std::vector<FormData> items;
  13246. content_reader(
  13247. [&](const FormData &file) {
  13248. items.push_back(file);
  13249. return true;
  13250. },
  13251. [&](const char *data, size_t data_length) {
  13252. items.back().content.append(data, data_length);
  13253. return true;
  13254. });
  13255. ASSERT_TRUE(items.size() == 4);
  13256. EXPECT_EQ(std::string(items[0].name), "name1");
  13257. EXPECT_EQ(items[0].content, "Testing123");
  13258. EXPECT_EQ(items[0].filename, "filename1");
  13259. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13260. EXPECT_EQ(items[1].name, "name2");
  13261. EXPECT_EQ(items[1].content, "Testing456");
  13262. EXPECT_EQ(items[1].filename, "");
  13263. EXPECT_EQ(items[1].content_type, "");
  13264. EXPECT_EQ(items[2].name, "name3");
  13265. EXPECT_EQ(items[2].content, rand1);
  13266. EXPECT_EQ(items[2].filename, "filename3");
  13267. EXPECT_EQ(items[2].content_type, "");
  13268. EXPECT_EQ(items[3].name, "name4");
  13269. EXPECT_EQ(items[3].content, rand2);
  13270. EXPECT_EQ(items[3].filename, "filename4");
  13271. EXPECT_EQ(items[3].content_type, "");
  13272. });
  13273. auto port = svr.bind_to_any_port("localhost");
  13274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13275. auto se = detail::scope_exit([&] {
  13276. svr.stop();
  13277. t.join();
  13278. ASSERT_FALSE(svr.is_running());
  13279. });
  13280. svr.wait_until_ready();
  13281. {
  13282. SSLClient cli("localhost", port);
  13283. cli.enable_server_certificate_verification(false);
  13284. UploadFormDataItems items{
  13285. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13286. {"name2", "Testing456", "", ""}, // not a file
  13287. };
  13288. {
  13289. auto res = cli.Post("/post-none", {}, {}, {});
  13290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13291. ASSERT_EQ(StatusCode::OK_200, res->status);
  13292. }
  13293. FormDataProviderItems providers;
  13294. {
  13295. auto res =
  13296. cli.Post("/post-items", {}, items, providers); // empty providers
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. ASSERT_EQ(StatusCode::OK_200, res->status);
  13299. }
  13300. providers.push_back({"name3",
  13301. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13302. // test the offset is given correctly at each step
  13303. if (!offset)
  13304. sink.os.write(rand1.data(), 30);
  13305. else if (offset == 30)
  13306. sink.os.write(rand1.data() + 30, 300);
  13307. else if (offset == 330)
  13308. sink.os.write(rand1.data() + 330, 670);
  13309. else if (offset == rand1.size())
  13310. sink.done();
  13311. return true;
  13312. },
  13313. "filename3",
  13314. {}});
  13315. providers.push_back({"name4",
  13316. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13317. // test the offset is given correctly at each step
  13318. if (!offset)
  13319. sink.os.write(rand2.data(), 2000);
  13320. else if (offset == 2000)
  13321. sink.os.write(rand2.data() + 2000, 1);
  13322. else if (offset == 2001)
  13323. sink.os.write(rand2.data() + 2001, 999);
  13324. else if (offset == rand2.size())
  13325. sink.done();
  13326. return true;
  13327. },
  13328. "filename4",
  13329. {}});
  13330. {
  13331. auto res = cli.Post("/post-providers", {}, {}, providers);
  13332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13333. ASSERT_EQ(StatusCode::OK_200, res->status);
  13334. }
  13335. {
  13336. auto res = cli.Post("/post-both", {}, items, providers);
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. ASSERT_EQ(StatusCode::OK_200, res->status);
  13339. }
  13340. }
  13341. }
  13342. TEST(MultipartFormDataTest, BadHeader) {
  13343. Server svr;
  13344. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13345. res.set_content("ok", "text/plain");
  13346. });
  13347. thread t = thread([&] { svr.listen(HOST, PORT); });
  13348. auto se = detail::scope_exit([&] {
  13349. svr.stop();
  13350. t.join();
  13351. ASSERT_FALSE(svr.is_running());
  13352. });
  13353. svr.wait_until_ready();
  13354. const std::string body =
  13355. "This is the preamble. It is to be ignored, though it\r\n"
  13356. "is a handy place for composition agents to include an\r\n"
  13357. "explanatory note to non-MIME conformant readers.\r\n"
  13358. "\r\n"
  13359. "\r\n"
  13360. "--simple boundary\r\n"
  13361. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13362. ": BAD...\r\n"
  13363. "\r\n"
  13364. "value1\r\n"
  13365. "--simple boundary\r\n"
  13366. "Content-Disposition: form-data; name=\"field2\"; "
  13367. "filename=\"example.txt\"\r\n"
  13368. "\r\n"
  13369. "value2\r\n"
  13370. "--simple boundary--\r\n"
  13371. "This is the epilogue. It is also to be ignored.\r\n";
  13372. std::string content_type =
  13373. R"(multipart/form-data; boundary="simple boundary")";
  13374. Client cli(HOST, PORT);
  13375. auto res = cli.Post("/post", body, content_type.c_str());
  13376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13378. }
  13379. TEST(MultipartFormDataTest, WithPreamble) {
  13380. Server svr;
  13381. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13382. res.set_content("ok", "text/plain");
  13383. });
  13384. thread t = thread([&] { svr.listen(HOST, PORT); });
  13385. auto se = detail::scope_exit([&] {
  13386. svr.stop();
  13387. t.join();
  13388. ASSERT_FALSE(svr.is_running());
  13389. });
  13390. svr.wait_until_ready();
  13391. const std::string body =
  13392. "This is the preamble. It is to be ignored, though it\r\n"
  13393. "is a handy place for composition agents to include an\r\n"
  13394. "explanatory note to non-MIME conformant readers.\r\n"
  13395. "\r\n"
  13396. "\r\n"
  13397. "--simple boundary\r\n"
  13398. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13399. "\r\n"
  13400. "value1\r\n"
  13401. "--simple boundary\r\n"
  13402. "Content-Disposition: form-data; name=\"field2\"; "
  13403. "filename=\"example.txt\"\r\n"
  13404. "\r\n"
  13405. "value2\r\n"
  13406. "--simple boundary--\r\n"
  13407. "This is the epilogue. It is also to be ignored.\r\n";
  13408. std::string content_type =
  13409. R"(multipart/form-data; boundary="simple boundary")";
  13410. Client cli(HOST, PORT);
  13411. auto res = cli.Post("/post", body, content_type.c_str());
  13412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13413. EXPECT_EQ(StatusCode::OK_200, res->status);
  13414. }
  13415. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13417. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13418. const ContentReader &content_reader) {
  13419. if (req.is_multipart_form_data()) {
  13420. std::vector<FormData> items;
  13421. content_reader(
  13422. [&](const FormData &file) {
  13423. items.push_back(file);
  13424. return true;
  13425. },
  13426. [&](const char *data, size_t data_length) {
  13427. items.back().content.append(data, data_length);
  13428. return true;
  13429. });
  13430. EXPECT_TRUE(std::string(items[0].name) == "document");
  13431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13432. EXPECT_TRUE(items[0].filename == "2MB_data");
  13433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13434. EXPECT_TRUE(items[1].name == "hello");
  13435. EXPECT_TRUE(items[1].content == "world");
  13436. EXPECT_TRUE(items[1].filename == "");
  13437. EXPECT_TRUE(items[1].content_type == "");
  13438. } else {
  13439. std::string body;
  13440. content_reader([&](const char *data, size_t data_length) {
  13441. body.append(data, data_length);
  13442. return true;
  13443. });
  13444. }
  13445. });
  13446. auto port = svr.bind_to_any_port("localhost");
  13447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13448. auto se = detail::scope_exit([&] {
  13449. svr.stop();
  13450. t.join();
  13451. ASSERT_FALSE(svr.is_running());
  13452. });
  13453. svr.wait_until_ready();
  13454. {
  13455. std::string data(1024 * 1024 * 2, '.');
  13456. std::stringstream buffer;
  13457. buffer << data;
  13458. SSLClient cli("localhost", port);
  13459. cli.enable_server_certificate_verification(false);
  13460. UploadFormDataItems items{
  13461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13462. {"hello", "world", "", ""},
  13463. };
  13464. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::OK_200, res->status);
  13467. }
  13468. }
  13469. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13470. std::string data(1024 * 1024 * 2, '&');
  13471. std::stringstream buffer;
  13472. buffer << data;
  13473. Client cli("https://localhost:8080");
  13474. UploadFormDataItems items{
  13475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13476. {"hello", "world", "", ""},
  13477. };
  13478. for (const char &c : " \t\r\n") {
  13479. auto res =
  13480. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13481. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13482. ASSERT_FALSE(res);
  13483. }
  13484. }
  13485. TEST(MultipartFormDataTest, PutFormData) {
  13486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13487. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13488. const ContentReader &content_reader) {
  13489. if (req.is_multipart_form_data()) {
  13490. std::vector<FormData> items;
  13491. content_reader(
  13492. [&](const FormData &file) {
  13493. items.push_back(file);
  13494. return true;
  13495. },
  13496. [&](const char *data, size_t data_length) {
  13497. items.back().content.append(data, data_length);
  13498. return true;
  13499. });
  13500. EXPECT_TRUE(std::string(items[0].name) == "document");
  13501. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13502. EXPECT_TRUE(items[0].filename == "2MB_data");
  13503. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13504. EXPECT_TRUE(items[1].name == "hello");
  13505. EXPECT_TRUE(items[1].content == "world");
  13506. EXPECT_TRUE(items[1].filename == "");
  13507. EXPECT_TRUE(items[1].content_type == "");
  13508. } else {
  13509. std::string body;
  13510. content_reader([&](const char *data, size_t data_length) {
  13511. body.append(data, data_length);
  13512. return true;
  13513. });
  13514. }
  13515. });
  13516. auto port = svr.bind_to_any_port("localhost");
  13517. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13518. auto se = detail::scope_exit([&] {
  13519. svr.stop();
  13520. t.join();
  13521. ASSERT_FALSE(svr.is_running());
  13522. });
  13523. svr.wait_until_ready();
  13524. {
  13525. std::string data(1024 * 1024 * 2, '&');
  13526. std::stringstream buffer;
  13527. buffer << data;
  13528. SSLClient cli("localhost", port);
  13529. cli.enable_server_certificate_verification(false);
  13530. UploadFormDataItems items{
  13531. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13532. {"hello", "world", "", ""},
  13533. };
  13534. auto res = cli.Put("/put", items);
  13535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13536. ASSERT_EQ(StatusCode::OK_200, res->status);
  13537. }
  13538. }
  13539. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13541. svr.Put("/put_customboundary",
  13542. [&](const Request &req, const Response & /*res*/,
  13543. const ContentReader &content_reader) {
  13544. if (req.is_multipart_form_data()) {
  13545. std::vector<FormData> items;
  13546. content_reader(
  13547. [&](const FormData &file) {
  13548. items.push_back(file);
  13549. return true;
  13550. },
  13551. [&](const char *data, size_t data_length) {
  13552. items.back().content.append(data, data_length);
  13553. return true;
  13554. });
  13555. EXPECT_TRUE(std::string(items[0].name) == "document");
  13556. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13557. EXPECT_TRUE(items[0].filename == "2MB_data");
  13558. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13559. EXPECT_TRUE(items[1].name == "hello");
  13560. EXPECT_TRUE(items[1].content == "world");
  13561. EXPECT_TRUE(items[1].filename == "");
  13562. EXPECT_TRUE(items[1].content_type == "");
  13563. } else {
  13564. std::string body;
  13565. content_reader([&](const char *data, size_t data_length) {
  13566. body.append(data, data_length);
  13567. return true;
  13568. });
  13569. }
  13570. });
  13571. auto port = svr.bind_to_any_port("localhost");
  13572. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13573. auto se = detail::scope_exit([&] {
  13574. svr.stop();
  13575. t.join();
  13576. ASSERT_FALSE(svr.is_running());
  13577. });
  13578. svr.wait_until_ready();
  13579. {
  13580. std::string data(1024 * 1024 * 2, '&');
  13581. std::stringstream buffer;
  13582. buffer << data;
  13583. SSLClient cli("localhost", port);
  13584. cli.enable_server_certificate_verification(false);
  13585. UploadFormDataItems items{
  13586. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13587. {"hello", "world", "", ""},
  13588. };
  13589. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13591. ASSERT_EQ(StatusCode::OK_200, res->status);
  13592. }
  13593. }
  13594. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13595. std::string data(1024 * 1024 * 2, '&');
  13596. std::stringstream buffer;
  13597. buffer << data;
  13598. Client cli("https://localhost:8080");
  13599. cli.enable_server_certificate_verification(false);
  13600. UploadFormDataItems items{
  13601. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13602. {"hello", "world", "", ""},
  13603. };
  13604. for (const char &c : " \t\r\n") {
  13605. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13606. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13607. ASSERT_FALSE(res);
  13608. }
  13609. }
  13610. TEST(MultipartFormDataTest, AlternateFilename) {
  13611. auto handled = false;
  13612. Server svr;
  13613. svr.Post("/test", [&](const Request &req, Response &res) {
  13614. ASSERT_EQ(2u, req.form.files.size());
  13615. ASSERT_EQ(1u, req.form.fields.size());
  13616. // Test files
  13617. const auto &file1 = req.form.get_file("file1");
  13618. ASSERT_EQ("file1", file1.name);
  13619. ASSERT_EQ("A.txt", file1.filename);
  13620. ASSERT_EQ("text/plain", file1.content_type);
  13621. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13622. const auto &file2 = req.form.get_file("file2");
  13623. ASSERT_EQ("file2", file2.name);
  13624. ASSERT_EQ("a.html", file2.filename);
  13625. ASSERT_EQ("text/html", file2.content_type);
  13626. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13627. file2.content);
  13628. // Test text field
  13629. const auto &text = req.form.get_field("text");
  13630. ASSERT_EQ("text default", text);
  13631. res.set_content("ok", "text/plain");
  13632. handled = true;
  13633. });
  13634. thread t = thread([&] { svr.listen(HOST, PORT); });
  13635. auto se = detail::scope_exit([&] {
  13636. svr.stop();
  13637. t.join();
  13638. ASSERT_FALSE(svr.is_running());
  13639. ASSERT_TRUE(handled);
  13640. });
  13641. svr.wait_until_ready();
  13642. auto req = "POST /test HTTP/1.1\r\n"
  13643. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13644. "Content-Length: 399\r\n"
  13645. "\r\n"
  13646. "----------\r\n"
  13647. "Content-Disposition: form-data; name=\"text\"\r\n"
  13648. "\r\n"
  13649. "text default\r\n"
  13650. "----------\r\n"
  13651. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13652. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13653. "Content-Type: text/plain\r\n"
  13654. "\r\n"
  13655. "Content of a.txt.\r\n"
  13656. "\r\n"
  13657. "----------\r\n"
  13658. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13659. "\"a.html\"\r\n"
  13660. "Content-Type: text/html\r\n"
  13661. "\r\n"
  13662. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13663. "\r\n"
  13664. "------------\r\n";
  13665. ASSERT_TRUE(send_request(1, req));
  13666. }
  13667. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13668. auto handled = false;
  13669. Server svr;
  13670. svr.Post("/test", [&](const Request &req, Response &res) {
  13671. // Case-insensitive "utf-8''" prefix with a long value
  13672. const auto &file = req.form.get_file("file1");
  13673. ASSERT_EQ("file1", file.name);
  13674. // 8000 chars exercises both the Content-Disposition parser and the
  13675. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13676. // Prior to the fix, std::regex_match on this header would cause O(N)
  13677. // stack recursion in libstdc++, leading to SIGSEGV.
  13678. std::string expected_filename(8000, 'A');
  13679. ASSERT_EQ(expected_filename, file.filename);
  13680. res.set_content("ok", "text/plain");
  13681. handled = true;
  13682. });
  13683. thread t = thread([&] { svr.listen(HOST, PORT); });
  13684. auto se = detail::scope_exit([&] {
  13685. svr.stop();
  13686. t.join();
  13687. ASSERT_FALSE(svr.is_running());
  13688. ASSERT_TRUE(handled);
  13689. });
  13690. svr.wait_until_ready();
  13691. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13692. // Regression test for GHSA-qq6v-r583-3h69
  13693. std::string long_filename(8000, 'A');
  13694. std::string body = "----------\r\n"
  13695. "Content-Disposition: form-data; name=\"file1\"; "
  13696. "filename*=\"Utf-8''" +
  13697. long_filename +
  13698. "\"\r\n"
  13699. "\r\n"
  13700. "hello\r\n"
  13701. "------------\r\n";
  13702. auto req = "POST /test HTTP/1.1\r\n"
  13703. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13704. "Content-Length: " +
  13705. std::to_string(body.size()) + "\r\n\r\n" + body;
  13706. ASSERT_TRUE(send_request(1, req));
  13707. }
  13708. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13709. auto handled = false;
  13710. Server svr;
  13711. svr.Post("/test", [&](const Request &req, Response &) {
  13712. ASSERT_EQ(2u, req.form.fields.size());
  13713. const auto &text1 = req.form.get_field("text1");
  13714. ASSERT_EQ("text1", text1);
  13715. const auto &text2 = req.form.get_field("text2");
  13716. ASSERT_EQ("text2", text2);
  13717. handled = true;
  13718. });
  13719. thread t = thread([&] { svr.listen(HOST, PORT); });
  13720. auto se = detail::scope_exit([&] {
  13721. svr.stop();
  13722. t.join();
  13723. ASSERT_FALSE(svr.is_running());
  13724. ASSERT_TRUE(handled);
  13725. });
  13726. svr.wait_until_ready();
  13727. auto req = "POST /test HTTP/1.1\r\n"
  13728. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13729. "Content-Length: 146\r\n"
  13730. "\r\n----------\r\n"
  13731. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13732. "\r\n"
  13733. "text1"
  13734. "\r\n----------\r\n"
  13735. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13736. "\r\n"
  13737. "text2"
  13738. "\r\n------------";
  13739. std::string response;
  13740. ASSERT_TRUE(send_request(1, req, &response));
  13741. ASSERT_EQ("200", response.substr(9, 3));
  13742. }
  13743. TEST(MultipartFormDataTest, ContentLength) {
  13744. auto handled = false;
  13745. Server svr;
  13746. svr.Post("/test", [&](const Request &req, Response &) {
  13747. ASSERT_EQ(2u, req.form.fields.size());
  13748. const auto &text1 = req.form.get_field("text1");
  13749. ASSERT_EQ("text1", text1);
  13750. const auto &text2 = req.form.get_field("text2");
  13751. ASSERT_EQ("text2", text2);
  13752. handled = true;
  13753. });
  13754. thread t = thread([&] { svr.listen(HOST, PORT); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. ASSERT_FALSE(svr.is_running());
  13759. ASSERT_TRUE(handled);
  13760. });
  13761. svr.wait_until_ready();
  13762. auto req = "POST /test HTTP/1.1\r\n"
  13763. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13764. "Content-Length: 167\r\n"
  13765. "\r\n----------\r\n"
  13766. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13767. "Content-Length: 5\r\n"
  13768. "\r\n"
  13769. "text1"
  13770. "\r\n----------\r\n"
  13771. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13772. "\r\n"
  13773. "text2"
  13774. "\r\n------------\r\n";
  13775. std::string response;
  13776. ASSERT_TRUE(send_request(1, req, &response));
  13777. ASSERT_EQ("200", response.substr(9, 3));
  13778. }
  13779. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13780. auto handled = false;
  13781. Server svr;
  13782. svr.Post("/test", [&](const Request &req, Response &) {
  13783. ASSERT_EQ(2u, req.form.fields.size());
  13784. const auto &text1 = req.form.get_field("text1");
  13785. ASSERT_EQ("text1", text1);
  13786. // TODO: Add header access for text fields if needed
  13787. const auto &text2 = req.form.get_field("text2");
  13788. ASSERT_EQ("text2", text2);
  13789. // TODO: Header access for text fields needs to be implemented
  13790. // auto &headers = it->second.headers;
  13791. // ASSERT_EQ(3U, headers.size());
  13792. // auto custom_header = headers.find("x-whatever");
  13793. // ASSERT_TRUE(custom_header != headers.end());
  13794. // ASSERT_NE("customvalue", custom_header->second);
  13795. // ASSERT_EQ("CustomValue", custom_header->second);
  13796. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13797. handled = true;
  13798. });
  13799. thread t = thread([&] { svr.listen(HOST, PORT); });
  13800. auto se = detail::scope_exit([&] {
  13801. svr.stop();
  13802. t.join();
  13803. ASSERT_FALSE(svr.is_running());
  13804. ASSERT_TRUE(handled);
  13805. });
  13806. svr.wait_until_ready();
  13807. auto req = "POST /test HTTP/1.1\r\n"
  13808. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13809. "Content-Length: 232\r\n"
  13810. "\r\n----------\r\n"
  13811. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13812. "Content-Length: 5\r\n"
  13813. "X-Test: 1\r\n"
  13814. "\r\n"
  13815. "text1"
  13816. "\r\n----------\r\n"
  13817. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13818. "Content-Type: text/plain\r\n"
  13819. "X-Whatever: CustomValue\r\n"
  13820. "\r\n"
  13821. "text2"
  13822. "\r\n------------\r\n"
  13823. "That should be disregarded. Not even read";
  13824. std::string response;
  13825. ASSERT_TRUE(send_request(1, req, &response));
  13826. ASSERT_EQ("200", response.substr(9, 3));
  13827. }
  13828. TEST(MultipartFormDataTest, LargeHeader) {
  13829. auto handled = false;
  13830. Server svr;
  13831. svr.Post("/test", [&](const Request &req, Response &) {
  13832. ASSERT_EQ(1u, req.form.fields.size());
  13833. const auto &text = req.form.get_field("name1");
  13834. ASSERT_EQ("text1", text);
  13835. handled = true;
  13836. });
  13837. thread t = thread([&] { svr.listen(HOST, PORT); });
  13838. auto se = detail::scope_exit([&] {
  13839. svr.stop();
  13840. t.join();
  13841. ASSERT_FALSE(svr.is_running());
  13842. ASSERT_TRUE(handled);
  13843. });
  13844. svr.wait_until_ready();
  13845. auto boundary = std::string("cpp-httplib-multipart-data");
  13846. std::string content = "--" + boundary +
  13847. "\r\n"
  13848. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13849. "\r\n"
  13850. "text1\r\n"
  13851. "--" +
  13852. boundary + "--\r\n";
  13853. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13854. "Content-Type: multipart/form-data;boundary=" +
  13855. boundary +
  13856. "\r\n"
  13857. "Content-Length: " +
  13858. std::to_string(content.size()) +
  13859. "\r\n"
  13860. "Dummy-Header: ";
  13861. std::string header_suffix = "\r\n"
  13862. "\r\n";
  13863. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13864. size_t header_dummy_size =
  13865. read_buff_size -
  13866. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13867. auto header_dummy = std::string(header_dummy_size, '@');
  13868. auto req = header_prefix + header_dummy + header_suffix + content;
  13869. std::string response;
  13870. ASSERT_TRUE(send_request(1, req, &response));
  13871. ASSERT_EQ("200", response.substr(9, 3));
  13872. }
  13873. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13874. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13875. // (not chunked Transfer-Encoding) after the streaming refactor.
  13876. auto handled = false;
  13877. Server svr;
  13878. svr.Post("/upload", [&](const Request &req, Response &res) {
  13879. auto cl_it = req.headers.find("Content-Length");
  13880. EXPECT_TRUE(cl_it != req.headers.end());
  13881. auto te_it = req.headers.find("Transfer-Encoding");
  13882. EXPECT_TRUE(te_it == req.headers.end());
  13883. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13884. res.set_content("ok", "text/plain");
  13885. handled = true;
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. auto t = thread([&] { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. ASSERT_TRUE(handled);
  13894. });
  13895. svr.wait_until_ready();
  13896. UploadFormDataItems items = {
  13897. {"field1", "hello", "", "text/plain"},
  13898. {"file1", "world", "test.txt", "application/octet-stream"},
  13899. };
  13900. Client cli(HOST, port);
  13901. auto res = cli.Post("/upload", {}, items);
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13906. // Verify that make_multipart_content_provider coalesces many small segments
  13907. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13908. constexpr size_t kItemCount = 1000;
  13909. UploadFormDataItems items;
  13910. items.reserve(kItemCount);
  13911. for (size_t i = 0; i < kItemCount; i++) {
  13912. items.push_back(
  13913. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13914. }
  13915. const std::string boundary = "----test-boundary";
  13916. auto content_length = detail::get_multipart_content_length(items, boundary);
  13917. auto provider = detail::make_multipart_content_provider(items, boundary);
  13918. // Drive the provider the same way write_content_with_progress does
  13919. size_t write_count = 0;
  13920. size_t total_bytes = 0;
  13921. DataSink sink;
  13922. size_t offset = 0;
  13923. sink.write = [&](const char *d, size_t l) -> bool {
  13924. (void)d;
  13925. write_count++;
  13926. total_bytes += l;
  13927. offset += l;
  13928. return true;
  13929. };
  13930. sink.is_writable = []() -> bool { return true; };
  13931. while (offset < content_length) {
  13932. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13933. }
  13934. EXPECT_EQ(content_length, total_bytes);
  13935. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13936. // With buffering into 64KB blocks, write_count should be much smaller.
  13937. auto segment_count = 3 * kItemCount + 1;
  13938. EXPECT_LT(write_count, segment_count / 10);
  13939. }
  13940. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13941. // Integration test: send many UploadFormDataItems and verify the server
  13942. // receives all of them correctly (#2410).
  13943. constexpr size_t kItemCount = 500;
  13944. auto handled = false;
  13945. Server svr;
  13946. svr.Post("/upload", [&](const Request &req, Response &res) {
  13947. EXPECT_EQ(kItemCount, req.form.fields.size());
  13948. for (size_t i = 0; i < kItemCount; i++) {
  13949. auto key = "field" + std::to_string(i);
  13950. auto val = "value" + std::to_string(i);
  13951. auto it = req.form.fields.find(key);
  13952. if (it != req.form.fields.end()) {
  13953. EXPECT_EQ(val, it->second.content);
  13954. } else {
  13955. ADD_FAILURE() << "Missing field: " << key;
  13956. }
  13957. }
  13958. res.set_content("ok", "text/plain");
  13959. handled = true;
  13960. });
  13961. auto port = svr.bind_to_any_port(HOST);
  13962. auto t = thread([&] { svr.listen_after_bind(); });
  13963. auto se = detail::scope_exit([&] {
  13964. svr.stop();
  13965. t.join();
  13966. ASSERT_FALSE(svr.is_running());
  13967. ASSERT_TRUE(handled);
  13968. });
  13969. svr.wait_until_ready();
  13970. UploadFormDataItems items;
  13971. items.reserve(kItemCount);
  13972. for (size_t i = 0; i < kItemCount; i++) {
  13973. items.push_back(
  13974. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13975. }
  13976. Client cli(HOST, port);
  13977. auto res = cli.Post("/upload", items);
  13978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13979. EXPECT_EQ(StatusCode::OK_200, res->status);
  13980. }
  13981. TEST(MultipartFormDataTest, MakeFileProvider) {
  13982. // Verify make_file_provider sends a file's contents correctly.
  13983. const std::string file_content(4096, 'Z');
  13984. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13985. {
  13986. std::ofstream ofs(tmp_path, std::ios::binary);
  13987. ofs.write(file_content.data(),
  13988. static_cast<std::streamsize>(file_content.size()));
  13989. }
  13990. auto handled = false;
  13991. Server svr;
  13992. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13993. const ContentReader &content_reader) {
  13994. ASSERT_TRUE(req.is_multipart_form_data());
  13995. std::vector<FormData> items;
  13996. content_reader(
  13997. [&](const FormData &file) {
  13998. items.push_back(file);
  13999. return true;
  14000. },
  14001. [&](const char *data, size_t data_length) {
  14002. items.back().content.append(data, data_length);
  14003. return true;
  14004. });
  14005. ASSERT_EQ(1u, items.size());
  14006. EXPECT_EQ("myfile", items[0].name);
  14007. EXPECT_EQ("data.bin", items[0].filename);
  14008. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14009. EXPECT_EQ(file_content, items[0].content);
  14010. handled = true;
  14011. });
  14012. auto port = svr.bind_to_any_port(HOST);
  14013. auto t = thread([&] { svr.listen_after_bind(); });
  14014. auto se = detail::scope_exit([&] {
  14015. svr.stop();
  14016. t.join();
  14017. ASSERT_FALSE(svr.is_running());
  14018. ASSERT_TRUE(handled);
  14019. std::remove(tmp_path.c_str());
  14020. });
  14021. svr.wait_until_ready();
  14022. FormDataProviderItems providers;
  14023. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14024. "application/octet-stream"));
  14025. Client cli(HOST, port);
  14026. auto res = cli.Post("/upload", {}, {}, providers);
  14027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14028. EXPECT_EQ(StatusCode::OK_200, res->status);
  14029. }
  14030. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14031. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14032. // (100) headers is rejected with a 400 Bad Request response.
  14033. Server svr;
  14034. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14035. res.set_content("ok", "text/plain");
  14036. });
  14037. thread t = thread([&] { svr.listen(HOST, PORT); });
  14038. auto se = detail::scope_exit([&] {
  14039. svr.stop();
  14040. t.join();
  14041. ASSERT_FALSE(svr.is_running());
  14042. });
  14043. svr.wait_until_ready();
  14044. // Build a multipart part with 101 custom headers (exceeding
  14045. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14046. std::stringstream body;
  14047. body << "--simpleboundary\r\n"
  14048. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14049. for (int i = 0; i < 101; i++) {
  14050. body << "X-Custom-Header-" << i << ": value\r\n";
  14051. }
  14052. body << "\r\n"
  14053. << "value1\r\n"
  14054. << "--simpleboundary--\r\n";
  14055. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14056. Client cli(HOST, PORT);
  14057. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14060. }
  14061. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14062. // A body that never contains the declared boundary must not be accumulated
  14063. // while the parser waits for it. Buffering it would also make every read
  14064. // rescan everything seen so far, which is quadratic in the body size.
  14065. Server svr;
  14066. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14067. res.set_content("ok", "text/plain");
  14068. });
  14069. auto port = svr.bind_to_any_port(HOST);
  14070. thread t = thread([&] { svr.listen_after_bind(); });
  14071. auto se = detail::scope_exit([&] {
  14072. svr.stop();
  14073. t.join();
  14074. ASSERT_FALSE(svr.is_running());
  14075. });
  14076. svr.wait_until_ready();
  14077. Client cli(HOST, port);
  14078. cli.set_read_timeout(60, 0);
  14079. cli.set_write_timeout(60, 0);
  14080. // '-' is the worst case: it matches the first character of the boundary, so
  14081. // every position has to be checked against it.
  14082. auto post_dashes = [&](size_t size) {
  14083. const std::string body(size, '-');
  14084. auto start = std::chrono::steady_clock::now();
  14085. auto res =
  14086. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14087. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14088. std::chrono::steady_clock::now() - start)
  14089. .count();
  14090. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14091. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14092. return ms;
  14093. };
  14094. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14095. // Windows.
  14096. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14097. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14098. // Comparing the two sizes rather than checking an absolute duration keeps
  14099. // this meaningful across build types and CI load, both of which move the
  14100. // absolute numbers by more than an order of magnitude. Four times the bytes
  14101. // costs about four times the time when parsing is linear, and about sixteen
  14102. // times when the body is buffered and rescanned.
  14103. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14104. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14105. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14106. << "ms, which suggests the body is being buffered and rescanned";
  14107. }
  14108. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14109. // A boundary can only be followed by CRLF or by "--", so anything else is
  14110. // malformed no matter what comes next. The parser must say so right away
  14111. // instead of buffering the rest of the declared body.
  14112. Server svr;
  14113. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14114. res.set_content("ok", "text/plain");
  14115. });
  14116. auto port = svr.bind_to_any_port(HOST);
  14117. thread t = thread([&] { svr.listen_after_bind(); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. ASSERT_FALSE(svr.is_running());
  14122. });
  14123. svr.wait_until_ready();
  14124. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14125. // buffers instead of failing would still be waiting for the remaining bytes.
  14126. const std::string body = "--zzzz\r\n"
  14127. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14128. "\r\n"
  14129. "text1"
  14130. "\r\n--zzzzXX";
  14131. const std::string req = "POST /post HTTP/1.1\r\n"
  14132. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14133. "Content-Length: 1048576\r\n"
  14134. "\r\n" +
  14135. body;
  14136. std::string response;
  14137. ASSERT_TRUE(send_request(3, req, &response, port));
  14138. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14139. EXPECT_EQ("400", response.substr(9, 3));
  14140. }
  14141. // Posts a multipart body split into two writes, so that the server sees the
  14142. // split at whatever offset the caller chose, and expects the single "text1"
  14143. // field to come through.
  14144. static void expect_split_multipart_ok(const std::string &body1,
  14145. const std::string &body2) {
  14146. auto handled = false;
  14147. Server svr;
  14148. svr.Post("/post", [&](const Request &req, Response &) {
  14149. EXPECT_EQ(1u, req.form.fields.size());
  14150. EXPECT_EQ("text1", req.form.get_field("text1"));
  14151. handled = true;
  14152. });
  14153. auto port = svr.bind_to_any_port(HOST);
  14154. thread t = thread([&] { svr.listen_after_bind(); });
  14155. auto se = detail::scope_exit([&] {
  14156. svr.stop();
  14157. t.join();
  14158. ASSERT_FALSE(svr.is_running());
  14159. ASSERT_TRUE(handled);
  14160. });
  14161. svr.wait_until_ready();
  14162. // "Connection: close" makes the server close once it has answered, so the
  14163. // response drain ends immediately instead of idling until the read timeout.
  14164. const std::string head =
  14165. "POST /post HTTP/1.1\r\n"
  14166. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14167. "Connection: close\r\n"
  14168. "Content-Length: " +
  14169. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14170. std::string response;
  14171. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14172. ASSERT_GE(response.size(), 12u) << "no response";
  14173. EXPECT_EQ("200", response.substr(9, 3));
  14174. }
  14175. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14176. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14177. // ignored, including when it does not arrive in the same read as the
  14178. // close-delimiter itself.
  14179. expect_split_multipart_ok("--zzzz\r\n"
  14180. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14181. "\r\n"
  14182. "text1"
  14183. "\r\n--zzzz--",
  14184. "\r\nthis epilogue must be ignored\r\n");
  14185. }
  14186. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14187. // The initial boundary may be preceded by a preamble of any length and may
  14188. // straddle a read boundary. Discarding data while waiting for it must not
  14189. // throw away a partial boundary sitting at the end of the buffer.
  14190. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14191. "zz\r\n"
  14192. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14193. "\r\n"
  14194. "text1"
  14195. "\r\n--zzzz--\r\n");
  14196. }
  14197. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14198. // The received boundary was only checked for being non-empty, so it could be
  14199. // as long as a header is allowed to be. The parser scans the body for
  14200. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14201. // costs a nearly full comparison at nearly every position, making the
  14202. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14203. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14204. Server svr;
  14205. svr.Post("/post", [](const Request &req, Response &res) {
  14206. EXPECT_EQ(1u, req.form.fields.size());
  14207. EXPECT_EQ("text1", req.form.get_field("text1"));
  14208. res.set_content("ok", "text/plain");
  14209. });
  14210. auto port = svr.bind_to_any_port(HOST);
  14211. thread t = thread([&] { svr.listen_after_bind(); });
  14212. auto se = detail::scope_exit([&] {
  14213. svr.stop();
  14214. t.join();
  14215. ASSERT_FALSE(svr.is_running());
  14216. });
  14217. svr.wait_until_ready();
  14218. Client cli(HOST, port);
  14219. auto post_with_boundary_of_length = [&](size_t len) {
  14220. const std::string boundary(len, 'a');
  14221. const std::string body =
  14222. "--" + boundary +
  14223. "\r\n"
  14224. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14225. "\r\n"
  14226. "text1"
  14227. "\r\n--" +
  14228. boundary + "--\r\n";
  14229. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14230. };
  14231. auto res = post_with_boundary_of_length(70);
  14232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14233. EXPECT_EQ(StatusCode::OK_200, res->status);
  14234. res = post_with_boundary_of_length(71);
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14237. }
  14238. TEST(MakeFileBodyTest, Basic) {
  14239. const std::string file_content(4096, 'Z');
  14240. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14241. {
  14242. std::ofstream ofs(tmp_path, std::ios::binary);
  14243. ofs.write(file_content.data(),
  14244. static_cast<std::streamsize>(file_content.size()));
  14245. }
  14246. auto handled = false;
  14247. Server svr;
  14248. svr.Post("/upload", [&](const Request &req, Response &res) {
  14249. EXPECT_EQ(file_content, req.body);
  14250. handled = true;
  14251. res.status = StatusCode::OK_200;
  14252. });
  14253. auto port = svr.bind_to_any_port(HOST);
  14254. auto t = thread([&] { svr.listen_after_bind(); });
  14255. auto se = detail::scope_exit([&] {
  14256. svr.stop();
  14257. t.join();
  14258. ASSERT_FALSE(svr.is_running());
  14259. ASSERT_TRUE(handled);
  14260. std::remove(tmp_path.c_str());
  14261. });
  14262. svr.wait_until_ready();
  14263. auto fb = make_file_body(tmp_path);
  14264. ASSERT_GT(fb.first, 0u);
  14265. Client cli(HOST, port);
  14266. auto res =
  14267. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14269. EXPECT_EQ(StatusCode::OK_200, res->status);
  14270. }
  14271. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14272. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14273. {
  14274. std::ofstream ofs(path, std::ios::binary);
  14275. const std::string content(100, 'A');
  14276. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14277. }
  14278. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14279. auto body = make_file_body(path);
  14280. ASSERT_EQ(100u, body.first);
  14281. ASSERT_TRUE(static_cast<bool>(body.second));
  14282. // Rewritten shorter after its length was measured - and, on a server, after
  14283. // that length has already gone out as Content-Length.
  14284. {
  14285. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14286. const std::string content(10, 'A');
  14287. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14288. }
  14289. std::string written;
  14290. DataSink sink;
  14291. sink.write = [&](const char *d, size_t l) {
  14292. written.append(d, l);
  14293. return true;
  14294. };
  14295. // The provider has to report failure. write_content_with_progress() advances
  14296. // its offset only by what was written, so a provider that returns true
  14297. // without completing the length it promised is called again straight away,
  14298. // and again.
  14299. EXPECT_FALSE(body.second(0, body.first, sink));
  14300. EXPECT_EQ(std::string(10, 'A'), written);
  14301. }
  14302. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14303. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14304. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14305. {
  14306. std::ofstream ofs(path, std::ios::binary);
  14307. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14308. }
  14309. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14310. auto body = make_file_body(path);
  14311. ASSERT_EQ(content.size(), body.first);
  14312. ASSERT_TRUE(static_cast<bool>(body.second));
  14313. std::string written;
  14314. DataSink sink;
  14315. sink.write = [&](const char *d, size_t l) {
  14316. written.append(d, l);
  14317. return true;
  14318. };
  14319. EXPECT_TRUE(body.second(0, body.first, sink));
  14320. EXPECT_EQ(content, written);
  14321. }
  14322. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14323. static constexpr unsigned int number_of_tasks{1000000};
  14324. std::atomic_uint count{0};
  14325. std::unique_ptr<TaskQueue> task_queue{
  14326. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14327. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14328. auto queued = task_queue->enqueue(
  14329. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14330. EXPECT_TRUE(queued);
  14331. }
  14332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14333. task_queue->shutdown();
  14334. #else
  14335. EXPECT_NO_THROW(task_queue->shutdown());
  14336. #endif
  14337. EXPECT_EQ(number_of_tasks, count.load());
  14338. }
  14339. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14340. static constexpr unsigned int number_of_tasks{1000000};
  14341. static constexpr unsigned int qlimit{2};
  14342. unsigned int queued_count{0};
  14343. std::atomic_uint count{0};
  14344. std::unique_ptr<TaskQueue> task_queue{
  14345. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14346. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14347. if (task_queue->enqueue(
  14348. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14349. queued_count++;
  14350. }
  14351. }
  14352. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14353. task_queue->shutdown();
  14354. #else
  14355. EXPECT_NO_THROW(task_queue->shutdown());
  14356. #endif
  14357. EXPECT_EQ(queued_count, count.load());
  14358. EXPECT_TRUE(queued_count <= number_of_tasks);
  14359. EXPECT_TRUE(queued_count >= qlimit);
  14360. }
  14361. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14362. // Use a short idle timeout so a dynamic thread spawns, times out and
  14363. // exits during the test, and the pool keeps working afterwards.
  14364. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14365. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14366. /*idle_timeout_sec=*/1}};
  14367. std::atomic_uint count{0};
  14368. std::condition_variable cv;
  14369. std::mutex mtx;
  14370. bool release = false;
  14371. // Block the base thread so the second task spawns a dynamic thread.
  14372. EXPECT_TRUE(task_queue->enqueue([&] {
  14373. std::unique_lock<std::mutex> lock(mtx);
  14374. while (!release) {
  14375. cv.wait(lock);
  14376. }
  14377. count++;
  14378. }));
  14379. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14380. // Let the dynamic thread finish its task and exceed the idle timeout.
  14381. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14382. {
  14383. std::unique_lock<std::mutex> lock(mtx);
  14384. release = true;
  14385. }
  14386. cv.notify_all();
  14387. // The pool must still accept and run tasks after the dynamic thread exited.
  14388. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14389. task_queue->shutdown();
  14390. EXPECT_EQ(3u, count.load());
  14391. }
  14392. TEST(TaskQueueTest, MaxQueuedRequests) {
  14393. static constexpr unsigned int qlimit{3};
  14394. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14395. std::condition_variable sem_cv;
  14396. std::mutex sem_mtx;
  14397. int credits = 0;
  14398. bool queued;
  14399. /* Fill up the queue with tasks that will block until we give them credits to
  14400. * complete. */
  14401. for (unsigned int n = 0; n <= qlimit;) {
  14402. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14403. std::unique_lock<std::mutex> lock(sem_mtx);
  14404. while (credits <= 0) {
  14405. sem_cv.wait(lock);
  14406. }
  14407. /* Consume the credit and signal the test code if they are all gone. */
  14408. if (--credits == 0) { sem_cv.notify_one(); }
  14409. });
  14410. if (n < qlimit) {
  14411. /* The first qlimit enqueues must succeed. */
  14412. EXPECT_TRUE(queued);
  14413. } else {
  14414. /* The last one will succeed only when the worker thread
  14415. * starts and dequeues the first blocking task. Although
  14416. * not necessary for the correctness of this test, we sleep for
  14417. * a short while to avoid busy waiting. */
  14418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14419. }
  14420. if (queued) { n++; }
  14421. }
  14422. /* Further enqueues must fail since the queue is full. */
  14423. for (auto i = 0; i < 4; i++) {
  14424. queued = task_queue->enqueue([] {});
  14425. EXPECT_FALSE(queued);
  14426. }
  14427. /* Give the credits to allow the previous tasks to complete. */
  14428. {
  14429. std::unique_lock<std::mutex> lock(sem_mtx);
  14430. credits += qlimit + 1;
  14431. }
  14432. sem_cv.notify_all();
  14433. /* Wait for all the credits to be consumed. */
  14434. {
  14435. std::unique_lock<std::mutex> lock(sem_mtx);
  14436. while (credits > 0) {
  14437. sem_cv.wait(lock);
  14438. }
  14439. }
  14440. /* Check that we are able again to enqueue at least qlimit tasks. */
  14441. for (unsigned int i = 0; i < qlimit; i++) {
  14442. queued = task_queue->enqueue([] {});
  14443. EXPECT_TRUE(queued);
  14444. }
  14445. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14446. task_queue->shutdown();
  14447. #else
  14448. EXPECT_NO_THROW(task_queue->shutdown());
  14449. #endif
  14450. }
  14451. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14452. Server svr;
  14453. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14454. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14455. });
  14456. svr.Get("/hello", [](const Request &req, Response &res) {
  14457. res.set_content(req.get_param_value("key"), "text/plain");
  14458. });
  14459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14460. auto se = detail::scope_exit([&] {
  14461. svr.stop();
  14462. thread.join();
  14463. ASSERT_FALSE(svr.is_running());
  14464. });
  14465. svr.wait_until_ready();
  14466. {
  14467. Client cli(HOST, PORT);
  14468. cli.set_follow_location(true);
  14469. auto res = cli.Get("/");
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. EXPECT_EQ(StatusCode::OK_200, res->status);
  14472. EXPECT_EQ("val&key2=val2", res->body);
  14473. }
  14474. }
  14475. #endif
  14476. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14477. Server svr;
  14478. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14479. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14480. });
  14481. svr.Get("/hello", [](const Request &req, Response &res) {
  14482. res.set_content(req.get_param_value("key"), "text/plain");
  14483. });
  14484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14485. auto se = detail::scope_exit([&] {
  14486. svr.stop();
  14487. thread.join();
  14488. ASSERT_FALSE(svr.is_running());
  14489. });
  14490. svr.wait_until_ready();
  14491. {
  14492. Client cli(HOST, PORT);
  14493. cli.set_follow_location(true);
  14494. auto res = cli.Get("/");
  14495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14496. EXPECT_EQ(StatusCode::OK_200, res->status);
  14497. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14498. }
  14499. }
  14500. TEST(RedirectTest, RedirectWithPlusInPath) {
  14501. Server svr;
  14502. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14503. res.set_redirect("/a+b");
  14504. });
  14505. // Route pattern uses regex; escape + as \\+
  14506. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14507. res.set_content(req.path, "text/plain");
  14508. });
  14509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. thread.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. });
  14515. svr.wait_until_ready();
  14516. {
  14517. Client cli(HOST, PORT);
  14518. cli.set_follow_location(true);
  14519. auto res = cli.Get("/");
  14520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14521. EXPECT_EQ(StatusCode::OK_200, res->status);
  14522. EXPECT_EQ("/a+b", res->body);
  14523. }
  14524. }
  14525. TEST(RedirectTest, ResolveRelativeLocation) {
  14526. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14527. const std::vector<std::pair<std::string, std::string>> cases = {
  14528. {"g", "/b/c/g"},
  14529. {"./g", "/b/c/g"},
  14530. {"g/", "/b/c/g/"},
  14531. {"?y", "/b/c/d;p?y"},
  14532. {"g?y", "/b/c/g?y"},
  14533. {"#s", "/b/c/d;p?q#s"},
  14534. {"g#s", "/b/c/g#s"},
  14535. {"g?y#s", "/b/c/g?y#s"},
  14536. {";x", "/b/c/;x"},
  14537. {"g;x", "/b/c/g;x"},
  14538. {".", "/b/c/"},
  14539. {"./", "/b/c/"},
  14540. {"..", "/b/"},
  14541. {"../", "/b/"},
  14542. {"../g", "/b/g"},
  14543. {"../..", "/"},
  14544. {"../../", "/"},
  14545. {"../../g", "/g"},
  14546. {"../../../g", "/g"},
  14547. {"g.", "/b/c/g."},
  14548. {".g", "/b/c/.g"},
  14549. {"g..", "/b/c/g.."},
  14550. {"..g", "/b/c/..g"},
  14551. {"./../g", "/b/g"},
  14552. {"./g/.", "/b/c/g/"},
  14553. {"g/./h", "/b/c/g/h"},
  14554. {"g/../h", "/b/c/h"},
  14555. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14556. {"g;x=1/../y", "/b/c/y"},
  14557. {"g?y/./x", "/b/c/g?y/./x"},
  14558. {"g#s/../x", "/b/c/g#s/../x"},
  14559. // Not relative-path references, so left for parse_url.
  14560. {"/g", "/g"},
  14561. {"//g", "//g"},
  14562. {"http://g/x", "http://g/x"},
  14563. {"g:h", "g:h"},
  14564. };
  14565. for (const auto &c : cases) {
  14566. EXPECT_EQ(c.second,
  14567. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14568. << c.first;
  14569. }
  14570. }
  14571. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14572. Server svr;
  14573. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14574. res.set_redirect(req.get_param_value("to"));
  14575. });
  14576. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14577. res.set_content(req.target, "text/plain");
  14578. });
  14579. svr.Get("/other", [](const Request &req, Response &res) {
  14580. res.set_content(req.target, "text/plain");
  14581. });
  14582. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14583. auto se = detail::scope_exit([&] {
  14584. svr.stop();
  14585. thread.join();
  14586. ASSERT_FALSE(svr.is_running());
  14587. });
  14588. svr.wait_until_ready();
  14589. const std::vector<std::pair<std::string, std::string>> cases = {
  14590. {"next", "/dir/next"},
  14591. {"./next?x=1", "/dir/next?x=1"},
  14592. {"../other", "/other"},
  14593. };
  14594. for (const auto &c : cases) {
  14595. Client cli(HOST, PORT);
  14596. cli.set_follow_location(true);
  14597. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14598. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14599. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14600. EXPECT_EQ(c.second, res->body) << c.first;
  14601. }
  14602. }
  14603. #ifdef CPPHTTPLIB_SSL_ENABLED
  14604. TEST(RedirectTest, Issue2185_Online) {
  14605. SSLClient client("github.com");
  14606. client.set_follow_location(true);
  14607. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14608. "Coollab-Windows.zip");
  14609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14610. EXPECT_EQ(StatusCode::OK_200, res->status);
  14611. EXPECT_EQ(9920427U, res->body.size());
  14612. }
  14613. #endif
  14614. TEST(VulnerabilityTest, CRLFInjection) {
  14615. Server svr;
  14616. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14617. res.set_content("Hello 1", "text/plain");
  14618. });
  14619. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14620. res.set_content("Hello 2", "text/plain");
  14621. });
  14622. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14623. res.set_content("Hello 3", "text/plain");
  14624. });
  14625. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14626. res.set_content("Hello 4", "text/plain");
  14627. });
  14628. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14629. for (const auto &x : req.headers) {
  14630. auto key = x.first;
  14631. EXPECT_STRNE("evil", key.c_str());
  14632. }
  14633. });
  14634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. thread.join();
  14638. ASSERT_FALSE(svr.is_running());
  14639. });
  14640. svr.wait_until_ready();
  14641. {
  14642. Client cli(HOST, PORT);
  14643. cli.Post("/test1", "A=B",
  14644. "application/x-www-form-urlencoded\r\nevil: hello1");
  14645. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14646. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14647. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14648. }
  14649. }
  14650. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14651. auto server_thread = std::thread([] {
  14652. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14653. default_socket_options(srv);
  14654. sockaddr_in addr{};
  14655. addr.sin_family = AF_INET;
  14656. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14657. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14658. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14659. ::listen(srv, 1);
  14660. sockaddr_in cli_addr{};
  14661. socklen_t cli_len = sizeof(cli_addr);
  14662. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14663. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14664. std::string buf_all;
  14665. char buf[2048];
  14666. ssize_t n;
  14667. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14668. buf_all.append(buf, static_cast<size_t>(n));
  14669. size_t pos;
  14670. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14671. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14672. auto e = request_block.find("\r\n");
  14673. if (e != std::string::npos) {
  14674. auto request_line = request_block.substr(0, e);
  14675. std::string msg =
  14676. "CRLF injection detected in request line: '" + request_line + "'";
  14677. EXPECT_FALSE(true) << msg;
  14678. }
  14679. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14680. ::send(cli,
  14681. #ifdef _WIN32
  14682. static_cast<const char *>(resp.c_str()),
  14683. static_cast<int>(resp.size()),
  14684. #else
  14685. resp.c_str(), resp.size(),
  14686. #endif
  14687. 0);
  14688. buf_all.erase(0, pos + 4);
  14689. }
  14690. }
  14691. detail::close_socket(cli);
  14692. detail::close_socket(srv);
  14693. });
  14694. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14695. auto cli = Client("127.0.0.1", PORT + 1);
  14696. auto headers = Headers{
  14697. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14698. {"Connection", "keep-alive"}};
  14699. auto res = cli.Get("/hi", headers);
  14700. EXPECT_FALSE(res);
  14701. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14702. server_thread.join();
  14703. }
  14704. // A request rejected before any byte reaches the socket must fail right away
  14705. // instead of waiting for a response the server will never send.
  14706. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14707. // The kernel completes the TCP handshake from the listen backlog, so the
  14708. // client connects, but nothing ever reads, responds or closes.
  14709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14710. default_socket_options(srv);
  14711. sockaddr_in addr{};
  14712. addr.sin_family = AF_INET;
  14713. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14714. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14715. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14716. ASSERT_EQ(0, ::listen(srv, 8));
  14717. auto cli = Client("127.0.0.1", PORT + 1);
  14718. cli.set_read_timeout(10, 0);
  14719. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14720. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14721. std::chrono::steady_clock::now() - start)
  14722. .count();
  14723. };
  14724. {
  14725. Request req;
  14726. req.method = "GE T";
  14727. req.path = "/";
  14728. auto start = std::chrono::steady_clock::now();
  14729. auto res = cli.send(req);
  14730. EXPECT_FALSE(res);
  14731. EXPECT_EQ(Error::Write, res.error());
  14732. EXPECT_LT(elapsed_ms(start), 1000);
  14733. }
  14734. {
  14735. auto start = std::chrono::steady_clock::now();
  14736. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14737. EXPECT_FALSE(res);
  14738. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14739. EXPECT_LT(elapsed_ms(start), 1000);
  14740. }
  14741. EXPECT_FALSE(cli.is_socket_open());
  14742. detail::close_socket(srv);
  14743. }
  14744. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14745. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14746. default_socket_options(srv);
  14747. sockaddr_in addr{};
  14748. addr.sin_family = AF_INET;
  14749. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14750. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14751. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14752. ASSERT_EQ(0, ::listen(srv, 1));
  14753. std::string received;
  14754. auto server_thread = std::thread([&] {
  14755. auto sock = ::accept(srv, nullptr, nullptr);
  14756. if (sock == INVALID_SOCKET) { return; }
  14757. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14758. char buf[2048];
  14759. ssize_t n;
  14760. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14761. received.append(buf, static_cast<size_t>(n));
  14762. }
  14763. detail::close_socket(sock);
  14764. });
  14765. {
  14766. auto cli = Client("127.0.0.1", PORT + 1);
  14767. // "Z" sorts after the default headers, so writing straight to the socket
  14768. // would have sent the request line and those headers before the rejection.
  14769. auto handle =
  14770. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14771. EXPECT_FALSE(handle.is_valid());
  14772. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14773. }
  14774. server_thread.join();
  14775. detail::close_socket(srv);
  14776. EXPECT_TRUE(received.empty()) << received;
  14777. }
  14778. TEST(PathParamsTest, StaticMatch) {
  14779. const auto pattern = "/users/all";
  14780. detail::PathParamsMatcher matcher(pattern);
  14781. Request request;
  14782. request.path = "/users/all";
  14783. ASSERT_TRUE(matcher.match(request));
  14784. std::unordered_map<std::string, std::string> expected_params = {};
  14785. EXPECT_EQ(request.path_params, expected_params);
  14786. }
  14787. TEST(PathParamsTest, StaticMismatch) {
  14788. const auto pattern = "/users/all";
  14789. detail::PathParamsMatcher matcher(pattern);
  14790. Request request;
  14791. request.path = "/users/1";
  14792. ASSERT_FALSE(matcher.match(request));
  14793. }
  14794. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14795. const auto pattern = "/users/:id/subscriptions";
  14796. detail::PathParamsMatcher matcher(pattern);
  14797. Request request;
  14798. request.path = "/users/42/subscriptions";
  14799. ASSERT_TRUE(matcher.match(request));
  14800. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14801. EXPECT_EQ(request.path_params, expected_params);
  14802. }
  14803. TEST(PathParamsTest, SingleParamInTheEnd) {
  14804. const auto pattern = "/users/:id";
  14805. detail::PathParamsMatcher matcher(pattern);
  14806. Request request;
  14807. request.path = "/users/24";
  14808. ASSERT_TRUE(matcher.match(request));
  14809. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14810. EXPECT_EQ(request.path_params, expected_params);
  14811. }
  14812. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14813. const auto pattern = "/users/:id/";
  14814. detail::PathParamsMatcher matcher(pattern);
  14815. Request request;
  14816. request.path = "/users/42/";
  14817. ASSERT_TRUE(matcher.match(request));
  14818. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14819. EXPECT_EQ(request.path_params, expected_params);
  14820. }
  14821. TEST(PathParamsTest, EmptyParam) {
  14822. const auto pattern = "/users/:id/";
  14823. detail::PathParamsMatcher matcher(pattern);
  14824. Request request;
  14825. request.path = "/users//";
  14826. ASSERT_TRUE(matcher.match(request));
  14827. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14828. EXPECT_EQ(request.path_params, expected_params);
  14829. }
  14830. TEST(PathParamsTest, FragmentMismatch) {
  14831. const auto pattern = "/users/:id/";
  14832. detail::PathParamsMatcher matcher(pattern);
  14833. Request request;
  14834. request.path = "/admins/24/";
  14835. ASSERT_FALSE(matcher.match(request));
  14836. }
  14837. TEST(PathParamsTest, ExtraFragments) {
  14838. const auto pattern = "/users/:id";
  14839. detail::PathParamsMatcher matcher(pattern);
  14840. Request request;
  14841. request.path = "/users/42/subscriptions";
  14842. ASSERT_FALSE(matcher.match(request));
  14843. }
  14844. TEST(PathParamsTest, MissingTrailingParam) {
  14845. const auto pattern = "/users/:id";
  14846. detail::PathParamsMatcher matcher(pattern);
  14847. Request request;
  14848. request.path = "/users";
  14849. ASSERT_FALSE(matcher.match(request));
  14850. }
  14851. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14852. const auto pattern = "/users/:id/subscriptions";
  14853. detail::PathParamsMatcher matcher(pattern);
  14854. Request request;
  14855. request.path = "/users/subscriptions";
  14856. ASSERT_FALSE(matcher.match(request));
  14857. }
  14858. TEST(PathParamsTest, MultipleParams) {
  14859. const auto pattern = "/users/:userid/subscriptions/:subid";
  14860. detail::PathParamsMatcher matcher(pattern);
  14861. Request request;
  14862. request.path = "/users/42/subscriptions/2";
  14863. ASSERT_TRUE(matcher.match(request));
  14864. std::unordered_map<std::string, std::string> expected_params = {
  14865. {"userid", "42"}, {"subid", "2"}};
  14866. EXPECT_EQ(request.path_params, expected_params);
  14867. }
  14868. TEST(PathParamsTest, SequenceOfParams) {
  14869. const auto pattern = "/values/:x/:y/:z";
  14870. detail::PathParamsMatcher matcher(pattern);
  14871. Request request;
  14872. request.path = "/values/1/2/3";
  14873. ASSERT_TRUE(matcher.match(request));
  14874. std::unordered_map<std::string, std::string> expected_params = {
  14875. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14876. EXPECT_EQ(request.path_params, expected_params);
  14877. }
  14878. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14879. const auto pattern = "/prefix:suffix";
  14880. detail::PathParamsMatcher matcher(pattern);
  14881. Request request;
  14882. request.path = "/prefix:suffix";
  14883. ASSERT_TRUE(matcher.match(request));
  14884. const std::unordered_map<std::string, std::string> expected_params = {};
  14885. EXPECT_EQ(request.path_params, expected_params);
  14886. }
  14887. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14888. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14889. // calling thread's stack on a long enough path for a quantified pattern;
  14890. // RegexMatcher must refuse to run regex matching on paths beyond
  14891. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14892. detail::RegexMatcher matcher("/files/(.*)");
  14893. Request within_limit;
  14894. within_limit.path = "/files/" + std::string(10, 'A');
  14895. EXPECT_TRUE(matcher.match(within_limit));
  14896. Request over_limit;
  14897. over_limit.path =
  14898. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14899. EXPECT_FALSE(matcher.match(over_limit));
  14900. }
  14901. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14902. Server svr;
  14903. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14904. res.set_content("ok", "text/plain");
  14905. });
  14906. auto port = svr.bind_to_any_port(HOST);
  14907. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. thread.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14915. // request URI limit; this used to be able to crash the process.
  14916. std::string path =
  14917. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14918. std::string req = "GET " + path +
  14919. " HTTP/1.1\r\n"
  14920. "Host: " +
  14921. std::string(HOST) + ":" + std::to_string(port) +
  14922. "\r\n"
  14923. "Connection: close\r\n"
  14924. "\r\n";
  14925. std::string response;
  14926. ASSERT_TRUE(send_request(5, req, &response, port));
  14927. EXPECT_NE(std::string::npos, response.find("404"));
  14928. }
  14929. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14930. Server svr;
  14931. auto handler = [](const Request & /*req*/, Response &res) {
  14932. res.set_content("hit", "text/plain");
  14933. };
  14934. // No regex metacharacter, so this one is compared literally
  14935. svr.Get("/literal/route", handler);
  14936. // '.' is a regex metacharacter, so this one must keep regex semantics
  14937. svr.Get("/a.c", handler);
  14938. auto port = svr.bind_to_any_port(HOST);
  14939. std::thread t([&]() { svr.listen_after_bind(); });
  14940. auto se = detail::scope_exit([&] {
  14941. svr.stop();
  14942. t.join();
  14943. ASSERT_FALSE(svr.is_running());
  14944. });
  14945. svr.wait_until_ready();
  14946. Client cli(HOST, port);
  14947. struct {
  14948. const char *path;
  14949. int status;
  14950. } cases[] = {
  14951. {"/literal/route", StatusCode::OK_200},
  14952. {"/literal/routes", StatusCode::NotFound_404},
  14953. {"/literal/rout", StatusCode::NotFound_404},
  14954. {"/abc", StatusCode::OK_200},
  14955. {"/a.c", StatusCode::OK_200},
  14956. };
  14957. for (const auto &x : cases) {
  14958. auto res = cli.Get(x.path);
  14959. ASSERT_TRUE(res) << x.path;
  14960. EXPECT_EQ(x.status, res->status) << x.path;
  14961. }
  14962. }
  14963. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14964. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14965. // from exhausting the stack, so it must only constrain routes that actually
  14966. // run a regular expression. A literal route is matched by comparison and
  14967. // stays usable at any length.
  14968. Server svr;
  14969. const std::string pattern =
  14970. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14971. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14972. res.set_content("hit", "text/plain");
  14973. });
  14974. auto port = svr.bind_to_any_port(HOST);
  14975. std::thread t([&]() { svr.listen_after_bind(); });
  14976. auto se = detail::scope_exit([&] {
  14977. svr.stop();
  14978. t.join();
  14979. ASSERT_FALSE(svr.is_running());
  14980. });
  14981. svr.wait_until_ready();
  14982. Client cli(HOST, port);
  14983. auto res = cli.Get(pattern);
  14984. ASSERT_TRUE(res);
  14985. EXPECT_EQ(StatusCode::OK_200, res->status);
  14986. }
  14987. TEST(ParseUrlTest, VariousPatterns) {
  14988. {
  14989. detail::UrlComponents uc;
  14990. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14991. EXPECT_EQ("http", uc.scheme);
  14992. EXPECT_EQ("example.com", uc.host);
  14993. EXPECT_EQ("8080", uc.port);
  14994. EXPECT_EQ("/path", uc.path);
  14995. EXPECT_EQ("?q=1", uc.query);
  14996. }
  14997. {
  14998. detail::UrlComponents uc;
  14999. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15000. EXPECT_EQ("https", uc.scheme);
  15001. EXPECT_EQ("example.com", uc.host);
  15002. EXPECT_TRUE(uc.port.empty());
  15003. EXPECT_EQ("/path", uc.path);
  15004. }
  15005. {
  15006. detail::UrlComponents uc;
  15007. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15008. EXPECT_EQ("::1", uc.host);
  15009. EXPECT_EQ("8080", uc.port);
  15010. EXPECT_EQ("/path", uc.path);
  15011. }
  15012. {
  15013. detail::UrlComponents uc;
  15014. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15015. }
  15016. {
  15017. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15018. // the path while the connection still targets the bracketed host.
  15019. detail::UrlComponents uc;
  15020. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15021. }
  15022. {
  15023. detail::UrlComponents uc;
  15024. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15025. }
  15026. {
  15027. detail::UrlComponents uc;
  15028. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15029. EXPECT_EQ("::1", uc.host);
  15030. EXPECT_TRUE(uc.port.empty());
  15031. EXPECT_EQ("/path", uc.path);
  15032. }
  15033. {
  15034. detail::UrlComponents uc;
  15035. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15036. EXPECT_TRUE(uc.scheme.empty());
  15037. EXPECT_EQ("example.com", uc.host);
  15038. EXPECT_EQ("/path", uc.path);
  15039. EXPECT_EQ("?q=1", uc.query);
  15040. }
  15041. {
  15042. detail::UrlComponents uc;
  15043. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15044. EXPECT_TRUE(uc.host.empty());
  15045. EXPECT_EQ("/path", uc.path);
  15046. EXPECT_EQ("?q=1", uc.query);
  15047. }
  15048. {
  15049. detail::UrlComponents uc;
  15050. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15051. EXPECT_EQ("example.com", uc.host);
  15052. EXPECT_EQ("8080", uc.port);
  15053. }
  15054. {
  15055. // Unix socket path — must not be parsed as host
  15056. detail::UrlComponents uc;
  15057. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15058. EXPECT_TRUE(uc.host.empty());
  15059. }
  15060. {
  15061. detail::UrlComponents uc;
  15062. ASSERT_TRUE(detail::parse_url("", uc));
  15063. EXPECT_TRUE(uc.host.empty());
  15064. EXPECT_TRUE(uc.path.empty());
  15065. }
  15066. {
  15067. detail::UrlComponents uc;
  15068. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15069. }
  15070. {
  15071. detail::UrlComponents uc;
  15072. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15073. }
  15074. {
  15075. // Accepted by parse_url; callers restrict to http/https
  15076. detail::UrlComponents uc;
  15077. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15078. EXPECT_EQ("ftp", uc.scheme);
  15079. }
  15080. {
  15081. detail::UrlComponents uc;
  15082. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15083. }
  15084. {
  15085. detail::UrlComponents uc;
  15086. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15087. }
  15088. }
  15089. TEST(ParseUrlTest, FragmentHandling) {
  15090. {
  15091. detail::UrlComponents uc;
  15092. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15093. EXPECT_EQ("/path", uc.path);
  15094. EXPECT_TRUE(uc.query.empty());
  15095. }
  15096. {
  15097. detail::UrlComponents uc;
  15098. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15099. EXPECT_TRUE(uc.path.empty());
  15100. EXPECT_TRUE(uc.query.empty());
  15101. }
  15102. }
  15103. TEST(ParseUrlTest, UserinfoHandling) {
  15104. // Userinfo with @ but no colon — host includes @
  15105. detail::UrlComponents uc;
  15106. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15107. EXPECT_EQ("user@host.com", uc.host);
  15108. EXPECT_EQ("/path", uc.path);
  15109. }
  15110. TEST(ParseUrlTest, IPv6EdgeCases) {
  15111. {
  15112. detail::UrlComponents uc;
  15113. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15114. EXPECT_TRUE(uc.scheme.empty());
  15115. EXPECT_EQ("::1", uc.host);
  15116. EXPECT_EQ("8080", uc.port);
  15117. }
  15118. {
  15119. // Zone ID '%25' is not in [a-fA-F0-9:]
  15120. detail::UrlComponents uc;
  15121. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15122. }
  15123. }
  15124. TEST(ParseUrlTest, SchemeEdgeCases) {
  15125. {
  15126. detail::UrlComponents uc;
  15127. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15128. }
  15129. {
  15130. detail::UrlComponents uc;
  15131. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15132. }
  15133. {
  15134. detail::UrlComponents uc;
  15135. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15136. }
  15137. }
  15138. TEST(ParseUrlTest, PortEdgeCases) {
  15139. {
  15140. detail::UrlComponents uc;
  15141. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15142. EXPECT_TRUE(uc.port.empty());
  15143. EXPECT_EQ("/path", uc.path);
  15144. }
  15145. {
  15146. // parse_url accepts any port string; validation is done by parse_port
  15147. detail::UrlComponents uc;
  15148. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15149. EXPECT_EQ("abc", uc.port);
  15150. }
  15151. }
  15152. TEST(ParseUrlTest, WebSocketPatterns) {
  15153. {
  15154. detail::UrlComponents uc;
  15155. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15156. EXPECT_EQ("ws", uc.scheme);
  15157. EXPECT_EQ("echo.example.com", uc.host);
  15158. EXPECT_EQ("8080", uc.port);
  15159. EXPECT_EQ("/ws", uc.path);
  15160. }
  15161. {
  15162. detail::UrlComponents uc;
  15163. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15164. EXPECT_EQ("wss", uc.scheme);
  15165. EXPECT_EQ("echo.example.com", uc.host);
  15166. EXPECT_TRUE(uc.port.empty());
  15167. EXPECT_EQ("/ws", uc.path);
  15168. }
  15169. }
  15170. TEST(ParseUrlTest, QueryOnly) {
  15171. detail::UrlComponents uc;
  15172. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15173. EXPECT_TRUE(uc.host.empty());
  15174. EXPECT_TRUE(uc.path.empty());
  15175. EXPECT_EQ("?q=1&r=2", uc.query);
  15176. }
  15177. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15178. detail::UrlComponents uc;
  15179. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15180. EXPECT_TRUE(uc.scheme.empty());
  15181. EXPECT_EQ("example.com", uc.host);
  15182. EXPECT_EQ("443", uc.port);
  15183. EXPECT_EQ("/path", uc.path);
  15184. }
  15185. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15186. // If ipv6 regex working, regex match codepath is taken.
  15187. // else port will default to 80 in Client impl
  15188. int clientImplMagicPort = 80;
  15189. int port = 4321;
  15190. // above ports must be different to avoid false negative
  15191. EXPECT_NE(clientImplMagicPort, port);
  15192. std::string ipV6TestURL = "http://[ff06::c3]";
  15193. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15194. CLIENT_PRIVATE_KEY_FILE);
  15195. EXPECT_EQ(cli.port(), port);
  15196. }
  15197. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15198. auto file_path = "./www/dir/index.html";
  15199. auto dir_path = "./www/dir";
  15200. detail::FileStat stat_file(file_path);
  15201. EXPECT_TRUE(stat_file.is_file());
  15202. EXPECT_FALSE(stat_file.is_dir());
  15203. detail::FileStat stat_dir(dir_path);
  15204. EXPECT_FALSE(stat_dir.is_file());
  15205. EXPECT_TRUE(stat_dir.is_dir());
  15206. }
  15207. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15208. // IPv4 with default HTTP port (80)
  15209. EXPECT_EQ("example.com",
  15210. detail::make_host_and_port_string("example.com", 80, false));
  15211. // IPv4 with default HTTPS port (443)
  15212. EXPECT_EQ("example.com",
  15213. detail::make_host_and_port_string("example.com", 443, true));
  15214. // IPv4 with non-default HTTP port
  15215. EXPECT_EQ("example.com:8080",
  15216. detail::make_host_and_port_string("example.com", 8080, false));
  15217. // IPv4 with non-default HTTPS port
  15218. EXPECT_EQ("example.com:8443",
  15219. detail::make_host_and_port_string("example.com", 8443, true));
  15220. // IPv6 with default HTTP port (80)
  15221. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15222. // IPv6 with default HTTPS port (443)
  15223. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15224. // IPv6 with non-default HTTP port
  15225. EXPECT_EQ("[::1]:8080",
  15226. detail::make_host_and_port_string("::1", 8080, false));
  15227. // IPv6 with non-default HTTPS port
  15228. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15229. // IPv6 full address with default port
  15230. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15231. detail::make_host_and_port_string(
  15232. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15233. // IPv6 full address with non-default port
  15234. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15235. detail::make_host_and_port_string(
  15236. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15237. // IPv6 localhost with non-default port
  15238. EXPECT_EQ("[::1]:3000",
  15239. detail::make_host_and_port_string("::1", 3000, false));
  15240. // IPv6 with zone ID (link-local address) with default port
  15241. EXPECT_EQ("[fe80::1%eth0]",
  15242. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15243. // IPv6 with zone ID (link-local address) with non-default port
  15244. EXPECT_EQ("[fe80::1%eth0]:8080",
  15245. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15246. // Edge case: Port 443 with is_ssl=false (should add port)
  15247. EXPECT_EQ("example.com:443",
  15248. detail::make_host_and_port_string("example.com", 443, false));
  15249. // Edge case: Port 80 with is_ssl=true (should add port)
  15250. EXPECT_EQ("example.com:80",
  15251. detail::make_host_and_port_string("example.com", 80, true));
  15252. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15253. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15254. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15255. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15256. // Security fix: Already bracketed IPv6 should not get double brackets
  15257. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15258. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15259. EXPECT_EQ("[::1]:8080",
  15260. detail::make_host_and_port_string("[::1]", 8080, false));
  15261. EXPECT_EQ("[2001:db8::1]:8080",
  15262. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15263. EXPECT_EQ("[fe80::1%eth0]",
  15264. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15265. EXPECT_EQ("[fe80::1%eth0]:8080",
  15266. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15267. // Edge case: Empty host (should return as-is)
  15268. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15269. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15270. // This is a known limitation but shouldn't crash
  15271. EXPECT_EQ("[host:name]",
  15272. detail::make_host_and_port_string("host:name", 80, false));
  15273. // Port number edge cases (no validation, but should not crash)
  15274. EXPECT_EQ("example.com:0",
  15275. detail::make_host_and_port_string("example.com", 0, false));
  15276. EXPECT_EQ("example.com:-1",
  15277. detail::make_host_and_port_string("example.com", -1, false));
  15278. EXPECT_EQ("example.com:65535",
  15279. detail::make_host_and_port_string("example.com", 65535, false));
  15280. EXPECT_EQ("example.com:65536",
  15281. detail::make_host_and_port_string("example.com", 65536, false));
  15282. }
  15283. #ifdef CPPHTTPLIB_SSL_ENABLED
  15284. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15285. httplib::SSLClient cli("roblox.com", 443);
  15286. cli.set_follow_location(true);
  15287. auto res = cli.Get("/");
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::OK_200, res->status);
  15290. }
  15291. #endif
  15292. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15293. Server svr;
  15294. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15295. EXPECT_EQ(res.status, 400);
  15296. });
  15297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. thread.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. });
  15303. svr.wait_until_ready();
  15304. Client cli(HOST, PORT);
  15305. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15306. }
  15307. TEST(InvalidHeaderCharsTest, is_field_name) {
  15308. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15309. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15310. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15311. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15312. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15313. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15314. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15315. EXPECT_FALSE(detail::fields::is_field_name(""));
  15316. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15317. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15318. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15319. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15320. }
  15321. TEST(InvalidHeaderCharsTest, is_field_value) {
  15322. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15323. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15324. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15325. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15326. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15327. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15328. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15329. EXPECT_TRUE(detail::fields::is_field_value(""));
  15330. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15331. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15332. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15333. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15334. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15335. }
  15336. TEST(InvalidHeaderCharsTest, OnServer) {
  15337. Server svr;
  15338. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15339. std::string header = "Not Set";
  15340. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15341. res.set_header(header, "value");
  15342. res.set_content("Page Content Page Content", "text/plain");
  15343. });
  15344. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15345. std::string header = "Not Set";
  15346. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15347. res.set_header("X-Test", header);
  15348. res.set_content("Page Content Page Content", "text/plain");
  15349. });
  15350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15351. auto se = detail::scope_exit([&] {
  15352. svr.stop();
  15353. thread.join();
  15354. ASSERT_FALSE(svr.is_running());
  15355. });
  15356. svr.wait_until_ready();
  15357. Client cli(HOST, PORT);
  15358. {
  15359. auto res = cli.Get(
  15360. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15362. EXPECT_EQ("Page Content Page Content", res->body);
  15363. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15364. }
  15365. {
  15366. auto res = cli.Get(
  15367. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15369. EXPECT_EQ("Page Content Page Content", res->body);
  15370. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15371. }
  15372. }
  15373. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15374. auto handled = false;
  15375. Server svr;
  15376. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15377. thread t = thread([&] { svr.listen(HOST, PORT); });
  15378. auto se = detail::scope_exit([&] {
  15379. svr.stop();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. ASSERT_FALSE(handled);
  15383. });
  15384. svr.wait_until_ready();
  15385. auto req = "POST /test HTTP/1.1\r\n"
  15386. "Content-Length: x\r\n"
  15387. "\r\n";
  15388. std::string response;
  15389. ASSERT_TRUE(send_request(1, req, &response));
  15390. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15391. response.substr(0, response.find("\r\n")));
  15392. }
  15393. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15394. // case-insensitive, and a server that receives a 100-continue expectation in
  15395. // an HTTP/1.0 request MUST ignore it.
  15396. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15397. std::string response;
  15398. ASSERT_TRUE(send_request(1, req, &response, port));
  15399. *got_100 = response.find("100 Continue") != std::string::npos;
  15400. }
  15401. class ExpectTokenTest : public ::testing::Test {
  15402. protected:
  15403. void SetUp() override {
  15404. svr_.Post("/p", [](const Request &, Response &res) {
  15405. res.set_content("ok", "text/plain");
  15406. });
  15407. port_ = svr_.bind_to_any_port(HOST);
  15408. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15409. svr_.wait_until_ready();
  15410. }
  15411. void TearDown() override {
  15412. svr_.stop();
  15413. if (thread_.joinable()) { thread_.join(); }
  15414. }
  15415. std::string request(const char *version, const char *expect_value) const {
  15416. return std::string("POST /p ") + version +
  15417. "\r\n"
  15418. "Host: localhost\r\n"
  15419. "Content-Length: 2\r\n"
  15420. "Connection: close\r\n"
  15421. "Expect: " +
  15422. expect_value +
  15423. "\r\n"
  15424. "\r\n"
  15425. "hi";
  15426. }
  15427. Server svr_;
  15428. int port_ = 0;
  15429. thread thread_;
  15430. };
  15431. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15432. bool got_100 = false;
  15433. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15434. EXPECT_TRUE(got_100);
  15435. }
  15436. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15437. bool got_100 = true;
  15438. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15439. EXPECT_FALSE(got_100);
  15440. }
  15441. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15442. bool got_100 = false;
  15443. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15444. EXPECT_TRUE(got_100);
  15445. }
  15446. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15447. bool got_100 = false;
  15448. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15449. EXPECT_TRUE(got_100);
  15450. }
  15451. // `100 Continue` is sent only when the server starts reading the body, so a
  15452. // request rejected before that never invites the client to send it. The
  15453. // requests below carry the expectation but withhold the body, as a client
  15454. // waiting for `100 Continue` would.
  15455. // A POST that expects `100 Continue` and withholds its two-byte body.
  15456. static std::string expect_headers_only(const std::string &path) {
  15457. return "POST " + path +
  15458. " HTTP/1.1\r\n"
  15459. "Host: localhost\r\n"
  15460. "Content-Length: 2\r\n"
  15461. "Expect: 100-continue\r\n"
  15462. "\r\n";
  15463. }
  15464. class ExpectLazyContinueTest : public ::testing::Test {
  15465. protected:
  15466. void SetUp() override {
  15467. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15468. if (req.path == "/pre-routing") {
  15469. res.status = StatusCode::Unauthorized_401;
  15470. return Server::HandlerResponse::Handled;
  15471. }
  15472. return Server::HandlerResponse::Unhandled;
  15473. });
  15474. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15475. if (req.matched_route == "/pre-request") {
  15476. res.status = StatusCode::Forbidden_403;
  15477. return Server::HandlerResponse::Handled;
  15478. }
  15479. return Server::HandlerResponse::Unhandled;
  15480. });
  15481. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15482. res.set_content("ok", "text/plain");
  15483. });
  15484. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15485. res.set_content("ok", "text/plain");
  15486. });
  15487. svr_.Post("/reader-used", [](const Request &, Response &res,
  15488. const ContentReader &content_reader) {
  15489. std::string body;
  15490. content_reader([&](const char *data, size_t len) {
  15491. body.append(data, len);
  15492. return true;
  15493. });
  15494. res.set_content(body, "text/plain");
  15495. });
  15496. svr_.Post("/reader-unused",
  15497. [](const Request &, Response &res, const ContentReader &) {
  15498. res.set_content("ignored", "text/plain");
  15499. });
  15500. port_ = svr_.bind_to_any_port(HOST);
  15501. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15502. svr_.wait_until_ready();
  15503. }
  15504. void TearDown() override {
  15505. svr_.stop();
  15506. if (thread_.joinable()) { thread_.join(); }
  15507. }
  15508. // Sends `req` and reads until the server closes the connection. Returns
  15509. // false if the read had to wait for the client-side timeout instead.
  15510. bool send_until_closed(const std::string &req, std::string *resp) const {
  15511. auto start = std::chrono::steady_clock::now();
  15512. if (!send_request(3, req, resp, port_)) { return false; }
  15513. auto elapsed = std::chrono::steady_clock::now() - start;
  15514. return elapsed < std::chrono::seconds(2);
  15515. }
  15516. // The final response comes without `100 Continue`, and the server closes
  15517. // the connection since the body may or may not follow.
  15518. void expect_final_without_interim(const std::string &path,
  15519. const char *status_line) const {
  15520. std::string resp;
  15521. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15522. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15523. EXPECT_EQ(0u, resp.find(status_line));
  15524. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15525. }
  15526. Server svr_;
  15527. int port_ = 0;
  15528. thread thread_;
  15529. };
  15530. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15531. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15532. }
  15533. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15534. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15535. }
  15536. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15537. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15538. }
  15539. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15540. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15541. }
  15542. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15543. // The body follows once `100 Continue` has had time to arrive.
  15544. auto req = expect_headers_only("/reader-used");
  15545. req.insert(req.size() - 2, "Connection: close\r\n");
  15546. std::string resp;
  15547. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15548. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15549. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15550. EXPECT_NE(std::string::npos, resp.find("hi"));
  15551. }
  15552. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15553. // Large enough for the client to add `Expect: 100-continue` itself.
  15554. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15555. std::atomic<bool> body_sent{false};
  15556. Client cli(HOST, port_);
  15557. auto res = cli.Post(
  15558. "/pre-request", length,
  15559. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15560. body_sent = true;
  15561. std::string chunk(len, 'x');
  15562. sink.write(chunk.data(), chunk.size());
  15563. return true;
  15564. },
  15565. "application/octet-stream");
  15566. ASSERT_TRUE(res);
  15567. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15568. EXPECT_FALSE(body_sent);
  15569. }
  15570. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15571. Server svr;
  15572. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15573. return StatusCode::ExpectationFailed_417;
  15574. });
  15575. svr.Post("/p", [](const Request &, Response &res) {
  15576. res.set_content("ok", "text/plain");
  15577. });
  15578. auto port = svr.bind_to_any_port(HOST);
  15579. thread t = thread([&] { svr.listen_after_bind(); });
  15580. auto se = detail::scope_exit([&] {
  15581. svr.stop();
  15582. t.join();
  15583. });
  15584. svr.wait_until_ready();
  15585. std::string resp;
  15586. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15587. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15588. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15589. // Exactly one response: the route handler must not run after the 417.
  15590. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15591. }
  15592. #ifndef _WIN32
  15593. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15594. static constexpr char reject[] = "Unauthorized";
  15595. static constexpr char accept[] = "Upload accepted";
  15596. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15597. Server svr;
  15598. svr.set_expect_100_continue_handler(
  15599. [](const Request & /*req*/, Response &res) {
  15600. res.status = StatusCode::Unauthorized_401;
  15601. res.set_content(reject, "text/plain");
  15602. return res.status;
  15603. });
  15604. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15605. res.set_content(accept, "text/plain");
  15606. });
  15607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15608. auto se = detail::scope_exit([&] {
  15609. svr.stop();
  15610. thread.join();
  15611. ASSERT_FALSE(svr.is_running());
  15612. });
  15613. svr.wait_until_ready();
  15614. {
  15615. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15616. curl_easy_init(), &curl_easy_cleanup};
  15617. ASSERT_NE(curl, nullptr);
  15618. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15619. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15620. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15621. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15622. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15623. &curl_slist_free_all};
  15624. ASSERT_NE(list, nullptr);
  15625. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15626. struct read_data {
  15627. size_t read_size;
  15628. size_t total_size;
  15629. } data = {0, total_size};
  15630. using read_callback_t =
  15631. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15632. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15633. void *userdata) -> size_t {
  15634. read_data *d = (read_data *)userdata;
  15635. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15636. std::fill_n(ptr, size * nmemb, 'A');
  15637. d->read_size += size * nmemb;
  15638. return size * nmemb;
  15639. };
  15640. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15641. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15642. std::vector<char> buffer;
  15643. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15644. using write_callback_t =
  15645. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15646. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15647. void *userdata) -> size_t {
  15648. std::vector<char> *buf = (std::vector<char> *)userdata;
  15649. buf->reserve(buf->size() + size * nmemb + 1);
  15650. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15651. return size * nmemb;
  15652. };
  15653. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15654. {
  15655. const auto res = curl_easy_perform(curl.get());
  15656. ASSERT_EQ(res, CURLE_OK);
  15657. }
  15658. {
  15659. auto response_code = long{};
  15660. const auto res =
  15661. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15662. ASSERT_EQ(res, CURLE_OK);
  15663. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15664. }
  15665. {
  15666. auto dl = curl_off_t{};
  15667. const auto res =
  15668. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15669. ASSERT_EQ(res, CURLE_OK);
  15670. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15671. }
  15672. {
  15673. buffer.push_back('\0');
  15674. ASSERT_STRCASEEQ(buffer.data(), reject);
  15675. }
  15676. }
  15677. }
  15678. #endif
  15679. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15680. // Regression test for #2458.
  15681. //
  15682. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15683. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15684. // ticket can make the client socket spuriously readable during the
  15685. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15686. // the client withholds the body and then blocks reading a response that never
  15687. // comes, failing with `Failed to read connection`.
  15688. //
  15689. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15690. // within the timeout. This raw OpenSSL server deliberately never sends
  15691. // `100 Continue`; the client must still deliver the body and receive 200.
  15692. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15693. signal(SIGPIPE, SIG_IGN);
  15694. const auto port = PORT + 4;
  15695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15696. ASSERT_NE(srv, INVALID_SOCKET);
  15697. int opt = 1;
  15698. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15699. sockaddr_in addr{};
  15700. addr.sin_family = AF_INET;
  15701. addr.sin_port = htons(static_cast<uint16_t>(port));
  15702. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15703. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15704. ASSERT_EQ(0, ::listen(srv, 1));
  15705. std::atomic<size_t> server_body_bytes{0};
  15706. auto server_thread = std::thread([&] {
  15707. sockaddr_in cli_addr{};
  15708. socklen_t cli_len = sizeof(cli_addr);
  15709. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15710. if (cli == INVALID_SOCKET) { return; }
  15711. // Bound the lifetime of the server side so a buggy client (which never
  15712. // sends the body) cannot make this thread block forever on join.
  15713. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15714. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15715. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15716. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15717. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15718. SSL *ssl = SSL_new(ctx);
  15719. SSL_set_fd(ssl, static_cast<int>(cli));
  15720. if (SSL_accept(ssl) > 0) {
  15721. // Read the request headers. Reading here also flushes the TLS 1.3
  15722. // session tickets to the client. Deliberately do NOT send
  15723. // `100 Continue`.
  15724. std::string buf;
  15725. char tmp[1024];
  15726. while (buf.find("\r\n\r\n") == std::string::npos) {
  15727. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15728. if (n <= 0) { break; }
  15729. buf.append(tmp, static_cast<size_t>(n));
  15730. }
  15731. // A correct client sends the body now; count what arrives.
  15732. auto pos = buf.find("\r\n\r\n");
  15733. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15734. while (body < 4096) {
  15735. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15736. if (n <= 0) { break; }
  15737. body += static_cast<size_t>(n);
  15738. }
  15739. server_body_bytes = body;
  15740. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15741. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15742. SSL_shutdown(ssl);
  15743. }
  15744. SSL_free(ssl);
  15745. detail::close_socket(cli);
  15746. SSL_CTX_free(ctx);
  15747. });
  15748. auto se = detail::scope_exit([&] {
  15749. server_thread.join();
  15750. detail::close_socket(srv);
  15751. });
  15752. SSLClient cli("127.0.0.1", port);
  15753. cli.enable_server_certificate_verification(false);
  15754. cli.set_connection_timeout(5, 0);
  15755. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15756. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15757. std::string body(4096, 'A');
  15758. auto res = cli.Put("/api/test", body, "application/json");
  15759. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15760. EXPECT_EQ(StatusCode::OK_200, res->status);
  15761. EXPECT_EQ(body.size(), server_body_bytes.load());
  15762. }
  15763. #endif
  15764. template <typename S, typename C>
  15765. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15766. svr.Get("/stream", [&](const Request &, Response &res) {
  15767. auto data = new std::string("01234567890123456789");
  15768. res.set_content_provider(
  15769. data->size(), "text/plain",
  15770. [&, data](size_t offset, size_t length, DataSink &sink) {
  15771. const size_t DATA_CHUNK_SIZE = 4;
  15772. const auto &d = *data;
  15773. std::this_thread::sleep_for(std::chrono::seconds(1));
  15774. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15775. return true;
  15776. },
  15777. [data](bool success) {
  15778. EXPECT_FALSE(success);
  15779. delete data;
  15780. });
  15781. });
  15782. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15783. auto i = new size_t(0);
  15784. res.set_content_provider(
  15785. "text/plain",
  15786. [i](size_t, DataSink &sink) {
  15787. if (*i < 5) {
  15788. std::this_thread::sleep_for(std::chrono::seconds(1));
  15789. sink.write("abcd", 4);
  15790. (*i)++;
  15791. } else {
  15792. sink.done();
  15793. }
  15794. return true;
  15795. },
  15796. [i](bool success) {
  15797. EXPECT_FALSE(success);
  15798. delete i;
  15799. });
  15800. });
  15801. svr.Get("/chunked", [&](const Request &, Response &res) {
  15802. auto i = new size_t(0);
  15803. res.set_chunked_content_provider(
  15804. "text/plain",
  15805. [i](size_t, DataSink &sink) {
  15806. if (*i < 5) {
  15807. std::this_thread::sleep_for(std::chrono::seconds(1));
  15808. sink.os << "abcd";
  15809. (*i)++;
  15810. } else {
  15811. sink.done();
  15812. }
  15813. return true;
  15814. },
  15815. [i](bool success) {
  15816. EXPECT_FALSE(success);
  15817. delete i;
  15818. });
  15819. });
  15820. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15821. auto se = detail::scope_exit([&] {
  15822. svr.stop();
  15823. listen_thread.join();
  15824. ASSERT_FALSE(svr.is_running());
  15825. });
  15826. svr.wait_until_ready();
  15827. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15828. {
  15829. auto start = std::chrono::steady_clock::now();
  15830. auto res = cli.Get("/stream");
  15831. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15832. std::chrono::steady_clock::now() - start)
  15833. .count();
  15834. ASSERT_FALSE(res);
  15835. EXPECT_EQ(Error::Read, res.error());
  15836. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15837. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15838. }
  15839. {
  15840. auto start = std::chrono::steady_clock::now();
  15841. auto res = cli.Get("/stream_without_length");
  15842. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15843. std::chrono::steady_clock::now() - start)
  15844. .count();
  15845. ASSERT_FALSE(res);
  15846. EXPECT_EQ(Error::Read, res.error());
  15847. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15848. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15849. }
  15850. {
  15851. auto start = std::chrono::steady_clock::now();
  15852. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15853. EXPECT_EQ("abcd", string(data, data_length));
  15854. return true;
  15855. });
  15856. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15857. std::chrono::steady_clock::now() - start)
  15858. .count();
  15859. ASSERT_FALSE(res);
  15860. EXPECT_EQ(Error::Read, res.error());
  15861. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15862. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15863. }
  15864. }
  15865. TEST(MaxTimeoutTest, ContentStream) {
  15866. time_t timeout = 2000;
  15867. time_t threshold = 200;
  15868. Server svr;
  15869. Client cli("localhost", PORT);
  15870. max_timeout_test(svr, cli, timeout, threshold);
  15871. }
  15872. #ifdef CPPHTTPLIB_SSL_ENABLED
  15873. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15874. time_t timeout = 2000;
  15875. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15877. SSLClient cli("localhost", PORT);
  15878. cli.enable_server_certificate_verification(false);
  15879. max_timeout_test(svr, cli, timeout, threshold);
  15880. }
  15881. #endif
  15882. class EventDispatcher {
  15883. public:
  15884. EventDispatcher() {}
  15885. bool wait_event(DataSink *sink) {
  15886. unique_lock<mutex> lk(m_);
  15887. int id = id_;
  15888. // Wait with timeout to prevent hanging if client disconnects
  15889. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15890. [&] { return cid_ == id; })) {
  15891. return false; // Timeout occurred
  15892. }
  15893. sink->write(message_.data(), message_.size());
  15894. return true;
  15895. }
  15896. void send_event(const string &message) {
  15897. lock_guard<mutex> lk(m_);
  15898. cid_ = id_++;
  15899. message_ = message;
  15900. cv_.notify_all();
  15901. }
  15902. private:
  15903. mutex m_;
  15904. condition_variable cv_;
  15905. atomic_int id_{0};
  15906. atomic_int cid_{-1};
  15907. string message_;
  15908. };
  15909. TEST(ClientInThreadTest, Issue2068) {
  15910. EventDispatcher ed;
  15911. Server svr;
  15912. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15913. res.set_chunked_content_provider("text/event-stream",
  15914. [&](size_t /*offset*/, DataSink &sink) {
  15915. return ed.wait_event(&sink);
  15916. });
  15917. });
  15918. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15919. svr.wait_until_ready();
  15920. thread event_thread([&] {
  15921. int id = 0;
  15922. while (svr.is_running()) {
  15923. this_thread::sleep_for(chrono::milliseconds(500));
  15924. std::stringstream ss;
  15925. ss << "data: " << id << "\n\n";
  15926. ed.send_event(ss.str());
  15927. id++;
  15928. }
  15929. });
  15930. auto se = detail::scope_exit([&] {
  15931. svr.stop();
  15932. listen_thread.join();
  15933. event_thread.join();
  15934. ASSERT_FALSE(svr.is_running());
  15935. });
  15936. {
  15937. auto client = detail::make_unique<Client>(HOST, PORT);
  15938. client->set_read_timeout(std::chrono::minutes(10));
  15939. std::atomic<bool> stop{false};
  15940. std::thread t([&] {
  15941. client->Get("/event1",
  15942. [&](const char *, size_t) -> bool { return !stop; });
  15943. });
  15944. std::this_thread::sleep_for(std::chrono::seconds(2));
  15945. stop = true;
  15946. client->stop();
  15947. t.join();
  15948. // Reset client after thread has finished
  15949. client.reset();
  15950. }
  15951. }
  15952. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15953. auto handled = false;
  15954. Server svr;
  15955. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15957. auto se = detail::scope_exit([&] {
  15958. svr.stop();
  15959. t.join();
  15960. ASSERT_FALSE(svr.is_running());
  15961. ASSERT_FALSE(handled);
  15962. });
  15963. svr.wait_until_ready();
  15964. // Two Content-Length headers with different values — must be rejected
  15965. auto req = "POST /test HTTP/1.1\r\n"
  15966. "Content-Length: 5\r\n"
  15967. "Content-Length: 10\r\n"
  15968. "\r\n"
  15969. "hello";
  15970. std::string response;
  15971. ASSERT_TRUE(send_request(1, req, &response));
  15972. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15973. response.substr(0, response.find("\r\n")));
  15974. }
  15975. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15976. auto handled = false;
  15977. Server svr;
  15978. svr.Post("/test", [&](const Request &, Response &res) {
  15979. handled = true;
  15980. res.set_content("ok", "text/plain");
  15981. });
  15982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15983. auto se = detail::scope_exit([&] {
  15984. svr.stop();
  15985. t.join();
  15986. ASSERT_FALSE(svr.is_running());
  15987. ASSERT_TRUE(handled);
  15988. });
  15989. svr.wait_until_ready();
  15990. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15991. auto req = "POST /test HTTP/1.1\r\n"
  15992. "Content-Length: 5\r\n"
  15993. "Content-Length: 5\r\n"
  15994. "\r\n"
  15995. "hello";
  15996. std::string response;
  15997. ASSERT_TRUE(send_request(1, req, &response));
  15998. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15999. }
  16000. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16001. Server svr;
  16002. svr.Get("/", [](const Request &req, Response &res) {
  16003. EXPECT_EQ(2U, req.trailers.size());
  16004. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16005. // Denied
  16006. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16007. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16008. // Accepted
  16009. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16010. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16011. EXPECT_TRUE(req.has_trailer("X-World"));
  16012. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16013. res.set_content("ok", "text/plain");
  16014. });
  16015. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16016. auto se = detail::scope_exit([&] {
  16017. svr.stop();
  16018. t.join();
  16019. ASSERT_FALSE(svr.is_running());
  16020. });
  16021. svr.wait_until_ready();
  16022. const std::string req = "GET / HTTP/1.1\r\n"
  16023. "Transfer-Encoding: chunked\r\n"
  16024. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16025. "\r\n"
  16026. "0\r\n"
  16027. "Content-Length: 10\r\n"
  16028. "Host: internal.local\r\n"
  16029. "Content-Type: malicious/content\r\n"
  16030. "Cookie: any\r\n"
  16031. "Set-Cookie: any\r\n"
  16032. "X-Forwarded-For: attacker.com\r\n"
  16033. "X-Real-Ip: 1.1.1.1\r\n"
  16034. "X-Hello: hello\r\n"
  16035. "X-World: world\r\n"
  16036. "\r\n";
  16037. std::string res;
  16038. ASSERT_TRUE(send_request(1, req, &res));
  16039. }
  16040. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16041. // several field lines, and the combined value is what has to be parsed. A
  16042. // Trailer field split across lines therefore declares every name it lists;
  16043. // reading only the first line silently drops the trailers the later lines
  16044. // declare. The prohibited-trailer filter still applies to every line.
  16045. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16046. Server svr;
  16047. size_t observed_trailer_count = 0;
  16048. std::string observed_hello;
  16049. std::string observed_world;
  16050. bool observed_content_length = true;
  16051. svr.Get("/", [&](const Request &req, Response &res) {
  16052. observed_trailer_count = req.trailers.size();
  16053. observed_hello = req.get_trailer_value("X-Hello");
  16054. observed_world = req.get_trailer_value("X-World");
  16055. observed_content_length = req.has_trailer("Content-Length");
  16056. res.set_content("ok", "text/plain");
  16057. });
  16058. auto port = svr.bind_to_any_port(HOST);
  16059. thread t = thread([&]() { svr.listen_after_bind(); });
  16060. auto se = detail::scope_exit([&] {
  16061. svr.stop();
  16062. t.join();
  16063. ASSERT_FALSE(svr.is_running());
  16064. });
  16065. svr.wait_until_ready();
  16066. const std::string req = "GET / HTTP/1.1\r\n"
  16067. "Transfer-Encoding: chunked\r\n"
  16068. "Trailer: X-Hello\r\n"
  16069. "Trailer: X-World, Content-Length\r\n"
  16070. "\r\n"
  16071. "0\r\n"
  16072. "X-Hello: hello\r\n"
  16073. "X-World: world\r\n"
  16074. "Content-Length: 10\r\n"
  16075. "\r\n";
  16076. std::string res;
  16077. ASSERT_TRUE(send_request(1, req, &res, port));
  16078. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16079. // Accepted: both field lines contribute to the declared set
  16080. EXPECT_EQ(2U, observed_trailer_count);
  16081. EXPECT_EQ(observed_hello, "hello");
  16082. EXPECT_EQ(observed_world, "world");
  16083. // Denied: a prohibited name stays prohibited on a later field line
  16084. EXPECT_FALSE(observed_content_length);
  16085. }
  16086. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16087. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16088. // unbounded run of fields that are never declared, because the counter would
  16089. // only advance for declared fields.
  16090. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16091. Server svr;
  16092. bool handler_called = false;
  16093. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16094. handler_called = true;
  16095. res.set_content("ok", "text/plain");
  16096. });
  16097. auto port = svr.bind_to_any_port(HOST);
  16098. thread t = thread([&]() { svr.listen_after_bind(); });
  16099. auto se = detail::scope_exit([&] {
  16100. svr.stop();
  16101. t.join();
  16102. ASSERT_FALSE(svr.is_running());
  16103. });
  16104. svr.wait_until_ready();
  16105. // Declare nothing, then send far more undeclared trailer fields than the
  16106. // header-count limit. Parsing must stop and reject the request rather than
  16107. // read every line.
  16108. std::string req = "GET / HTTP/1.1\r\n"
  16109. "Transfer-Encoding: chunked\r\n"
  16110. "\r\n"
  16111. "0\r\n";
  16112. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16113. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16114. }
  16115. req += "\r\n";
  16116. std::string res;
  16117. ASSERT_TRUE(send_request(1, req, &res, port));
  16118. // The request is rejected before the handler runs.
  16119. EXPECT_FALSE(handler_called);
  16120. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16121. }
  16122. // The set of declared trailer names is capped so a peer cannot grow it without
  16123. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16124. // declared past the cap is not honored, even if the field is actually sent.
  16125. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16126. Server svr;
  16127. // One name inside the cap and one past it, so the test tracks the cap rather
  16128. // than a fixed count.
  16129. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16130. const std::string within_cap_name = "X-T-0";
  16131. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16132. bool observed_within_cap = false;
  16133. bool observed_past_cap = false;
  16134. svr.Get("/", [&](const Request &req, Response &res) {
  16135. observed_within_cap = req.has_trailer(within_cap_name);
  16136. observed_past_cap = req.has_trailer(past_cap_name);
  16137. res.set_content("ok", "text/plain");
  16138. });
  16139. auto port = svr.bind_to_any_port(HOST);
  16140. thread t = thread([&]() { svr.listen_after_bind(); });
  16141. auto se = detail::scope_exit([&] {
  16142. svr.stop();
  16143. t.join();
  16144. ASSERT_FALSE(svr.is_running());
  16145. });
  16146. svr.wait_until_ready();
  16147. // Declare more trailer names than the cap in a single Trailer field, then
  16148. // actually send the first (within the cap) and the last (past it).
  16149. std::string trailer_decl = "Trailer: ";
  16150. for (int i = 0; i < declared_count; i++) {
  16151. if (i != 0) { trailer_decl += ", "; }
  16152. trailer_decl += "X-T-" + std::to_string(i);
  16153. }
  16154. trailer_decl += "\r\n";
  16155. const std::string req = "GET / HTTP/1.1\r\n"
  16156. "Transfer-Encoding: chunked\r\n" +
  16157. trailer_decl +
  16158. "\r\n"
  16159. "0\r\n" +
  16160. within_cap_name + ": a\r\n" + past_cap_name +
  16161. ": b\r\n"
  16162. "\r\n";
  16163. std::string res;
  16164. ASSERT_TRUE(send_request(1, req, &res, port));
  16165. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16166. // A name within the cap is honored; one declared past the cap is dropped.
  16167. EXPECT_TRUE(observed_within_cap);
  16168. EXPECT_FALSE(observed_past_cap);
  16169. }
  16170. // A direct client that is not listed in trusted_proxies must not be able to
  16171. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16172. // the peer address on the actual TCP connection determines whether the
  16173. // header is honored.
  16174. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16175. Server svr;
  16176. // Deliberately does NOT include the loopback address the test client
  16177. // actually connects from, so the direct connection is not a trusted proxy.
  16178. svr.set_trusted_proxies({"203.0.113.66"});
  16179. std::string observed_remote_addr;
  16180. svr.Get("/ip", [&](const Request &req, Response &res) {
  16181. observed_remote_addr = req.remote_addr;
  16182. res.set_content("ok", "text/plain");
  16183. });
  16184. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16185. auto se = detail::scope_exit([&] {
  16186. svr.stop();
  16187. t.join();
  16188. ASSERT_FALSE(svr.is_running());
  16189. });
  16190. svr.wait_until_ready();
  16191. Client cli(HOST, PORT);
  16192. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16194. EXPECT_EQ(StatusCode::OK_200, res->status);
  16195. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16196. // ignored entirely and the real connection-level address retained.
  16197. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16198. observed_remote_addr == "127.0.0.1");
  16199. }
  16200. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16201. Server svr;
  16202. std::string observed_remote_addr;
  16203. std::string observed_xff;
  16204. svr.Get("/ip", [&](const Request &req, Response &res) {
  16205. observed_remote_addr = req.remote_addr;
  16206. observed_xff = req.get_header_value("X-Forwarded-For");
  16207. res.set_content("ok", "text/plain");
  16208. });
  16209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16210. auto se = detail::scope_exit([&] {
  16211. svr.stop();
  16212. t.join();
  16213. ASSERT_FALSE(svr.is_running());
  16214. });
  16215. svr.wait_until_ready();
  16216. Client cli(HOST, PORT);
  16217. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16219. EXPECT_EQ(StatusCode::OK_200, res->status);
  16220. EXPECT_EQ(observed_xff, "203.0.113.66");
  16221. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16222. observed_remote_addr == "127.0.0.1");
  16223. }
  16224. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16225. Server svr;
  16226. svr.set_trusted_proxies({"203.0.113.66"});
  16227. std::string observed_remote_addr;
  16228. std::string observed_xff;
  16229. svr.Get("/ip", [&](const Request &req, Response &res) {
  16230. observed_remote_addr = req.remote_addr;
  16231. observed_xff = req.get_header_value("X-Forwarded-For");
  16232. res.set_content("ok", "text/plain");
  16233. });
  16234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16235. auto se = detail::scope_exit([&] {
  16236. svr.stop();
  16237. t.join();
  16238. ASSERT_FALSE(svr.is_running());
  16239. });
  16240. svr.wait_until_ready();
  16241. Client cli(HOST, PORT);
  16242. auto res = cli.Get("/ip");
  16243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16244. EXPECT_EQ(StatusCode::OK_200, res->status);
  16245. EXPECT_EQ(observed_xff, "");
  16246. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16247. observed_remote_addr == "127.0.0.1");
  16248. }
  16249. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16250. Server svr;
  16251. // Include the loopback address the test client actually connects from, so
  16252. // the direct connection itself is recognized as the trusted proxy hop.
  16253. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16254. std::string observed_remote_addr;
  16255. std::string observed_xff;
  16256. svr.Get("/ip", [&](const Request &req, Response &res) {
  16257. observed_remote_addr = req.remote_addr;
  16258. observed_xff = req.get_header_value("X-Forwarded-For");
  16259. res.set_content("ok", "text/plain");
  16260. });
  16261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16262. auto se = detail::scope_exit([&] {
  16263. svr.stop();
  16264. t.join();
  16265. ASSERT_FALSE(svr.is_running());
  16266. });
  16267. svr.wait_until_ready();
  16268. Client cli(HOST, PORT);
  16269. auto res = cli.Get(
  16270. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16272. EXPECT_EQ(StatusCode::OK_200, res->status);
  16273. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16274. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16275. }
  16276. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16277. Server svr;
  16278. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16279. std::string observed_remote_addr;
  16280. std::string observed_xff;
  16281. svr.Get("/ip", [&](const Request &req, Response &res) {
  16282. observed_remote_addr = req.remote_addr;
  16283. observed_xff = req.get_header_value("X-Forwarded-For");
  16284. res.set_content("ok", "text/plain");
  16285. });
  16286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. });
  16292. svr.wait_until_ready();
  16293. Client cli(HOST, PORT);
  16294. auto res = cli.Get(
  16295. "/ip",
  16296. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16298. EXPECT_EQ(StatusCode::OK_200, res->status);
  16299. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16300. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16301. }
  16302. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16303. Server svr;
  16304. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16305. std::string observed_remote_addr;
  16306. std::string observed_xff;
  16307. svr.Get("/ip", [&](const Request &req, Response &res) {
  16308. observed_remote_addr = req.remote_addr;
  16309. observed_xff = req.get_header_value("X-Forwarded-For");
  16310. res.set_content("ok", "text/plain");
  16311. });
  16312. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16313. auto se = detail::scope_exit([&] {
  16314. svr.stop();
  16315. t.join();
  16316. ASSERT_FALSE(svr.is_running());
  16317. });
  16318. svr.wait_until_ready();
  16319. Client cli(HOST, PORT);
  16320. auto res = cli.Get(
  16321. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16323. EXPECT_EQ(StatusCode::OK_200, res->status);
  16324. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16325. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16326. // and must not be selected.
  16327. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16328. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16329. }
  16330. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16331. Server svr;
  16332. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16333. std::string observed_remote_addr;
  16334. svr.Get("/ip", [&](const Request &req, Response &res) {
  16335. observed_remote_addr = req.remote_addr;
  16336. res.set_content("ok", "text/plain");
  16337. });
  16338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16339. auto se = detail::scope_exit([&] {
  16340. svr.stop();
  16341. t.join();
  16342. ASSERT_FALSE(svr.is_running());
  16343. });
  16344. svr.wait_until_ready();
  16345. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16346. // a forged address and the trusted proxy's own address; the forged value must
  16347. // not win over the address the trusted proxy actually recorded.
  16348. Client cli(HOST, PORT);
  16349. auto res = cli.Get(
  16350. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16352. EXPECT_EQ(StatusCode::OK_200, res->status);
  16353. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16354. }
  16355. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16356. Server svr;
  16357. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16358. std::string observed_remote_addr;
  16359. std::string observed_xff;
  16360. svr.Get("/ip", [&](const Request &req, Response &res) {
  16361. observed_remote_addr = req.remote_addr;
  16362. observed_xff = req.get_header_value("X-Forwarded-For");
  16363. res.set_content("ok", "text/plain");
  16364. });
  16365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16366. auto se = detail::scope_exit([&] {
  16367. svr.stop();
  16368. t.join();
  16369. ASSERT_FALSE(svr.is_running());
  16370. });
  16371. svr.wait_until_ready();
  16372. Client cli(HOST, PORT);
  16373. auto res = cli.Get(
  16374. "/ip",
  16375. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16377. EXPECT_EQ(StatusCode::OK_200, res->status);
  16378. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16379. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16380. }
  16381. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16382. Server svr;
  16383. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16384. std::string observed_remote_addr;
  16385. std::string observed_xff;
  16386. svr.Get("/ip", [&](const Request &req, Response &res) {
  16387. observed_remote_addr = req.remote_addr;
  16388. observed_xff = req.get_header_value("X-Forwarded-For");
  16389. res.set_content("ok", "text/plain");
  16390. });
  16391. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16392. auto se = detail::scope_exit([&] {
  16393. svr.stop();
  16394. t.join();
  16395. ASSERT_FALSE(svr.is_running());
  16396. });
  16397. svr.wait_until_ready();
  16398. std::string raw_req =
  16399. "GET /ip HTTP/1.1\r\n"
  16400. "Host: localhost\r\n"
  16401. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16402. "Connection: close\r\n"
  16403. "\r\n";
  16404. std::string out;
  16405. ASSERT_TRUE(send_request(5, raw_req, &out));
  16406. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16407. // Header parser trims surrounding whitespace of the header value
  16408. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16409. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16410. }
  16411. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16412. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16413. // their own X-Forwarded-For as a separate field line rather than extending the
  16414. // one the client sent, so every occurrence has to be taken into account.
  16415. // Reading only the first one hands back the address the client chose.
  16416. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16417. Server svr;
  16418. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16419. std::string observed_remote_addr;
  16420. size_t observed_xff_count = 0;
  16421. svr.Get("/ip", [&](const Request &req, Response &res) {
  16422. observed_remote_addr = req.remote_addr;
  16423. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16424. res.set_content("ok", "text/plain");
  16425. });
  16426. auto port = svr.bind_to_any_port(HOST);
  16427. thread t = thread([&]() { svr.listen_after_bind(); });
  16428. auto se = detail::scope_exit([&] {
  16429. svr.stop();
  16430. t.join();
  16431. ASSERT_FALSE(svr.is_running());
  16432. });
  16433. svr.wait_until_ready();
  16434. // The client supplies the first field line; the trusted proxy appends the
  16435. // address it observed as a second one.
  16436. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16437. "Host: localhost\r\n"
  16438. "X-Forwarded-For: 1.2.3.4\r\n"
  16439. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16440. "Connection: close\r\n"
  16441. "\r\n";
  16442. std::string out;
  16443. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16444. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16445. EXPECT_EQ(observed_xff_count, 2U);
  16446. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16447. // The same chain spread over one field line per hop derives the same client
  16448. // address, i.e. the split and the comma-joined representations agree.
  16449. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16450. "Host: localhost\r\n"
  16451. "X-Forwarded-For: 1.2.3.4\r\n"
  16452. "X-Forwarded-For: 198.51.100.23\r\n"
  16453. "X-Forwarded-For: 192.0.2.45\r\n"
  16454. "Connection: close\r\n"
  16455. "\r\n";
  16456. out.clear();
  16457. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16458. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16459. EXPECT_EQ(observed_xff_count, 3U);
  16460. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16461. }
  16462. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16463. // crash the server (it used to call front() on an empty vector inside
  16464. // get_client_ip). The connection-level remote address must be retained instead.
  16465. static void run_malformed_xff_test(const std::string &xff_value) {
  16466. Server svr;
  16467. svr.set_trusted_proxies({"192.0.2.45"});
  16468. std::string observed_remote_addr;
  16469. svr.Get("/ip", [&](const Request &req, Response &res) {
  16470. observed_remote_addr = req.remote_addr;
  16471. res.set_content("ok", "text/plain");
  16472. });
  16473. int port = 0;
  16474. thread t = thread([&]() {
  16475. port = svr.bind_to_any_port(HOST);
  16476. svr.listen_after_bind();
  16477. });
  16478. auto se = detail::scope_exit([&] {
  16479. svr.stop();
  16480. t.join();
  16481. ASSERT_FALSE(svr.is_running());
  16482. });
  16483. svr.wait_until_ready();
  16484. Client cli(HOST, port);
  16485. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16487. EXPECT_EQ(StatusCode::OK_200, res->status);
  16488. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16489. observed_remote_addr == "127.0.0.1");
  16490. }
  16491. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16492. run_malformed_xff_test("");
  16493. }
  16494. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16495. run_malformed_xff_test(",");
  16496. }
  16497. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16498. run_malformed_xff_test(", , ,");
  16499. }
  16500. // The same rule applies to Accept: a request whose acceptable types are spread
  16501. // over several field lines must be negotiated against all of them.
  16502. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16503. // case-insensitive connection options. Comparing the whole field value against
  16504. // one option misses a client that sends several of them, and misses every
  16505. // casing but the one written in the comparison.
  16506. //
  16507. // Sends req, reads the response, then reuses the same socket for a second
  16508. // request to find out whether the server kept the connection.
  16509. static void probe_connection_reuse(int port, const std::string &req,
  16510. bool *announced_close, bool *reusable) {
  16511. auto error = Error::Success;
  16512. auto sock = detail::create_client_socket(
  16513. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16514. /*connection_timeout_sec=*/5, 0,
  16515. /*read_timeout_sec=*/1, 0,
  16516. /*write_timeout_sec=*/5, 0, std::string(), error);
  16517. ASSERT_NE(sock, INVALID_SOCKET);
  16518. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16519. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16520. "Host: localhost\r\n"
  16521. "Connection: close\r\n"
  16522. "\r\n";
  16523. std::string first_response;
  16524. std::string second_response;
  16525. detail::process_client_socket(
  16526. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16527. [&](Stream &strm) {
  16528. if (strm.write(req.data(), req.size()) !=
  16529. static_cast<ssize_t>(req.size())) {
  16530. return false;
  16531. }
  16532. char buf[512];
  16533. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16534. // Headers plus the two-byte body of the handler below
  16535. while (reader.getline()) {
  16536. first_response += reader.ptr();
  16537. if (first_response.find("ok") != std::string::npos) { break; }
  16538. }
  16539. if (strm.write(second.data(), second.size()) !=
  16540. static_cast<ssize_t>(second.size())) {
  16541. return true;
  16542. }
  16543. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16544. while (reader2.getline()) {
  16545. second_response += reader2.ptr();
  16546. if (second_response.find("ok") != std::string::npos) { break; }
  16547. }
  16548. return true;
  16549. });
  16550. *announced_close =
  16551. first_response.find("Connection: close") != std::string::npos;
  16552. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16553. }
  16554. class ConnectionTokenTest : public ::testing::Test {
  16555. protected:
  16556. void SetUp() override {
  16557. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16558. res.set_content("ok", "text/plain");
  16559. });
  16560. port_ = svr_.bind_to_any_port(HOST);
  16561. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16562. svr_.wait_until_ready();
  16563. }
  16564. void TearDown() override {
  16565. svr_.stop();
  16566. if (thread_.joinable()) { thread_.join(); }
  16567. }
  16568. Server svr_;
  16569. int port_ = 0;
  16570. thread thread_;
  16571. };
  16572. // "close" alongside another option still closes the connection, and the
  16573. // response says so rather than leaving the peer to discover it.
  16574. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16575. bool announced_close = false;
  16576. bool reusable = true;
  16577. probe_connection_reuse(port_,
  16578. "GET /keepalive HTTP/1.1\r\n"
  16579. "Host: localhost\r\n"
  16580. "Connection: keep-alive, close\r\n"
  16581. "\r\n",
  16582. &announced_close, &reusable);
  16583. EXPECT_TRUE(announced_close);
  16584. EXPECT_FALSE(reusable);
  16585. }
  16586. // "close" split over two field lines is the same list, so it is honored too.
  16587. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16588. bool announced_close = false;
  16589. bool reusable = true;
  16590. probe_connection_reuse(port_,
  16591. "GET /keepalive HTTP/1.1\r\n"
  16592. "Host: localhost\r\n"
  16593. "Connection: keep-alive\r\n"
  16594. "Connection: close\r\n"
  16595. "\r\n",
  16596. &announced_close, &reusable);
  16597. EXPECT_TRUE(announced_close);
  16598. EXPECT_FALSE(reusable);
  16599. }
  16600. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16601. // keep-alive in the spelling everyone actually sends keeps its connection.
  16602. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16603. bool announced_close = false;
  16604. bool reusable = false;
  16605. probe_connection_reuse(port_,
  16606. "GET /keepalive HTTP/1.0\r\n"
  16607. "Host: localhost\r\n"
  16608. "Connection: keep-alive\r\n"
  16609. "\r\n",
  16610. &announced_close, &reusable);
  16611. EXPECT_FALSE(announced_close);
  16612. EXPECT_TRUE(reusable);
  16613. }
  16614. // A token the value merely contains is not the token itself.
  16615. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16616. bool announced_close = false;
  16617. bool reusable = false;
  16618. probe_connection_reuse(port_,
  16619. "GET /keepalive HTTP/1.1\r\n"
  16620. "Host: localhost\r\n"
  16621. "Connection: notclose\r\n"
  16622. "\r\n",
  16623. &announced_close, &reusable);
  16624. EXPECT_FALSE(announced_close);
  16625. EXPECT_TRUE(reusable);
  16626. }
  16627. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16628. Server svr;
  16629. std::vector<std::string> observed_types;
  16630. svr.Get("/", [&](const Request &req, Response &res) {
  16631. observed_types = req.accept_content_types;
  16632. res.set_content("ok", "text/plain");
  16633. });
  16634. auto port = svr.bind_to_any_port(HOST);
  16635. thread t = thread([&]() { svr.listen_after_bind(); });
  16636. auto se = detail::scope_exit([&] {
  16637. svr.stop();
  16638. t.join();
  16639. ASSERT_FALSE(svr.is_running());
  16640. });
  16641. svr.wait_until_ready();
  16642. Client cli(HOST, port);
  16643. Headers headers;
  16644. headers.emplace("Accept", "text/plain;q=0.5");
  16645. headers.emplace("Accept", "application/json");
  16646. auto res = cli.Get("/", headers);
  16647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16648. EXPECT_EQ(StatusCode::OK_200, res->status);
  16649. // Sorted by q-value, so the second field line's type comes first
  16650. ASSERT_EQ(2U, observed_types.size());
  16651. EXPECT_EQ("application/json", observed_types[0]);
  16652. EXPECT_EQ("text/plain", observed_types[1]);
  16653. }
  16654. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16655. // empty field line must not contribute a bare comma to the combined value.
  16656. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16657. Server svr;
  16658. std::vector<std::string> observed_types;
  16659. svr.Get("/", [&](const Request &req, Response &res) {
  16660. observed_types = req.accept_content_types;
  16661. res.set_content("ok", "text/plain");
  16662. });
  16663. auto port = svr.bind_to_any_port(HOST);
  16664. thread t = thread([&]() { svr.listen_after_bind(); });
  16665. auto se = detail::scope_exit([&] {
  16666. svr.stop();
  16667. t.join();
  16668. ASSERT_FALSE(svr.is_running());
  16669. });
  16670. svr.wait_until_ready();
  16671. // Empty first field line, then a real one
  16672. std::string raw_req = "GET / HTTP/1.1\r\n"
  16673. "Host: localhost\r\n"
  16674. "Accept:\r\n"
  16675. "Accept: application/json\r\n"
  16676. "Connection: close\r\n"
  16677. "\r\n";
  16678. std::string out;
  16679. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16680. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16681. ASSERT_EQ(1U, observed_types.size());
  16682. EXPECT_EQ("application/json", observed_types[0]);
  16683. }
  16684. // The skip in get_combined_header_value() is what keeps an empty field line
  16685. // from contributing a bare comma. Only a trailing empty field line exercises
  16686. // it: a leading one is already covered by the "combined is still empty" check,
  16687. // and parse_accept_header() now ignores the empty element either way, so the
  16688. // request-level test above can no longer tell the two apart.
  16689. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16690. Headers headers;
  16691. headers.emplace("Accept", "text/html");
  16692. headers.emplace("Accept", "");
  16693. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16694. headers.clear();
  16695. headers.emplace("Accept", "");
  16696. headers.emplace("Accept", "application/json");
  16697. EXPECT_EQ("application/json",
  16698. detail::get_combined_header_value(headers, "Accept"));
  16699. }
  16700. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16701. // An encoding offered on a later Accept-Encoding field line is still offered.
  16702. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16703. Server svr;
  16704. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16705. res.set_content(std::string(1024, 'x'), "text/plain");
  16706. });
  16707. auto port = svr.bind_to_any_port(HOST);
  16708. thread t = thread([&]() { svr.listen_after_bind(); });
  16709. auto se = detail::scope_exit([&] {
  16710. svr.stop();
  16711. t.join();
  16712. ASSERT_FALSE(svr.is_running());
  16713. });
  16714. svr.wait_until_ready();
  16715. Client cli(HOST, port);
  16716. cli.set_decompress(false);
  16717. Headers headers;
  16718. headers.emplace("Accept-Encoding", "identity");
  16719. headers.emplace("Accept-Encoding", "gzip");
  16720. auto res = cli.Get("/", headers);
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::OK_200, res->status);
  16723. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16724. }
  16725. #endif
  16726. #ifndef _WIN32
  16727. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16728. Server svr;
  16729. svr.Post("/post", [&](const Request &req, Response &res) {
  16730. res.set_content(req.body, "text/plain");
  16731. });
  16732. svr.Put("/put", [&](const Request &req, Response &res) {
  16733. res.set_content(req.body, "text/plain");
  16734. });
  16735. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16736. res.set_content(req.body, "text/plain");
  16737. });
  16738. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16739. res.set_content(req.body, "text/plain");
  16740. });
  16741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16742. auto se = detail::scope_exit([&] {
  16743. svr.stop();
  16744. t.join();
  16745. ASSERT_FALSE(svr.is_running());
  16746. });
  16747. svr.wait_until_ready();
  16748. std::string resp;
  16749. // POST without Content-Length
  16750. ASSERT_TRUE(send_request(5,
  16751. "POST /post HTTP/1.1\r\n"
  16752. "Host: localhost\r\n"
  16753. "Connection: close\r\n"
  16754. "\r\n",
  16755. &resp));
  16756. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16757. // PUT without Content-Length
  16758. resp.clear();
  16759. ASSERT_TRUE(send_request(5,
  16760. "PUT /put HTTP/1.1\r\n"
  16761. "Host: localhost\r\n"
  16762. "Connection: close\r\n"
  16763. "\r\n",
  16764. &resp));
  16765. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16766. // PATCH without Content-Length
  16767. resp.clear();
  16768. ASSERT_TRUE(send_request(5,
  16769. "PATCH /patch HTTP/1.1\r\n"
  16770. "Host: localhost\r\n"
  16771. "Connection: close\r\n"
  16772. "\r\n",
  16773. &resp));
  16774. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16775. // DELETE without Content-Length
  16776. resp.clear();
  16777. ASSERT_TRUE(send_request(5,
  16778. "DELETE /delete HTTP/1.1\r\n"
  16779. "Host: localhost\r\n"
  16780. "Connection: close\r\n"
  16781. "\r\n",
  16782. &resp));
  16783. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16784. }
  16785. #endif
  16786. //==============================================================================
  16787. // open_stream() Tests
  16788. //==============================================================================
  16789. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16790. std::string result;
  16791. char buf[8192];
  16792. ssize_t n;
  16793. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16794. result.append(buf, static_cast<size_t>(n));
  16795. }
  16796. return result;
  16797. }
  16798. // Mock stream for unit tests
  16799. class MockStream : public Stream {
  16800. public:
  16801. std::string data;
  16802. size_t pos = 0;
  16803. ssize_t error_after = -1; // -1 = no error
  16804. explicit MockStream(const std::string &d, ssize_t err = -1)
  16805. : data(d), error_after(err) {}
  16806. bool is_readable() const override { return true; }
  16807. bool wait_readable() const override { return true; }
  16808. bool wait_writable() const override { return true; }
  16809. ssize_t read(char *ptr, size_t size) override {
  16810. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16811. if (pos >= data.size()) return 0;
  16812. size_t limit =
  16813. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16814. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16815. std::memcpy(ptr, data.data() + pos, to_read);
  16816. pos += to_read;
  16817. return static_cast<ssize_t>(to_read);
  16818. }
  16819. ssize_t write(const char *, size_t) override { return -1; }
  16820. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16821. ip = "127.0.0.1";
  16822. port = 0;
  16823. }
  16824. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16825. ip = "127.0.0.1";
  16826. port = 0;
  16827. }
  16828. socket_t socket() const override { return INVALID_SOCKET; }
  16829. time_t duration() const override { return 0; }
  16830. };
  16831. TEST(StreamHandleTest, Basic) {
  16832. ClientImpl::StreamHandle handle;
  16833. EXPECT_FALSE(handle.is_valid());
  16834. handle.response = detail::make_unique<Response>();
  16835. handle.error = Error::Connection;
  16836. EXPECT_FALSE(handle.is_valid());
  16837. handle.error = Error::Success;
  16838. EXPECT_TRUE(handle.is_valid());
  16839. }
  16840. TEST(BodyReaderTest, Basic) {
  16841. MockStream stream("Hello, World!");
  16842. detail::BodyReader reader;
  16843. reader.stream = &stream;
  16844. reader.content_length = 13;
  16845. char buf[32];
  16846. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16847. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16848. EXPECT_TRUE(reader.eof);
  16849. }
  16850. TEST(BodyReaderTest, NoStream) {
  16851. detail::BodyReader reader;
  16852. char buf[32];
  16853. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16854. EXPECT_EQ(Error::Connection, reader.last_error);
  16855. }
  16856. TEST(BodyReaderTest, Error) {
  16857. MockStream stream("Hello, World!", 5);
  16858. detail::BodyReader reader;
  16859. reader.stream = &stream;
  16860. reader.content_length = 13;
  16861. char buf[32];
  16862. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16863. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16864. EXPECT_EQ(Error::Read, reader.last_error);
  16865. }
  16866. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16867. // Mock-based StreamHandle tests relying on private internals are removed.
  16868. class OpenStreamTest : public ::testing::Test {
  16869. protected:
  16870. void SetUp() override {
  16871. svr_.Get("/hello", [](const Request &, Response &res) {
  16872. res.set_content("Hello World!", "text/plain");
  16873. });
  16874. svr_.Get("/large", [](const Request &, Response &res) {
  16875. res.set_content(std::string(10000, 'X'), "text/plain");
  16876. });
  16877. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16878. res.set_content("Hello World!", "image/jpeg");
  16879. res.set_header("Content-Encoding", "UTF-8");
  16880. });
  16881. svr_.Get("/chunked", [](const Request &, Response &res) {
  16882. res.set_chunked_content_provider("text/plain",
  16883. [](size_t offset, DataSink &sink) {
  16884. if (offset < 15) {
  16885. sink.write("chunk", 5);
  16886. return true;
  16887. }
  16888. sink.done();
  16889. return true;
  16890. });
  16891. });
  16892. svr_.Get("/compressible", [](const Request &, Response &res) {
  16893. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16894. DataSink &sink) {
  16895. if (offset < 100 * 1024) {
  16896. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16897. sink.write(chunk.data(), chunk.size());
  16898. return true;
  16899. }
  16900. sink.done();
  16901. return true;
  16902. });
  16903. });
  16904. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16905. [](const Request & /*req*/, Response &res) {
  16906. auto i = new int(0);
  16907. res.set_header("Trailer", "Content-Length, X-Allowed");
  16908. res.set_chunked_content_provider(
  16909. "text/plain",
  16910. [i](size_t /*offset*/, DataSink &sink) {
  16911. switch (*i) {
  16912. case 0: sink.os << "123"; break;
  16913. case 1: sink.os << "456"; break;
  16914. case 2: sink.os << "789"; break;
  16915. case 3: {
  16916. sink.done_with_trailer(
  16917. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16918. } break;
  16919. }
  16920. (*i)++;
  16921. return true;
  16922. },
  16923. [i](bool success) {
  16924. EXPECT_TRUE(success);
  16925. delete i;
  16926. });
  16927. });
  16928. // Echo headers endpoint for header-related tests
  16929. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16930. std::string body;
  16931. for (const auto &h : req.headers) {
  16932. body.append(h.first);
  16933. body.push_back(':');
  16934. body.append(h.second);
  16935. body.push_back('\n');
  16936. }
  16937. res.set_content(body, "text/plain");
  16938. });
  16939. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16940. std::string body;
  16941. for (const auto &h : req.headers) {
  16942. body.append(h.first);
  16943. body.push_back(':');
  16944. body.append(h.second);
  16945. body.push_back('\n');
  16946. }
  16947. res.set_content(body, "text/plain");
  16948. });
  16949. port_ = svr_.bind_to_any_port("127.0.0.1");
  16950. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16951. svr_.wait_until_ready();
  16952. }
  16953. void TearDown() override {
  16954. svr_.stop();
  16955. if (thread_.joinable()) thread_.join();
  16956. }
  16957. Server svr_;
  16958. std::thread thread_;
  16959. int port_ = 0;
  16960. };
  16961. TEST_F(OpenStreamTest, Basic) {
  16962. Client cli("127.0.0.1", port_);
  16963. auto handle = cli.open_stream("GET", "/hello");
  16964. EXPECT_TRUE(handle.is_valid());
  16965. EXPECT_EQ("Hello World!", read_all(handle));
  16966. }
  16967. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16968. Client cli("127.0.0.1", port_);
  16969. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16970. ASSERT_TRUE(handle.is_valid());
  16971. EXPECT_EQ("Hello World!", read_all(handle));
  16972. }
  16973. TEST_F(OpenStreamTest, SmallBuffer) {
  16974. Client cli("127.0.0.1", port_);
  16975. auto handle = cli.open_stream("GET", "/hello");
  16976. std::string result;
  16977. char buf[4];
  16978. ssize_t n;
  16979. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16980. result.append(buf, static_cast<size_t>(n));
  16981. EXPECT_EQ("Hello World!", result);
  16982. }
  16983. TEST_F(OpenStreamTest, DefaultHeaders) {
  16984. Client cli("127.0.0.1", port_);
  16985. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16986. {
  16987. auto handle = cli.open_stream("GET", "/echo-headers");
  16988. ASSERT_TRUE(handle.is_valid());
  16989. auto body = read_all(handle);
  16990. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16991. std::string::npos);
  16992. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16993. std::string::npos);
  16994. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16995. }
  16996. // open_stream POST with body and no explicit content_type should NOT add
  16997. // text/plain Content-Type (behavior differs from non-streaming path), but
  16998. // should include Content-Length
  16999. {
  17000. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17001. ASSERT_TRUE(handle.is_valid());
  17002. auto body = read_all(handle);
  17003. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17004. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17005. }
  17006. // open_stream POST with explicit Content-Type should preserve it
  17007. {
  17008. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17009. {{"Content-Type", "application/custom"}},
  17010. "{}", "application/custom");
  17011. ASSERT_TRUE(handle.is_valid());
  17012. auto body = read_all(handle);
  17013. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17014. }
  17015. // User-specified User-Agent must not be overwritten for stream API
  17016. {
  17017. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17018. {{"User-Agent", "MyAgent/1.2"}});
  17019. ASSERT_TRUE(handle.is_valid());
  17020. auto body = read_all(handle);
  17021. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17022. }
  17023. }
  17024. TEST_F(OpenStreamTest, Large) {
  17025. Client cli("127.0.0.1", port_);
  17026. auto handle = cli.open_stream("GET", "/large");
  17027. EXPECT_EQ(10000u, read_all(handle).size());
  17028. }
  17029. TEST_F(OpenStreamTest, ConnectionError) {
  17030. Client cli("127.0.0.1", 9999);
  17031. auto handle = cli.open_stream("GET", "/hello");
  17032. EXPECT_FALSE(handle.is_valid());
  17033. }
  17034. TEST_F(OpenStreamTest, Chunked) {
  17035. Client cli("127.0.0.1", port_);
  17036. auto handle = cli.open_stream("GET", "/chunked");
  17037. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17038. "Transfer-Encoding") == "chunked");
  17039. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17040. }
  17041. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17042. Client cli("127.0.0.1", port_);
  17043. auto handle =
  17044. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17045. ASSERT_TRUE(handle.is_valid());
  17046. // Consume body to allow trailers to be received/parsed
  17047. auto body = read_all(handle);
  17048. // Explicitly parse trailers (ensure trailers are available for assertion)
  17049. handle.parse_trailers_if_needed();
  17050. EXPECT_EQ(std::string("123456789"), body);
  17051. // The response should include a Trailer header declaring both names
  17052. ASSERT_TRUE(handle.response);
  17053. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17054. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17055. handle.response->get_header_value("Trailer"));
  17056. // Prohibited trailer must not be present
  17057. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17058. // Allowed trailer should be present
  17059. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17060. EXPECT_EQ(std::string("yes"),
  17061. handle.response->get_trailer_value("X-Allowed"));
  17062. // Verify trailers are NOT present as regular headers
  17063. EXPECT_EQ(std::string(""),
  17064. handle.response->get_header_value("Content-Length"));
  17065. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17066. }
  17067. static std::thread serve_single_response(std::promise<int> &port_promise,
  17068. const std::string &response) {
  17069. return std::thread([&port_promise, response] {
  17070. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17071. default_socket_options(srv);
  17072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17074. sockaddr_in addr{};
  17075. addr.sin_family = AF_INET;
  17076. addr.sin_port = htons(0); // Let OS assign a free port
  17077. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17078. int opt = 1;
  17079. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17080. #ifdef _WIN32
  17081. reinterpret_cast<const char *>(&opt),
  17082. #else
  17083. &opt,
  17084. #endif
  17085. sizeof(opt));
  17086. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17087. ::listen(srv, 1) != 0) {
  17088. port_promise.set_value(-1);
  17089. detail::close_socket(srv);
  17090. return;
  17091. }
  17092. socklen_t addr_len = sizeof(addr);
  17093. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17094. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17095. sockaddr_in cli_addr{};
  17096. socklen_t cli_len = sizeof(cli_addr);
  17097. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17098. if (cli != INVALID_SOCKET) {
  17099. // Read the complete HTTP request (until the blank line that terminates
  17100. // headers) before sending the response. If the server closes the socket
  17101. // while the client's request data is still unread in the kernel receive
  17102. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17103. // connection on both sides: it discards the client's receive buffer
  17104. // (which already holds our response) and causes any in-progress write on
  17105. // the client to fail with ECONNRESET. Reading all request data first
  17106. // ensures close() emits a graceful FIN.
  17107. {
  17108. char rbuf[256];
  17109. std::string req;
  17110. while (req.find("\r\n\r\n") == std::string::npos) {
  17111. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17112. if (n <= 0) { break; }
  17113. req.append(rbuf, static_cast<size_t>(n));
  17114. }
  17115. }
  17116. ::send(cli,
  17117. #ifdef _WIN32
  17118. static_cast<const char *>(response.c_str()),
  17119. static_cast<int>(response.size()),
  17120. #else
  17121. response.c_str(), response.size(),
  17122. #endif
  17123. 0);
  17124. detail::close_socket(cli);
  17125. }
  17126. detail::close_socket(srv);
  17127. });
  17128. }
  17129. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17130. #ifndef _WIN32
  17131. signal(SIGPIPE, SIG_IGN);
  17132. #endif
  17133. std::promise<int> port_promise;
  17134. auto port_future = port_promise.get_future();
  17135. auto server_thread =
  17136. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17137. "Content-Type: text/plain\r\n"
  17138. "Content-Length: not-a-number\r\n"
  17139. "Connection: close\r\n"
  17140. "\r\n"
  17141. "hello");
  17142. auto port = port_future.get();
  17143. ASSERT_GT(port, 0);
  17144. Client cli("127.0.0.1", port);
  17145. auto handle = cli.open_stream("GET", "/");
  17146. EXPECT_FALSE(handle.is_valid());
  17147. server_thread.join();
  17148. }
  17149. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17150. #ifndef _WIN32
  17151. signal(SIGPIPE, SIG_IGN);
  17152. #endif
  17153. std::promise<int> port_promise;
  17154. auto port_future = port_promise.get_future();
  17155. auto server_thread = serve_single_response(
  17156. port_promise, "HTTP/1.1 200 OK\r\n"
  17157. "Content-Type: text/plain\r\n"
  17158. "Content-Length: 99999999999999999999999999\r\n"
  17159. "Connection: close\r\n"
  17160. "\r\n"
  17161. "hello");
  17162. auto port = port_future.get();
  17163. ASSERT_GT(port, 0);
  17164. // Historically std::stoull would throw std::out_of_range here and crash
  17165. // the process, then parsing silently clamped to a bogus framing length and
  17166. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17167. // so the stream fails to open, matching the not-a-number case above. The
  17168. // process still must NOT terminate.
  17169. Client cli("127.0.0.1", port);
  17170. auto handle = cli.open_stream("GET", "/");
  17171. EXPECT_FALSE(handle.is_valid());
  17172. server_thread.join();
  17173. }
  17174. // Serves `response` to the single request `fn` makes with a fresh client.
  17175. template <typename Fn>
  17176. static void with_single_response(const std::string &response, Fn fn) {
  17177. #ifndef _WIN32
  17178. signal(SIGPIPE, SIG_IGN);
  17179. #endif
  17180. std::promise<int> port_promise;
  17181. auto port_future = port_promise.get_future();
  17182. auto server_thread = serve_single_response(port_promise, response);
  17183. auto se = detail::scope_exit([&] { server_thread.join(); });
  17184. auto port = port_future.get();
  17185. ASSERT_GT(port, 0);
  17186. Client cli("127.0.0.1", port);
  17187. fn(cli);
  17188. }
  17189. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17190. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17191. // the chunked coding and drop Content-Length, so a front-end that trusts
  17192. // Content-Length would disagree about where the body ends (response
  17193. // smuggling). The client must reject such a response.
  17194. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17195. for (const char *te : {"chunked", "gzip, chunked"}) {
  17196. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17197. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17198. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17199. "5\r\nhello\r\n0\r\n\r\n";
  17200. with_single_response(response, [&](Client &cli) {
  17201. auto res = cli.Get("/");
  17202. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17203. EXPECT_EQ(Error::Read, res.error()) << te;
  17204. });
  17205. with_single_response(response, [&](Client &cli) {
  17206. auto handle = cli.open_stream("GET", "/");
  17207. EXPECT_FALSE(handle.is_valid()) << te;
  17208. EXPECT_EQ(Error::Read, handle.error) << te;
  17209. });
  17210. }
  17211. }
  17212. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17213. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17214. // closing the connection (unlike a request, which must be rejected).
  17215. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17216. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17217. "Transfer-Encoding: chunked\r\n"
  17218. "Connection: close\r\n"
  17219. "\r\n"
  17220. "5\r\nhello\r\n0\r\n\r\n",
  17221. "HTTP/1.1 200 OK\r\n"
  17222. "Transfer-Encoding: gzip\r\n"
  17223. "Connection: close\r\n"
  17224. "\r\n"
  17225. "hello"}) {
  17226. with_single_response(response, [&](Client &cli) {
  17227. auto res = cli.Get("/");
  17228. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17229. EXPECT_EQ("hello", res->body);
  17230. });
  17231. with_single_response(response, [&](Client &cli) {
  17232. auto handle = cli.open_stream("GET", "/");
  17233. ASSERT_TRUE(handle.is_valid()) << response;
  17234. EXPECT_EQ("hello", read_all(handle));
  17235. });
  17236. }
  17237. }
  17238. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17239. // framing headers describe nothing to read and must not be rejected.
  17240. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17241. const std::string framing = "Content-Length: 5\r\n"
  17242. "Transfer-Encoding: chunked\r\n"
  17243. "Connection: close\r\n"
  17244. "\r\n";
  17245. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17246. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17247. });
  17248. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17249. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17250. });
  17251. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17252. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17253. with_single_response(response, [&](Client &cli) {
  17254. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17255. });
  17256. with_single_response(response, [&](Client &cli) {
  17257. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17258. });
  17259. }
  17260. }
  17261. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17262. TEST_F(OpenStreamTest, Gzip) {
  17263. Client cli("127.0.0.1", port_);
  17264. auto handle = cli.open_stream("GET", "/compressible", {},
  17265. {{"Accept-Encoding", "gzip"}});
  17266. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17267. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17268. }
  17269. #endif
  17270. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17271. TEST_F(OpenStreamTest, Brotli) {
  17272. Client cli("127.0.0.1", port_);
  17273. auto handle =
  17274. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17275. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17276. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17277. }
  17278. #endif
  17279. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17280. TEST_F(OpenStreamTest, Zstd) {
  17281. Client cli("127.0.0.1", port_);
  17282. auto handle = cli.open_stream("GET", "/compressible", {},
  17283. {{"Accept-Encoding", "zstd"}});
  17284. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17285. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17286. }
  17287. #endif
  17288. #ifdef CPPHTTPLIB_SSL_ENABLED
  17289. class SSLOpenStreamTest : public ::testing::Test {
  17290. protected:
  17291. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17292. void SetUp() override {
  17293. svr_.Get("/hello", [](const Request &, Response &res) {
  17294. res.set_content("Hello SSL World!", "text/plain");
  17295. });
  17296. svr_.Get("/chunked", [](const Request &, Response &res) {
  17297. res.set_chunked_content_provider("text/plain",
  17298. [](size_t offset, DataSink &sink) {
  17299. if (offset < 15) {
  17300. sink.write("chunk", 5);
  17301. return true;
  17302. }
  17303. sink.done();
  17304. return true;
  17305. });
  17306. });
  17307. svr_.Post("/echo", [](const Request &req, Response &res) {
  17308. res.set_content(req.body, req.get_header_value("Content-Type"));
  17309. });
  17310. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17311. std::string body = req.body;
  17312. res.set_chunked_content_provider(
  17313. "text/plain", [body](size_t offset, DataSink &sink) {
  17314. if (offset < body.size()) {
  17315. sink.write(body.data() + offset, body.size() - offset);
  17316. }
  17317. sink.done();
  17318. return true;
  17319. });
  17320. });
  17321. port_ = svr_.bind_to_any_port("127.0.0.1");
  17322. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17323. svr_.wait_until_ready();
  17324. }
  17325. void TearDown() override {
  17326. svr_.stop();
  17327. if (thread_.joinable()) thread_.join();
  17328. }
  17329. SSLServer svr_;
  17330. std::thread thread_;
  17331. int port_ = 0;
  17332. };
  17333. TEST_F(SSLOpenStreamTest, Basic) {
  17334. SSLClient cli("127.0.0.1", port_);
  17335. cli.enable_server_certificate_verification(false);
  17336. auto handle = cli.open_stream("GET", "/hello");
  17337. ASSERT_TRUE(handle.is_valid());
  17338. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17339. }
  17340. TEST_F(SSLOpenStreamTest, Chunked) {
  17341. SSLClient cli("127.0.0.1", port_);
  17342. cli.enable_server_certificate_verification(false);
  17343. auto handle = cli.open_stream("GET", "/chunked");
  17344. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17345. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17346. "Transfer-Encoding") == "chunked");
  17347. auto body = read_all(handle);
  17348. EXPECT_EQ("chunkchunkchunk", body);
  17349. }
  17350. TEST_F(SSLOpenStreamTest, Post) {
  17351. SSLClient cli("127.0.0.1", port_);
  17352. cli.enable_server_certificate_verification(false);
  17353. auto handle =
  17354. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17355. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17356. EXPECT_EQ(200, handle.response->status);
  17357. auto body = read_all(handle);
  17358. EXPECT_EQ("Hello SSL POST", body);
  17359. }
  17360. TEST_F(SSLOpenStreamTest, PostChunked) {
  17361. SSLClient cli("127.0.0.1", port_);
  17362. cli.enable_server_certificate_verification(false);
  17363. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17364. "Chunked SSL Data", "text/plain");
  17365. ASSERT_TRUE(handle.is_valid());
  17366. EXPECT_EQ(200, handle.response->status);
  17367. auto body = read_all(handle);
  17368. EXPECT_EQ("Chunked SSL Data", body);
  17369. }
  17370. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17371. // Content-Length is terminated by the server closing the connection. When the
  17372. // SSL peer sends a close_notify after the body, the client must treat it as a
  17373. // clean EOF and return a successful response rather than an error.
  17374. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17376. ASSERT_TRUE(svr.is_valid());
  17377. svr.set_keep_alive_max_count(1);
  17378. const std::string expected_body = "Hello from connection-close response!";
  17379. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17380. res.set_content_provider("text/plain",
  17381. [&](size_t offset, DataSink &sink) -> bool {
  17382. if (offset < expected_body.size()) {
  17383. sink.write(expected_body.data() + offset,
  17384. expected_body.size() - offset);
  17385. }
  17386. sink.done();
  17387. return true;
  17388. });
  17389. });
  17390. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. listen_thread.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. SSLClient cli(HOST, PORT);
  17398. cli.enable_server_certificate_verification(false);
  17399. auto res = cli.Get("/no-content-length");
  17400. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17401. EXPECT_EQ(StatusCode::OK_200, res->status);
  17402. EXPECT_EQ(expected_body, res->body);
  17403. }
  17404. #endif // CPPHTTPLIB_SSL_ENABLED
  17405. //==============================================================================
  17406. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17407. // results for various scenarios.
  17408. //==============================================================================
  17409. TEST(ParityTest, GetVsOpenStream) {
  17410. Server svr;
  17411. const std::string path = "/parity";
  17412. const std::string content = "Parity test content: hello world";
  17413. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17414. res.set_content(content, "text/plain");
  17415. });
  17416. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. });
  17422. svr.wait_until_ready();
  17423. Client cli(HOST, PORT);
  17424. // Non-stream path
  17425. auto r1 = cli.Get(path);
  17426. ASSERT_TRUE(r1);
  17427. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17428. // Stream path
  17429. auto h = cli.open_stream("GET", path);
  17430. ASSERT_TRUE(h.is_valid());
  17431. EXPECT_EQ(r1->body, read_all(h));
  17432. }
  17433. // Helper to compress data with provided compressor type T
  17434. template <typename Compressor>
  17435. static std::string compress_payload_for_parity(const std::string &in) {
  17436. std::string out;
  17437. Compressor compressor;
  17438. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17439. [&](const char *data, size_t n) {
  17440. out.append(data, n);
  17441. return true;
  17442. });
  17443. EXPECT_TRUE(ok);
  17444. return out;
  17445. }
  17446. // Helper function for compression parity tests
  17447. template <typename Compressor>
  17448. static void test_compression_parity(const std::string &original,
  17449. const std::string &path,
  17450. const std::string &encoding) {
  17451. const std::string compressed =
  17452. compress_payload_for_parity<Compressor>(original);
  17453. Server svr;
  17454. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17455. res.set_content(compressed, "application/octet-stream");
  17456. res.set_header("Content-Encoding", encoding);
  17457. });
  17458. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17459. auto se = detail::scope_exit([&] {
  17460. svr.stop();
  17461. t.join();
  17462. ASSERT_FALSE(svr.is_running());
  17463. });
  17464. svr.wait_until_ready();
  17465. Client cli(HOST, PORT);
  17466. // Non-streaming
  17467. {
  17468. auto res = cli.Get(path);
  17469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17470. EXPECT_EQ(StatusCode::OK_200, res->status);
  17471. EXPECT_EQ(original, res->body);
  17472. }
  17473. // Streaming
  17474. {
  17475. auto h = cli.open_stream("GET", path);
  17476. ASSERT_TRUE(h.is_valid());
  17477. EXPECT_EQ(original, read_all(h));
  17478. }
  17479. }
  17480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17481. TEST(ParityTest, Gzip) {
  17482. test_compression_parity<detail::gzip_compressor>(
  17483. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17484. }
  17485. #endif
  17486. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17487. TEST(ParityTest, Brotli) {
  17488. test_compression_parity<detail::brotli_compressor>(
  17489. "Hello, brotli parity test payload", "/parity-br", "br");
  17490. }
  17491. #endif
  17492. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17493. TEST(ParityTest, Zstd) {
  17494. test_compression_parity<detail::zstd_compressor>(
  17495. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17496. }
  17497. #endif
  17498. //==============================================================================
  17499. // New Stream API Tests
  17500. //==============================================================================
  17501. inline std::string read_body(httplib::stream::Result &result) {
  17502. std::string body;
  17503. while (result.next()) {
  17504. body.append(result.data(), result.size());
  17505. }
  17506. return body;
  17507. }
  17508. TEST(ClientConnectionTest, Basic) {
  17509. httplib::ClientConnection conn;
  17510. EXPECT_FALSE(conn.is_open());
  17511. conn.sock = 1;
  17512. EXPECT_TRUE(conn.is_open());
  17513. httplib::ClientConnection conn2(std::move(conn));
  17514. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17515. conn2.sock = INVALID_SOCKET;
  17516. }
  17517. // Unified test server for all stream::* tests
  17518. class StreamApiTest : public ::testing::Test {
  17519. protected:
  17520. void SetUp() override {
  17521. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17522. res.set_content("Hello World!", "text/plain");
  17523. });
  17524. svr_.Get("/echo-params",
  17525. [](const httplib::Request &req, httplib::Response &res) {
  17526. std::string r;
  17527. for (const auto &p : req.params) {
  17528. if (!r.empty()) r += "&";
  17529. r += p.first + "=" + p.second;
  17530. }
  17531. res.set_content(r, "text/plain");
  17532. });
  17533. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17534. res.set_content(req.body, req.get_header_value("Content-Type"));
  17535. });
  17536. svr_.Post("/echo-headers",
  17537. [](const httplib::Request &req, httplib::Response &res) {
  17538. std::string r;
  17539. for (const auto &h : req.headers)
  17540. r += h.first + ": " + h.second + "\n";
  17541. res.set_content(r, "text/plain");
  17542. });
  17543. svr_.Post("/echo-params",
  17544. [](const httplib::Request &req, httplib::Response &res) {
  17545. std::string r = "params:";
  17546. for (const auto &p : req.params)
  17547. r += p.first + "=" + p.second + ";";
  17548. res.set_content(r + " body:" + req.body, "text/plain");
  17549. });
  17550. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17551. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17552. });
  17553. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17554. res.set_content("PUT:" + req.body, "text/plain");
  17555. });
  17556. svr_.Patch("/echo",
  17557. [](const httplib::Request &req, httplib::Response &res) {
  17558. res.set_content("PATCH:" + req.body, "text/plain");
  17559. });
  17560. svr_.Delete(
  17561. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17562. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17563. "text/plain");
  17564. });
  17565. svr_.Get("/head-test",
  17566. [](const httplib::Request &, httplib::Response &res) {
  17567. res.set_content("body for HEAD", "text/plain");
  17568. });
  17569. svr_.Options("/options",
  17570. [](const httplib::Request &, httplib::Response &res) {
  17571. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17572. });
  17573. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17574. svr_.wait_until_ready();
  17575. }
  17576. void TearDown() override {
  17577. svr_.stop();
  17578. if (thread_.joinable()) thread_.join();
  17579. }
  17580. httplib::Server svr_;
  17581. std::thread thread_;
  17582. };
  17583. // stream::Get tests
  17584. TEST_F(StreamApiTest, GetBasic) {
  17585. httplib::Client cli(HOST, PORT);
  17586. auto result = httplib::stream::Get(cli, "/hello");
  17587. ASSERT_TRUE(result.is_valid());
  17588. EXPECT_EQ(200, result.status());
  17589. EXPECT_EQ("Hello World!", read_body(result));
  17590. }
  17591. TEST_F(StreamApiTest, GetWithParams) {
  17592. httplib::Client cli(HOST, PORT);
  17593. httplib::Params params{{"foo", "bar"}};
  17594. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17595. ASSERT_TRUE(result.is_valid());
  17596. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17597. }
  17598. TEST_F(StreamApiTest, GetConnectionError) {
  17599. httplib::Client cli(HOST, 9999);
  17600. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17601. }
  17602. TEST_F(StreamApiTest, Get404) {
  17603. httplib::Client cli(HOST, PORT);
  17604. auto result = httplib::stream::Get(cli, "/nonexistent");
  17605. EXPECT_TRUE(result.is_valid());
  17606. EXPECT_EQ(404, result.status());
  17607. }
  17608. // stream::Post tests
  17609. TEST_F(StreamApiTest, PostBasic) {
  17610. httplib::Client cli(HOST, PORT);
  17611. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17612. "application/json");
  17613. ASSERT_TRUE(result.is_valid());
  17614. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17615. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17616. }
  17617. TEST_F(StreamApiTest, PostWithHeaders) {
  17618. httplib::Client cli(HOST, PORT);
  17619. httplib::Headers headers{{"X-Custom", "value"}};
  17620. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17621. "text/plain");
  17622. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17623. }
  17624. TEST_F(StreamApiTest, PostWithParams) {
  17625. httplib::Client cli(HOST, PORT);
  17626. httplib::Params params{{"k", "v"}};
  17627. auto result =
  17628. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17629. auto body = read_body(result);
  17630. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17631. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17632. }
  17633. TEST_F(StreamApiTest, PostLarge) {
  17634. httplib::Client cli(HOST, PORT);
  17635. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17636. size_t total = 0;
  17637. while (result.next()) {
  17638. total += result.size();
  17639. }
  17640. EXPECT_EQ(100u * 1024u, total);
  17641. }
  17642. // stream::Put/Patch tests
  17643. TEST_F(StreamApiTest, PutAndPatch) {
  17644. httplib::Client cli(HOST, PORT);
  17645. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17646. EXPECT_EQ("PUT:test", read_body(put));
  17647. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17648. EXPECT_EQ("PATCH:test", read_body(patch));
  17649. }
  17650. // stream::Delete tests
  17651. TEST_F(StreamApiTest, Delete) {
  17652. httplib::Client cli(HOST, PORT);
  17653. auto del1 = httplib::stream::Delete(cli, "/resource");
  17654. EXPECT_EQ("Deleted", read_body(del1));
  17655. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17656. EXPECT_EQ("Deleted:data", read_body(del2));
  17657. }
  17658. // stream::Head/Options tests
  17659. TEST_F(StreamApiTest, HeadAndOptions) {
  17660. httplib::Client cli(HOST, PORT);
  17661. auto head = httplib::stream::Head(cli, "/head-test");
  17662. EXPECT_TRUE(head.is_valid());
  17663. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17664. auto opts = httplib::stream::Options(cli, "/options");
  17665. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17666. }
  17667. // SSL stream::* tests
  17668. #ifdef CPPHTTPLIB_SSL_ENABLED
  17669. class SSLStreamApiTest : public ::testing::Test {
  17670. protected:
  17671. void SetUp() override {
  17672. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17673. res.set_content("Hello SSL!", "text/plain");
  17674. });
  17675. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17676. res.set_content(req.body, "text/plain");
  17677. });
  17678. port_ = svr_.bind_to_any_port("127.0.0.1");
  17679. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17680. svr_.wait_until_ready();
  17681. }
  17682. void TearDown() override {
  17683. svr_.stop();
  17684. if (thread_.joinable()) thread_.join();
  17685. }
  17686. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17687. std::thread thread_;
  17688. int port_ = 0;
  17689. };
  17690. TEST_F(SSLStreamApiTest, GetAndPost) {
  17691. httplib::SSLClient cli("127.0.0.1", port_);
  17692. cli.enable_server_certificate_verification(false);
  17693. auto get = httplib::stream::Get(cli, "/hello");
  17694. EXPECT_EQ("Hello SSL!", read_body(get));
  17695. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17696. EXPECT_EQ("test", read_body(post));
  17697. }
  17698. #endif
  17699. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17700. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17701. // BodyReader
  17702. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17703. // Test that read timeout during streaming is detected
  17704. // Use a large content-length response where server delays mid-stream
  17705. Server svr;
  17706. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17707. // Send a large response with delay in the middle
  17708. res.set_content_provider(
  17709. 1000, // content_length
  17710. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17711. if (offset < 100) {
  17712. // Send first 100 bytes immediately
  17713. std::string data(100, 'A');
  17714. sink.write(data.c_str(), data.size());
  17715. return true;
  17716. }
  17717. // Then delay longer than client timeout
  17718. std::this_thread::sleep_for(std::chrono::seconds(3));
  17719. std::string data(900, 'B');
  17720. sink.write(data.c_str(), data.size());
  17721. return true;
  17722. });
  17723. });
  17724. auto port = 8091;
  17725. std::thread t([&]() { svr.listen("localhost", port); });
  17726. svr.wait_until_ready();
  17727. Client cli("localhost", port);
  17728. cli.set_read_timeout(1, 0); // 1 second timeout
  17729. auto handle = cli.open_stream("GET", "/slow-stream");
  17730. ASSERT_TRUE(handle.is_valid());
  17731. char buf[256];
  17732. ssize_t total = 0;
  17733. ssize_t n;
  17734. bool got_error = false;
  17735. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17736. total += n;
  17737. }
  17738. if (n < 0) {
  17739. got_error = true;
  17740. // Should be timeout or read error
  17741. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17742. handle.get_read_error() == Error::Read)
  17743. << "Actual error: " << to_string(handle.get_read_error());
  17744. }
  17745. // Either we got an error, or we got less data than expected
  17746. EXPECT_TRUE(got_error || total < 1000)
  17747. << "Expected timeout but got all " << total << " bytes";
  17748. svr.stop();
  17749. t.join();
  17750. }
  17751. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17752. // Test connection closed detection via BodyReader
  17753. Server svr;
  17754. std::atomic<bool> close_now{false};
  17755. svr.Get("/will-close", [&](const Request &, Response &res) {
  17756. res.set_content_provider(
  17757. 10000, // Large content_length that we won't fully send
  17758. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17759. if (offset < 100) {
  17760. std::string data(100, 'X');
  17761. sink.write(data.c_str(), data.size());
  17762. return true;
  17763. }
  17764. // Wait for signal then abort
  17765. while (!close_now) {
  17766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17767. }
  17768. return false; // Abort - server will close connection
  17769. });
  17770. });
  17771. auto port = 8092;
  17772. std::thread t([&]() { svr.listen("localhost", port); });
  17773. svr.wait_until_ready();
  17774. Client cli("localhost", port);
  17775. auto handle = cli.open_stream("GET", "/will-close");
  17776. ASSERT_TRUE(handle.is_valid());
  17777. char buf[256];
  17778. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17779. EXPECT_GT(n, 0) << "First read should succeed";
  17780. // Signal server to close
  17781. close_now = true;
  17782. // Keep reading until error or EOF
  17783. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17784. // Keep reading
  17785. }
  17786. // Should get an error since content_length wasn't satisfied
  17787. if (n < 0) {
  17788. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17789. handle.get_read_error() == Error::Read)
  17790. << "Actual error: " << to_string(handle.get_read_error());
  17791. }
  17792. svr.stop();
  17793. t.join();
  17794. }
  17795. #ifdef CPPHTTPLIB_SSL_ENABLED
  17796. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17797. // Test that read timeout during SSL streaming is detected
  17798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17799. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17800. res.set_content_provider(
  17801. 1000, "text/plain",
  17802. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17803. if (offset < 100) {
  17804. std::string data(100, 'A');
  17805. sink.write(data.c_str(), data.size());
  17806. return true;
  17807. }
  17808. std::this_thread::sleep_for(std::chrono::seconds(3));
  17809. std::string data(900, 'B');
  17810. sink.write(data.c_str(), data.size());
  17811. return true;
  17812. });
  17813. });
  17814. auto port = 8093;
  17815. std::thread t([&]() { svr.listen("localhost", port); });
  17816. svr.wait_until_ready();
  17817. SSLClient cli("localhost", port);
  17818. cli.enable_server_certificate_verification(false);
  17819. cli.set_read_timeout(1, 0); // 1 second timeout
  17820. auto handle = cli.open_stream("GET", "/slow-stream");
  17821. ASSERT_TRUE(handle.is_valid());
  17822. char buf[256];
  17823. ssize_t total = 0;
  17824. ssize_t n;
  17825. bool got_error = false;
  17826. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17827. total += n;
  17828. }
  17829. if (n < 0) {
  17830. got_error = true;
  17831. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17832. handle.get_read_error() == Error::Read)
  17833. << "Actual error: " << to_string(handle.get_read_error());
  17834. }
  17835. EXPECT_TRUE(got_error || total < 1000)
  17836. << "Expected timeout but got all " << total << " bytes";
  17837. svr.stop();
  17838. t.join();
  17839. }
  17840. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17841. // Test SSL connection closed detection
  17842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17843. std::atomic<bool> close_now{false};
  17844. svr.Get("/will-close", [&](const Request &, Response &res) {
  17845. res.set_content_provider(
  17846. 10000, "text/plain",
  17847. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17848. if (offset < 100) {
  17849. std::string data(100, 'X');
  17850. sink.write(data.c_str(), data.size());
  17851. return true;
  17852. }
  17853. while (!close_now) {
  17854. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17855. }
  17856. return false;
  17857. });
  17858. });
  17859. auto port = 8094;
  17860. std::thread t([&]() { svr.listen("localhost", port); });
  17861. svr.wait_until_ready();
  17862. SSLClient cli("localhost", port);
  17863. cli.enable_server_certificate_verification(false);
  17864. auto handle = cli.open_stream("GET", "/will-close");
  17865. ASSERT_TRUE(handle.is_valid());
  17866. char buf[256];
  17867. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17868. EXPECT_GT(n, 0);
  17869. // Signal server to close
  17870. close_now = true;
  17871. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17872. // Keep reading
  17873. }
  17874. if (n < 0) {
  17875. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17876. handle.get_read_error() == Error::Read)
  17877. << "Actual error: " << to_string(handle.get_read_error());
  17878. }
  17879. svr.stop();
  17880. t.join();
  17881. }
  17882. #endif
  17883. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17884. using namespace httplib;
  17885. // Create a test file
  17886. const char *fname = "etag_testfile.txt";
  17887. const char *content = "etag-content";
  17888. {
  17889. std::ofstream ofs(fname);
  17890. ofs << content;
  17891. ASSERT_TRUE(ofs.good());
  17892. }
  17893. Server svr;
  17894. svr.set_mount_point("/static", ".");
  17895. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17896. svr.wait_until_ready();
  17897. Client cli(HOST, PORT);
  17898. // First request: should get 200 with ETag header
  17899. auto res1 = cli.Get("/static/etag_testfile.txt");
  17900. ASSERT_TRUE(res1);
  17901. ASSERT_EQ(200, res1->status);
  17902. ASSERT_TRUE(res1->has_header("ETag"));
  17903. std::string etag = res1->get_header_value("ETag");
  17904. EXPECT_FALSE(etag.empty());
  17905. // Verify ETag format: W/"hex-hex"
  17906. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17907. EXPECT_EQ('W', etag[0]);
  17908. EXPECT_EQ('/', etag[1]);
  17909. EXPECT_EQ('"', etag[2]);
  17910. EXPECT_EQ('"', etag.back());
  17911. // Exact match: expect 304 Not Modified
  17912. Headers h2 = {{"If-None-Match", etag}};
  17913. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17914. ASSERT_TRUE(res2);
  17915. EXPECT_EQ(304, res2->status);
  17916. // Wildcard match: expect 304 Not Modified
  17917. Headers h3 = {{"If-None-Match", "*"}};
  17918. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17919. ASSERT_TRUE(res3);
  17920. EXPECT_EQ(304, res3->status);
  17921. // Non-matching ETag: expect 200
  17922. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17923. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17924. ASSERT_TRUE(res4);
  17925. EXPECT_EQ(200, res4->status);
  17926. // Multiple ETags with one matching: expect 304
  17927. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17928. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17929. ASSERT_TRUE(res5);
  17930. EXPECT_EQ(304, res5->status);
  17931. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17932. // that equivalent to the single comma-separated list above, so the match on
  17933. // the second line must still be found.
  17934. Headers h6;
  17935. h6.emplace("If-None-Match", "W/\"other\"");
  17936. h6.emplace("If-None-Match", etag);
  17937. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17938. ASSERT_TRUE(res6);
  17939. EXPECT_EQ(304, res6->status);
  17940. svr.stop();
  17941. t.join();
  17942. std::remove(fname);
  17943. }
  17944. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17945. using namespace httplib;
  17946. Server svr;
  17947. svr.set_mount_point("/static", ".");
  17948. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17949. svr.wait_until_ready();
  17950. Client cli(HOST, PORT);
  17951. // Send If-None-Match: * to a non-existent file
  17952. Headers h = {{"If-None-Match", "*"}};
  17953. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17955. EXPECT_EQ(404, res->status);
  17956. svr.stop();
  17957. t.join();
  17958. }
  17959. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17960. using namespace httplib;
  17961. // Create a test file
  17962. const char *fname = "etag_boundary_testfile.txt";
  17963. const char *content = "boundary-test";
  17964. {
  17965. std::ofstream ofs(fname);
  17966. ofs << content;
  17967. ASSERT_TRUE(ofs.good());
  17968. }
  17969. Server svr;
  17970. svr.set_mount_point("/static", ".");
  17971. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17972. svr.wait_until_ready();
  17973. Client cli(HOST, PORT);
  17974. // Get the actual ETag
  17975. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17976. ASSERT_TRUE(res1);
  17977. ASSERT_EQ(200, res1->status);
  17978. ASSERT_TRUE(res1->has_header("ETag"));
  17979. std::string etag = res1->get_header_value("ETag");
  17980. // Test 1: Very long ETag value (longer than actual ETag)
  17981. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17982. Headers h1 = {{"If-None-Match", "W/"
  17983. "\"very-long-etag-value-that-is-much-longer-"
  17984. "than-the-actual-etag-value\""}};
  17985. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17986. ASSERT_TRUE(res2);
  17987. EXPECT_EQ(200, res2->status); // Should not match
  17988. // Test 2: Long string followed by wildcard
  17989. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17990. // string)
  17991. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17992. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17993. ASSERT_TRUE(res3);
  17994. EXPECT_EQ(304, res3->status); // Should match on "*"
  17995. // Test 3: Wildcard followed by long string
  17996. // Should match on "*" immediately and return 304
  17997. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17998. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17999. ASSERT_TRUE(res4);
  18000. EXPECT_EQ(304, res4->status); // Should match on "*"
  18001. // Test 4: Multiple long non-matching values
  18002. // Should NOT match and return 200 (test that all comparisons are safe)
  18003. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18004. "W/\"second-long-non-matching-value\", "
  18005. "W/\"third-long-non-matching-value\""}};
  18006. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18007. ASSERT_TRUE(res5);
  18008. EXPECT_EQ(200, res5->status); // Should not match
  18009. // Test 5: Single character that is not "*" (edge case)
  18010. Headers h5 = {{"If-None-Match", "X"}};
  18011. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18012. ASSERT_TRUE(res6);
  18013. EXPECT_EQ(200, res6->status); // Should not match
  18014. svr.stop();
  18015. t.join();
  18016. std::remove(fname);
  18017. }
  18018. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18019. using namespace httplib;
  18020. // Create a test file
  18021. const char *fname = "ims_testfile.txt";
  18022. const char *content = "if-modified-since-test";
  18023. {
  18024. std::ofstream ofs(fname);
  18025. ofs << content;
  18026. ASSERT_TRUE(ofs.good());
  18027. }
  18028. Server svr;
  18029. svr.set_mount_point("/static", ".");
  18030. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18031. svr.wait_until_ready();
  18032. Client cli(HOST, PORT);
  18033. // First request: should get 200 with Last-Modified header
  18034. auto res1 = cli.Get("/static/ims_testfile.txt");
  18035. ASSERT_TRUE(res1);
  18036. ASSERT_EQ(200, res1->status);
  18037. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18038. std::string last_modified = res1->get_header_value("Last-Modified");
  18039. EXPECT_FALSE(last_modified.empty());
  18040. // If-Modified-Since with same time: expect 304
  18041. Headers h2 = {{"If-Modified-Since", last_modified}};
  18042. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18043. ASSERT_TRUE(res2);
  18044. EXPECT_EQ(304, res2->status);
  18045. // If-Modified-Since with future time: expect 304
  18046. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18047. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18048. ASSERT_TRUE(res3);
  18049. EXPECT_EQ(304, res3->status);
  18050. // If-Modified-Since with past time: expect 200
  18051. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18052. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18053. ASSERT_TRUE(res4);
  18054. EXPECT_EQ(200, res4->status);
  18055. // If-None-Match takes precedence over If-Modified-Since
  18056. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18057. ASSERT_TRUE(res1->has_header("ETag"));
  18058. std::string etag = res1->get_header_value("ETag");
  18059. Headers h5 = {{"If-None-Match", etag},
  18060. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18061. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18062. ASSERT_TRUE(res5);
  18063. EXPECT_EQ(304, res5->status);
  18064. svr.stop();
  18065. t.join();
  18066. std::remove(fname);
  18067. }
  18068. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18069. using namespace httplib;
  18070. Server svr;
  18071. // Endpoint that returns compressible content
  18072. svr.Get("/compressible", [](const Request &, Response &res) {
  18073. // Return a large enough body to trigger compression
  18074. std::string body(1000, 'a');
  18075. res.set_content(body, "text/plain");
  18076. });
  18077. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18078. svr.wait_until_ready();
  18079. Client cli(HOST, PORT);
  18080. // Request with gzip support: should get Vary header when compressed
  18081. cli.set_compress(true);
  18082. auto res1 = cli.Get("/compressible");
  18083. ASSERT_TRUE(res1);
  18084. EXPECT_EQ(200, res1->status);
  18085. // If Content-Encoding is set, Vary should also be set
  18086. if (res1->has_header("Content-Encoding")) {
  18087. EXPECT_TRUE(res1->has_header("Vary"));
  18088. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18089. }
  18090. // Request without Accept-Encoding header: should not have compression
  18091. Headers h_no_compress;
  18092. auto res2 = cli.Get("/compressible", h_no_compress);
  18093. ASSERT_TRUE(res2);
  18094. EXPECT_EQ(200, res2->status);
  18095. // Verify Vary header is present when compression is applied
  18096. // (the exact behavior depends on server configuration)
  18097. svr.stop();
  18098. t.join();
  18099. }
  18100. TEST(ETagTest, IfRangeWithETag) {
  18101. using namespace httplib;
  18102. // Create a test file with known content
  18103. const char *fname = "if_range_testfile.txt";
  18104. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18105. {
  18106. std::ofstream ofs(fname);
  18107. ofs << content;
  18108. ASSERT_TRUE(ofs.good());
  18109. }
  18110. Server svr;
  18111. svr.set_mount_point("/static", ".");
  18112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18113. svr.wait_until_ready();
  18114. Client cli(HOST, PORT);
  18115. // First request: get ETag
  18116. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18117. ASSERT_TRUE(res1);
  18118. ASSERT_EQ(200, res1->status);
  18119. ASSERT_TRUE(res1->has_header("ETag"));
  18120. std::string etag = res1->get_header_value("ETag");
  18121. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18122. // Since our server generates weak ETags (W/"..."), If-Range with our
  18123. // ETag should NOT result in partial content - it should return full content.
  18124. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18125. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18126. ASSERT_TRUE(res2);
  18127. // Weak ETag in If-Range -> full content (200), not partial (206)
  18128. EXPECT_EQ(200, res2->status);
  18129. EXPECT_EQ(content, res2->body);
  18130. EXPECT_FALSE(res2->has_header("Content-Range"));
  18131. // Range request with non-matching If-Range (ETag): should get 200 (full
  18132. // content)
  18133. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18134. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18135. ASSERT_TRUE(res3);
  18136. EXPECT_EQ(200, res3->status);
  18137. EXPECT_EQ(content, res3->body);
  18138. EXPECT_FALSE(res3->has_header("Content-Range"));
  18139. // Range request with strong ETag (hypothetical - our server doesn't generate
  18140. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18141. // should return full content)
  18142. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18143. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18144. ASSERT_TRUE(res4);
  18145. EXPECT_EQ(200, res4->status);
  18146. EXPECT_EQ(content, res4->body);
  18147. EXPECT_FALSE(res4->has_header("Content-Range"));
  18148. svr.stop();
  18149. t.join();
  18150. std::remove(fname);
  18151. }
  18152. TEST(ETagTest, IfRangeWithDate) {
  18153. using namespace httplib;
  18154. // Create a test file
  18155. const char *fname = "if_range_date_testfile.txt";
  18156. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18157. {
  18158. std::ofstream ofs(fname);
  18159. ofs << content;
  18160. ASSERT_TRUE(ofs.good());
  18161. }
  18162. Server svr;
  18163. svr.set_mount_point("/static", ".");
  18164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18165. svr.wait_until_ready();
  18166. Client cli(HOST, PORT);
  18167. // First request: get Last-Modified
  18168. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18169. ASSERT_TRUE(res1);
  18170. ASSERT_EQ(200, res1->status);
  18171. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18172. std::string last_modified = res1->get_header_value("Last-Modified");
  18173. // Range request with matching If-Range (date): should get 206
  18174. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18175. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18176. ASSERT_TRUE(res2);
  18177. EXPECT_EQ(206, res2->status);
  18178. EXPECT_EQ("FGHIJ", res2->body);
  18179. // Range request with old If-Range date: should get 200 (full content)
  18180. Headers h3 = {{"Range", "bytes=5-9"},
  18181. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18182. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18183. ASSERT_TRUE(res3);
  18184. EXPECT_EQ(200, res3->status);
  18185. EXPECT_EQ(content, res3->body);
  18186. // Range request with future If-Range date: should get 206
  18187. Headers h4 = {{"Range", "bytes=0-4"},
  18188. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18189. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18190. ASSERT_TRUE(res4);
  18191. EXPECT_EQ(206, res4->status);
  18192. EXPECT_EQ("ABCDE", res4->body);
  18193. svr.stop();
  18194. t.join();
  18195. std::remove(fname);
  18196. }
  18197. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18198. using namespace httplib;
  18199. const char *fname = "etag_malformed.txt";
  18200. const char *content = "malformed-etag";
  18201. {
  18202. std::ofstream ofs(fname);
  18203. ofs << content;
  18204. ASSERT_TRUE(ofs.good());
  18205. }
  18206. Server svr;
  18207. svr.set_mount_point("/static", ".");
  18208. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18209. svr.wait_until_ready();
  18210. Client cli(HOST, PORT);
  18211. // baseline: should get 200 and an ETag
  18212. auto res1 = cli.Get("/static/etag_malformed.txt");
  18213. ASSERT_TRUE(res1);
  18214. ASSERT_EQ(200, res1->status);
  18215. ASSERT_TRUE(res1->has_header("ETag"));
  18216. // Malformed ETag value (missing quotes) should be treated as non-matching
  18217. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18218. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18219. ASSERT_TRUE(res_bad);
  18220. EXPECT_EQ(200, res_bad->status);
  18221. // Whitespace-only header value should be considered invalid / non-matching
  18222. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18223. "Host: localhost\r\n"
  18224. "If-None-Match: \r\n"
  18225. "Connection: close\r\n"
  18226. "\r\n";
  18227. std::string out;
  18228. ASSERT_TRUE(send_request(5, raw_req, &out));
  18229. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18230. svr.stop();
  18231. t.join();
  18232. std::remove(fname);
  18233. }
  18234. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18235. using namespace httplib;
  18236. const char *fname = "ims_invalid_format.txt";
  18237. const char *content = "ims-bad-format";
  18238. {
  18239. std::ofstream ofs(fname);
  18240. ofs << content;
  18241. ASSERT_TRUE(ofs.good());
  18242. }
  18243. Server svr;
  18244. svr.set_mount_point("/static", ".");
  18245. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18246. svr.wait_until_ready();
  18247. Client cli(HOST, PORT);
  18248. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18249. ASSERT_TRUE(res1);
  18250. ASSERT_EQ(200, res1->status);
  18251. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18252. // If-Modified-Since with invalid format should not result in 304
  18253. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18254. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18255. ASSERT_TRUE(res_bad);
  18256. EXPECT_EQ(200, res_bad->status);
  18257. // If-Range with invalid date format should be treated as mismatch -> full
  18258. // content (200)
  18259. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18260. {"If-Range", "invalid-date"}};
  18261. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18262. ASSERT_TRUE(res_ifrange);
  18263. EXPECT_EQ(200, res_ifrange->status);
  18264. svr.stop();
  18265. t.join();
  18266. std::remove(fname);
  18267. }
  18268. TEST(ETagTest, IfRangeWithMalformedETag) {
  18269. using namespace httplib;
  18270. const char *fname = "ifrange_malformed.txt";
  18271. const std::string content = "0123456789";
  18272. {
  18273. std::ofstream ofs(fname);
  18274. ofs << content;
  18275. ASSERT_TRUE(ofs.good());
  18276. }
  18277. Server svr;
  18278. svr.set_mount_point("/static", ".");
  18279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18280. svr.wait_until_ready();
  18281. Client cli(HOST, PORT);
  18282. // First request: get ETag
  18283. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18284. ASSERT_TRUE(res1);
  18285. ASSERT_EQ(200, res1->status);
  18286. ASSERT_TRUE(res1->has_header("ETag"));
  18287. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18288. // full content (200)
  18289. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18290. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18291. ASSERT_TRUE(res2);
  18292. EXPECT_EQ(200, res2->status);
  18293. EXPECT_EQ(content, res2->body);
  18294. svr.stop();
  18295. t.join();
  18296. std::remove(fname);
  18297. }
  18298. TEST(ETagTest, ExtremeLargeDateValues) {
  18299. using namespace httplib;
  18300. const char *fname = "ims_extreme_date.txt";
  18301. const char *content = "ims-extreme-date";
  18302. {
  18303. std::ofstream ofs(fname);
  18304. ofs << content;
  18305. ASSERT_TRUE(ofs.good());
  18306. }
  18307. Server svr;
  18308. svr.set_mount_point("/static", ".");
  18309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18310. svr.wait_until_ready();
  18311. Client cli(HOST, PORT);
  18312. auto res1 = cli.Get(std::string("/static/") + fname);
  18313. ASSERT_TRUE(res1);
  18314. ASSERT_EQ(200, res1->status);
  18315. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18316. // Extremely large year that may overflow date parsing routines.
  18317. Headers h_large_date = {
  18318. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18319. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18320. ASSERT_TRUE(res_bad);
  18321. // Expect server to treat this as invalid/mismatch and return full content
  18322. EXPECT_EQ(200, res_bad->status);
  18323. // If-Range with extremely large date should be treated as mismatch -> full
  18324. // content (200)
  18325. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18326. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18327. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18328. ASSERT_TRUE(res_ifrange);
  18329. EXPECT_EQ(200, res_ifrange->status);
  18330. svr.stop();
  18331. t.join();
  18332. std::remove(fname);
  18333. }
  18334. TEST(ETagTest, NegativeFileModificationTime) {
  18335. using namespace httplib;
  18336. const char *fname = "ims_negative_mtime.txt";
  18337. const std::string content = "negative-mtime";
  18338. {
  18339. std::ofstream ofs(fname);
  18340. ofs << content;
  18341. ASSERT_TRUE(ofs.good());
  18342. }
  18343. // Try to set file mtime to a negative value. This may fail on some
  18344. // platforms/filesystems; if it fails, the test will still verify server
  18345. // behaves safely by performing a regular conditional request.
  18346. #if defined(__APPLE__) || defined(__linux__)
  18347. bool set_negative = false;
  18348. do {
  18349. struct timeval times[2];
  18350. // access time: now
  18351. times[0].tv_sec = time(nullptr);
  18352. times[0].tv_usec = 0;
  18353. // modification time: negative (e.g., -1)
  18354. times[1].tv_sec = -1;
  18355. times[1].tv_usec = 0;
  18356. if (utimes(fname, times) == 0) { set_negative = true; }
  18357. } while (0);
  18358. #else
  18359. bool set_negative = false;
  18360. #endif
  18361. Server svr;
  18362. svr.set_mount_point("/static", ".");
  18363. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18364. svr.wait_until_ready();
  18365. Client cli(HOST, PORT);
  18366. auto res1 = cli.Get(std::string("/static/") + fname);
  18367. ASSERT_TRUE(res1);
  18368. ASSERT_EQ(200, res1->status);
  18369. bool has_last_modified = res1->has_header("Last-Modified");
  18370. std::string last_modified;
  18371. if (has_last_modified) {
  18372. last_modified = res1->get_header_value("Last-Modified");
  18373. }
  18374. if (set_negative) {
  18375. // If we successfully set a negative mtime, ensure server returns a
  18376. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18377. // with an old date and ensure server handles it without crash.
  18378. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18379. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18380. ASSERT_TRUE(res2);
  18381. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18382. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18383. } else {
  18384. // Could not set negative mtime on this platform; fall back to verifying
  18385. // that normal invalid/malformed dates are treated safely (non-304).
  18386. Headers h_bad_date = {
  18387. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18388. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18389. ASSERT_TRUE(res_bad);
  18390. EXPECT_EQ(200, res_bad->status);
  18391. }
  18392. svr.stop();
  18393. t.join();
  18394. std::remove(fname);
  18395. }
  18396. //==============================================================================
  18397. // SSE Parsing Tests
  18398. //==============================================================================
  18399. class SSEParsingTest : public ::testing::Test {
  18400. protected:
  18401. // Test helper that mimics SSE parsing behavior
  18402. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18403. int &retry_ms) {
  18404. // Blank line signals end of event
  18405. if (line.empty() || line == "\r") { return true; }
  18406. // Lines starting with ':' are comments (ignored)
  18407. if (!line.empty() && line[0] == ':') { return false; }
  18408. // Find the colon separator
  18409. auto colon_pos = line.find(':');
  18410. if (colon_pos == std::string::npos) {
  18411. // Line with no colon is treated as field name with empty value
  18412. return false;
  18413. }
  18414. std::string field = line.substr(0, colon_pos);
  18415. std::string value;
  18416. // Value starts after colon, skip optional single space
  18417. if (colon_pos + 1 < line.size()) {
  18418. size_t value_start = colon_pos + 1;
  18419. if (line[value_start] == ' ') { value_start++; }
  18420. value = line.substr(value_start);
  18421. // Remove trailing \r if present
  18422. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18423. }
  18424. // Handle known fields
  18425. if (field == "event") {
  18426. msg.event = value;
  18427. } else if (field == "data") {
  18428. // Multiple data lines are concatenated with newlines
  18429. if (!msg.data.empty()) { msg.data += "\n"; }
  18430. msg.data += value;
  18431. } else if (field == "id") {
  18432. // Empty id is valid (clears the last event ID)
  18433. msg.id = value;
  18434. } else if (field == "retry") {
  18435. // Parse retry interval in milliseconds
  18436. {
  18437. int v = 0;
  18438. auto res =
  18439. detail::from_chars(value.data(), value.data() + value.size(), v);
  18440. if (res.ec == std::errc{}) { retry_ms = v; }
  18441. }
  18442. }
  18443. // Unknown fields are ignored per SSE spec
  18444. return false;
  18445. }
  18446. };
  18447. // Test: Single-line data
  18448. TEST_F(SSEParsingTest, SingleLineData) {
  18449. sse::SSEMessage msg;
  18450. int retry_ms = 3000;
  18451. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18452. EXPECT_EQ(msg.data, "hello");
  18453. EXPECT_EQ(msg.event, "message");
  18454. // Blank line ends event
  18455. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18456. }
  18457. // Test: Multi-line data
  18458. TEST_F(SSEParsingTest, MultiLineData) {
  18459. sse::SSEMessage msg;
  18460. int retry_ms = 3000;
  18461. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18462. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18463. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18464. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18465. }
  18466. // Test: Custom event types
  18467. TEST_F(SSEParsingTest, CustomEventType) {
  18468. sse::SSEMessage msg;
  18469. int retry_ms = 3000;
  18470. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18471. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18472. EXPECT_EQ(msg.event, "update");
  18473. EXPECT_EQ(msg.data, "payload");
  18474. }
  18475. // Test: Event ID handling
  18476. TEST_F(SSEParsingTest, EventIdHandling) {
  18477. sse::SSEMessage msg;
  18478. int retry_ms = 3000;
  18479. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18480. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18481. EXPECT_EQ(msg.id, "12345");
  18482. }
  18483. // Test: Empty event ID (clears last event ID)
  18484. TEST_F(SSEParsingTest, EmptyEventId) {
  18485. sse::SSEMessage msg;
  18486. msg.id = "previous";
  18487. int retry_ms = 3000;
  18488. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18489. EXPECT_EQ(msg.id, "");
  18490. }
  18491. // Test: Retry field parsing
  18492. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18493. sse::SSEMessage msg;
  18494. int retry_ms = 3000;
  18495. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18496. EXPECT_EQ(retry_ms, 5000);
  18497. }
  18498. // Test: Invalid retry value
  18499. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18500. sse::SSEMessage msg;
  18501. int retry_ms = 3000;
  18502. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18503. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18504. }
  18505. // Test: Comments (lines starting with :)
  18506. TEST_F(SSEParsingTest, CommentsIgnored) {
  18507. sse::SSEMessage msg;
  18508. int retry_ms = 3000;
  18509. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18510. EXPECT_EQ(msg.data, "");
  18511. EXPECT_EQ(msg.event, "message");
  18512. }
  18513. // Test: Colon in value
  18514. TEST_F(SSEParsingTest, ColonInValue) {
  18515. sse::SSEMessage msg;
  18516. int retry_ms = 3000;
  18517. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18518. EXPECT_EQ(msg.data, "hello:world:test");
  18519. }
  18520. // Test: Line with no colon (field name only)
  18521. TEST_F(SSEParsingTest, FieldNameOnly) {
  18522. sse::SSEMessage msg;
  18523. int retry_ms = 3000;
  18524. // According to SSE spec, this is treated as field name with empty value
  18525. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18526. // Since we don't recognize "data" without colon, data should be empty
  18527. EXPECT_EQ(msg.data, "");
  18528. }
  18529. // Test: Trailing \r handling
  18530. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18531. sse::SSEMessage msg;
  18532. int retry_ms = 3000;
  18533. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18534. EXPECT_EQ(msg.data, "hello");
  18535. }
  18536. // Test: Unknown fields ignored
  18537. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18538. sse::SSEMessage msg;
  18539. int retry_ms = 3000;
  18540. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18541. EXPECT_EQ(msg.data, "");
  18542. EXPECT_EQ(msg.event, "message");
  18543. }
  18544. // Test: Space after colon is optional
  18545. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18546. sse::SSEMessage msg1, msg2;
  18547. int retry_ms = 3000;
  18548. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18549. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18550. EXPECT_EQ(msg1.data, "hello");
  18551. EXPECT_EQ(msg2.data, "hello");
  18552. }
  18553. // Test: SSEMessage clear
  18554. TEST_F(SSEParsingTest, MessageClear) {
  18555. sse::SSEMessage msg;
  18556. msg.event = "custom";
  18557. msg.data = "some data";
  18558. msg.id = "123";
  18559. msg.clear();
  18560. EXPECT_EQ(msg.event, "message");
  18561. EXPECT_EQ(msg.data, "");
  18562. EXPECT_EQ(msg.id, "");
  18563. }
  18564. // Test: Complete event parsing
  18565. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18566. sse::SSEMessage msg;
  18567. int retry_ms = 3000;
  18568. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18569. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18570. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18571. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18572. // Blank line ends event
  18573. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18574. EXPECT_EQ(msg.event, "notification");
  18575. EXPECT_EQ(msg.id, "evt-42");
  18576. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18577. EXPECT_EQ(retry_ms, 1000);
  18578. }
  18579. //==============================================================================
  18580. // Integration Tests with Server
  18581. //==============================================================================
  18582. class SSEIntegrationTest : public ::testing::Test {
  18583. protected:
  18584. void SetUp() override {
  18585. stop_server_.store(false);
  18586. events_.clear();
  18587. server_ = httplib::detail::make_unique<Server>();
  18588. setup_server();
  18589. start_server();
  18590. }
  18591. void TearDown() override {
  18592. stop_server_.store(true);
  18593. event_cv_.notify_all();
  18594. server_->stop();
  18595. if (server_thread_.joinable()) { server_thread_.join(); }
  18596. }
  18597. void setup_server() {
  18598. // Simple SSE endpoint
  18599. server_->Get("/events", [this](const Request &req, Response &res) {
  18600. auto last_id = req.get_header_value("Last-Event-ID");
  18601. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18602. res.set_chunked_content_provider(
  18603. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18604. std::unique_lock<std::mutex> lock(event_mutex_);
  18605. if (event_cv_.wait_for(
  18606. lock, std::chrono::milliseconds(200), [this] {
  18607. return !events_.empty() || stop_server_.load();
  18608. })) {
  18609. if (stop_server_.load()) { return false; }
  18610. if (!events_.empty()) {
  18611. std::string event = events_.front();
  18612. events_.erase(events_.begin());
  18613. sink.write(event.data(), event.size());
  18614. return true;
  18615. }
  18616. }
  18617. return !stop_server_.load();
  18618. });
  18619. });
  18620. // Endpoint that returns error
  18621. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18622. res.status = 500;
  18623. res.set_content("Internal Server Error", "text/plain");
  18624. });
  18625. // Endpoint for custom event types
  18626. server_->Get("/custom-events", [](const Request &, Response &res) {
  18627. res.set_chunked_content_provider(
  18628. "text/event-stream", [](size_t offset, DataSink &sink) {
  18629. if (offset == 0) {
  18630. std::string event = "event: update\ndata: updated\n\n"
  18631. "event: delete\ndata: deleted\n\n";
  18632. sink.write(event.data(), event.size());
  18633. }
  18634. return false; // End stream after sending
  18635. });
  18636. });
  18637. }
  18638. void start_server() {
  18639. port_ = server_->bind_to_any_port(HOST);
  18640. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18641. // Wait for server to start
  18642. while (!server_->is_running()) {
  18643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18644. }
  18645. }
  18646. int get_port() const { return port_; }
  18647. void send_event(const std::string &event) {
  18648. std::lock_guard<std::mutex> lock(event_mutex_);
  18649. events_.push_back(event);
  18650. event_cv_.notify_all();
  18651. }
  18652. std::unique_ptr<Server> server_;
  18653. std::thread server_thread_;
  18654. std::mutex event_mutex_;
  18655. std::condition_variable event_cv_;
  18656. std::vector<std::string> events_;
  18657. std::atomic<bool> stop_server_{false};
  18658. std::string last_received_event_id_;
  18659. int port_ = 0;
  18660. };
  18661. // Test: Successful connection and on_open callback
  18662. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18663. // Add a simple endpoint that sends one event and closes
  18664. server_->Get("/simple-event", [](const Request &, Response &res) {
  18665. res.set_chunked_content_provider(
  18666. "text/event-stream", [](size_t offset, DataSink &sink) {
  18667. if (offset == 0) {
  18668. std::string event = "data: hello\n\n";
  18669. sink.write(event.data(), event.size());
  18670. }
  18671. return false; // Close stream after sending
  18672. });
  18673. });
  18674. Client client("localhost", get_port());
  18675. sse::SSEClient sse(client, "/simple-event");
  18676. std::atomic<bool> open_called{false};
  18677. std::atomic<bool> message_received{false};
  18678. sse.on_open([&open_called]() { open_called.store(true); });
  18679. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18680. if (msg.data == "hello") { message_received.store(true); }
  18681. });
  18682. sse.set_reconnect_interval(100);
  18683. sse.set_max_reconnect_attempts(1);
  18684. // Start async
  18685. sse.start_async();
  18686. // Wait for message to be processed
  18687. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18688. sse.stop();
  18689. EXPECT_TRUE(open_called.load());
  18690. EXPECT_TRUE(message_received.load());
  18691. }
  18692. // Test: on_message callback
  18693. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18694. // Endpoint that sends multiple events then closes
  18695. server_->Get("/multi-event", [](const Request &, Response &res) {
  18696. res.set_chunked_content_provider(
  18697. "text/event-stream", [](size_t offset, DataSink &sink) {
  18698. if (offset == 0) {
  18699. std::string events = "data: message1\n\ndata: message2\n\n";
  18700. sink.write(events.data(), events.size());
  18701. }
  18702. return false;
  18703. });
  18704. });
  18705. Client client("localhost", get_port());
  18706. sse::SSEClient sse(client, "/multi-event");
  18707. std::vector<std::string> received_messages;
  18708. std::mutex messages_mutex;
  18709. sse.on_message([&](const sse::SSEMessage &msg) {
  18710. std::lock_guard<std::mutex> lock(messages_mutex);
  18711. received_messages.push_back(msg.data);
  18712. });
  18713. sse.set_reconnect_interval(100);
  18714. sse.set_max_reconnect_attempts(1);
  18715. sse.start_async();
  18716. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18717. sse.stop();
  18718. std::lock_guard<std::mutex> lock(messages_mutex);
  18719. EXPECT_GE(received_messages.size(), 2u);
  18720. if (received_messages.size() >= 2) {
  18721. EXPECT_EQ(received_messages[0], "message1");
  18722. EXPECT_EQ(received_messages[1], "message2");
  18723. }
  18724. }
  18725. // Test: on_event for specific types
  18726. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18727. Client client("localhost", get_port());
  18728. sse::SSEClient sse(client, "/custom-events");
  18729. std::atomic<bool> update_received{false};
  18730. std::atomic<bool> delete_received{false};
  18731. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18732. if (msg.data == "updated") { update_received.store(true); }
  18733. });
  18734. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18735. if (msg.data == "deleted") { delete_received.store(true); }
  18736. });
  18737. sse.set_max_reconnect_attempts(1);
  18738. sse.start_async();
  18739. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18740. sse.stop();
  18741. EXPECT_TRUE(update_received.load());
  18742. EXPECT_TRUE(delete_received.load());
  18743. }
  18744. // Test: on_error callback on connection failure
  18745. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18746. // Connect to a non-existent port
  18747. Client client("localhost", 59999);
  18748. sse::SSEClient sse(client, "/events");
  18749. std::atomic<bool> error_called{false};
  18750. Error received_error = Error::Success;
  18751. sse.on_error([&](Error err) {
  18752. error_called.store(true);
  18753. received_error = err;
  18754. });
  18755. sse.set_reconnect_interval(50);
  18756. sse.set_max_reconnect_attempts(1);
  18757. sse.start_async();
  18758. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18759. sse.stop();
  18760. EXPECT_TRUE(error_called.load());
  18761. EXPECT_NE(received_error, Error::Success);
  18762. }
  18763. // Test: Last-Event-ID header sent on reconnect
  18764. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18765. // Endpoint that sends event with ID
  18766. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18767. res.set_chunked_content_provider(
  18768. "text/event-stream", [](size_t offset, DataSink &sink) {
  18769. if (offset == 0) {
  18770. std::string event = "id: evt-123\ndata: test\n\n";
  18771. sink.write(event.data(), event.size());
  18772. }
  18773. return false;
  18774. });
  18775. });
  18776. Client client("localhost", get_port());
  18777. sse::SSEClient sse(client, "/event-with-id");
  18778. std::atomic<bool> id_received{false};
  18779. sse.on_message([&](const sse::SSEMessage &msg) {
  18780. if (!msg.id.empty()) { id_received.store(true); }
  18781. });
  18782. sse.set_reconnect_interval(100);
  18783. sse.set_max_reconnect_attempts(1);
  18784. sse.start_async();
  18785. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18786. sse.stop();
  18787. EXPECT_TRUE(id_received.load());
  18788. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18789. }
  18790. // Test: Manual stop
  18791. TEST_F(SSEIntegrationTest, ManualStop) {
  18792. // Endpoint that sends one event and stays open briefly
  18793. std::atomic<bool> handler_running{true};
  18794. server_->Get("/stay-open", [&handler_running](const Request &,
  18795. Response &res) {
  18796. res.set_chunked_content_provider(
  18797. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18798. if (offset == 0) {
  18799. std::string event = "data: connected\n\n";
  18800. sink.write(event.data(), event.size());
  18801. }
  18802. // Keep connection open while handler_running is true
  18803. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18804. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18805. }
  18806. return false;
  18807. });
  18808. });
  18809. Client client("localhost", get_port());
  18810. sse::SSEClient sse(client, "/stay-open");
  18811. std::atomic<bool> connected{false};
  18812. sse.on_open([&connected]() { connected.store(true); });
  18813. sse.set_reconnect_interval(100);
  18814. sse.set_max_reconnect_attempts(1);
  18815. sse.start_async();
  18816. // Wait for connection to establish
  18817. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18818. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18819. }
  18820. EXPECT_TRUE(connected.load());
  18821. EXPECT_TRUE(sse.is_connected());
  18822. // Signal handler to stop
  18823. handler_running.store(false);
  18824. // Stop SSE client
  18825. sse.stop();
  18826. EXPECT_FALSE(sse.is_connected());
  18827. }
  18828. // Test: SSEClient with custom headers
  18829. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18830. // Setup a server endpoint that checks for custom header
  18831. std::atomic<bool> header_received{false};
  18832. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18833. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18834. header_received.store(true);
  18835. }
  18836. res.set_chunked_content_provider("text/event-stream",
  18837. [](size_t, DataSink &) { return false; });
  18838. });
  18839. Client client("localhost", get_port());
  18840. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18841. sse::SSEClient sse(client, "/header-check", headers);
  18842. sse.set_max_reconnect_attempts(1);
  18843. sse.start_async();
  18844. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18845. sse.stop();
  18846. EXPECT_TRUE(header_received.load());
  18847. }
  18848. // Test: Reconnect interval configuration
  18849. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18850. Client client("localhost", get_port());
  18851. sse::SSEClient sse(client, "/events");
  18852. auto &result = sse.set_reconnect_interval(500);
  18853. // Builder pattern should return reference to self
  18854. EXPECT_EQ(&result, &sse);
  18855. }
  18856. // Test: Max reconnect attempts
  18857. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18858. // Connect to non-existent port to force reconnects
  18859. Client client("localhost", 59998);
  18860. sse::SSEClient sse(client, "/events");
  18861. std::atomic<int> error_count{0};
  18862. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18863. sse.set_reconnect_interval(50);
  18864. sse.set_max_reconnect_attempts(2);
  18865. auto start = std::chrono::steady_clock::now();
  18866. sse.start(); // Blocking call
  18867. auto end = std::chrono::steady_clock::now();
  18868. // Should have stopped after 2 failed attempts
  18869. EXPECT_GE(error_count.load(), 2);
  18870. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18871. auto duration =
  18872. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18873. #ifdef _WIN32
  18874. // Windows is much slower for socket connection failures
  18875. EXPECT_LT(duration.count(), 7000);
  18876. #else
  18877. EXPECT_LT(duration.count(), 1000);
  18878. #endif
  18879. }
  18880. // Test: Multi-line data in integration
  18881. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18882. // Endpoint with multi-line data
  18883. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18884. res.set_chunked_content_provider(
  18885. "text/event-stream", [](size_t offset, DataSink &sink) {
  18886. if (offset == 0) {
  18887. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18888. sink.write(event.data(), event.size());
  18889. }
  18890. return false;
  18891. });
  18892. });
  18893. Client client("localhost", get_port());
  18894. sse::SSEClient sse(client, "/multiline-data");
  18895. std::string received_data;
  18896. std::mutex data_mutex;
  18897. sse.on_message([&](const sse::SSEMessage &msg) {
  18898. std::lock_guard<std::mutex> lock(data_mutex);
  18899. received_data = msg.data;
  18900. });
  18901. sse.set_reconnect_interval(100);
  18902. sse.set_max_reconnect_attempts(1);
  18903. sse.start_async();
  18904. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18905. sse.stop();
  18906. std::lock_guard<std::mutex> lock(data_mutex);
  18907. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18908. }
  18909. // Test: Auto-reconnect after server disconnection
  18910. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18911. std::atomic<int> connection_count{0};
  18912. std::atomic<int> message_count{0};
  18913. // Endpoint that sends one event and closes, forcing reconnect
  18914. server_->Get("/reconnect-test",
  18915. [&connection_count](const Request &, Response &res) {
  18916. connection_count.fetch_add(1);
  18917. res.set_chunked_content_provider(
  18918. "text/event-stream", [](size_t offset, DataSink &sink) {
  18919. if (offset == 0) {
  18920. std::string event = "data: hello\n\n";
  18921. sink.write(event.data(), event.size());
  18922. }
  18923. return false; // Close connection after sending
  18924. });
  18925. });
  18926. Client client("localhost", get_port());
  18927. sse::SSEClient sse(client, "/reconnect-test");
  18928. sse.on_message([&message_count](const sse::SSEMessage &) {
  18929. message_count.fetch_add(1);
  18930. });
  18931. sse.set_reconnect_interval(100);
  18932. sse.set_max_reconnect_attempts(3);
  18933. sse.start_async();
  18934. // Wait long enough for multiple reconnects
  18935. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18936. sse.stop();
  18937. // Should have connected multiple times (initial + reconnects)
  18938. EXPECT_GE(connection_count.load(), 2);
  18939. // Should have received messages from multiple connections
  18940. EXPECT_GE(message_count.load(), 2);
  18941. }
  18942. // Test: A retry field that is not all ASCII digits is ignored
  18943. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  18944. std::atomic<int> connection_count{0};
  18945. server_->Get("/bad-retry",
  18946. [&connection_count](const Request &, Response &res) {
  18947. connection_count.fetch_add(1);
  18948. res.set_chunked_content_provider(
  18949. "text/event-stream", [](size_t offset, DataSink &sink) {
  18950. if (offset == 0) {
  18951. std::string event = "retry: -1\ndata: hello\n\n";
  18952. sink.write(event.data(), event.size());
  18953. }
  18954. return false;
  18955. });
  18956. });
  18957. Client client("localhost", get_port());
  18958. sse::SSEClient sse(client, "/bad-retry");
  18959. sse.set_reconnect_interval(10000);
  18960. sse.start_async();
  18961. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18962. sse.stop();
  18963. EXPECT_EQ(connection_count.load(), 1);
  18964. }
  18965. // Test: A retry field of all ASCII digits sets the reconnection time
  18966. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  18967. std::atomic<int> connection_count{0};
  18968. server_->Get("/zero-retry",
  18969. [&connection_count](const Request &, Response &res) {
  18970. connection_count.fetch_add(1);
  18971. res.set_chunked_content_provider(
  18972. "text/event-stream", [](size_t offset, DataSink &sink) {
  18973. if (offset == 0) {
  18974. std::string event = "retry: 0\ndata: hello\n\n";
  18975. sink.write(event.data(), event.size());
  18976. }
  18977. return false;
  18978. });
  18979. });
  18980. Client client("localhost", get_port());
  18981. sse::SSEClient sse(client, "/zero-retry");
  18982. sse.set_reconnect_interval(10000);
  18983. sse.start_async();
  18984. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18985. sse.stop();
  18986. // The server-supplied interval is applied, but never below 100ms, so
  18987. // "retry: 0" does not cause a busy reconnect loop
  18988. EXPECT_GE(connection_count.load(), 2);
  18989. EXPECT_LE(connection_count.load(), 10);
  18990. }
  18991. // Test: Last-Event-ID sent on reconnect
  18992. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18993. std::atomic<int> connection_count{0};
  18994. std::vector<std::string> received_last_event_ids;
  18995. std::mutex id_mutex;
  18996. // Endpoint that checks Last-Event-ID header and sends event with ID
  18997. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18998. int conn = connection_count.fetch_add(1);
  18999. // Capture the Last-Event-ID header from each connection
  19000. {
  19001. std::lock_guard<std::mutex> lock(id_mutex);
  19002. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19003. }
  19004. res.set_chunked_content_provider(
  19005. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19006. if (offset == 0) {
  19007. std::string event =
  19008. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19009. sink.write(event.data(), event.size());
  19010. }
  19011. return false;
  19012. });
  19013. });
  19014. Client client("localhost", get_port());
  19015. sse::SSEClient sse(client, "/reconnect-with-id");
  19016. sse.set_reconnect_interval(100);
  19017. sse.set_max_reconnect_attempts(3);
  19018. sse.start_async();
  19019. // Wait for at least 2 connections
  19020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19021. sse.stop();
  19022. // Verify behavior
  19023. std::lock_guard<std::mutex> lock(id_mutex);
  19024. EXPECT_GE(received_last_event_ids.size(), 2u);
  19025. // First connection should have no Last-Event-ID
  19026. if (!received_last_event_ids.empty()) {
  19027. EXPECT_EQ(received_last_event_ids[0], "");
  19028. }
  19029. // Second connection should have Last-Event-ID from first connection
  19030. if (received_last_event_ids.size() >= 2) {
  19031. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19032. }
  19033. }
  19034. // Test: set_headers updates headers used on reconnect
  19035. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19036. std::vector<std::string> received_tokens;
  19037. std::mutex token_mutex;
  19038. // Endpoint that captures Authorization header
  19039. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19040. {
  19041. std::lock_guard<std::mutex> lock(token_mutex);
  19042. received_tokens.push_back(req.get_header_value("Authorization"));
  19043. }
  19044. res.set_chunked_content_provider(
  19045. "text/event-stream", [](size_t offset, DataSink &sink) {
  19046. if (offset == 0) {
  19047. std::string event = "data: hello\n\n";
  19048. sink.write(event.data(), event.size());
  19049. }
  19050. return false; // Close connection to trigger reconnect
  19051. });
  19052. });
  19053. Client client("localhost", get_port());
  19054. Headers headers = {{"Authorization", "Bearer old-token"}};
  19055. sse::SSEClient sse(client, "/auth-check", headers);
  19056. // Update headers on each successful connection
  19057. sse.on_open(
  19058. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19059. sse.set_reconnect_interval(100);
  19060. sse.set_max_reconnect_attempts(3);
  19061. sse.start_async();
  19062. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19063. sse.stop();
  19064. std::lock_guard<std::mutex> lock(token_mutex);
  19065. ASSERT_GE(received_tokens.size(), 2u);
  19066. // First connection uses original header
  19067. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19068. // Second connection uses updated header from set_headers
  19069. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19070. }
  19071. // Test: 401 allows reconnection (so on_error can refresh headers)
  19072. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19073. std::atomic<int> connection_count{0};
  19074. // Endpoint: returns 401 on first attempt, 200 on second
  19075. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19076. int conn = connection_count.fetch_add(1);
  19077. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19078. res.status = StatusCode::Unauthorized_401;
  19079. res.set_content("Unauthorized", "text/plain");
  19080. return;
  19081. }
  19082. res.set_chunked_content_provider(
  19083. "text/event-stream", [](size_t offset, DataSink &sink) {
  19084. if (offset == 0) {
  19085. std::string event = "data: authenticated\n\n";
  19086. sink.write(event.data(), event.size());
  19087. }
  19088. return false;
  19089. });
  19090. });
  19091. Client client("localhost", get_port());
  19092. Headers headers = {{"Authorization", "Bearer expired"}};
  19093. sse::SSEClient sse(client, "/auth-retry", headers);
  19094. std::atomic<bool> message_received{false};
  19095. // Refresh token on error
  19096. sse.on_error(
  19097. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19098. sse.on_message([&](const sse::SSEMessage &msg) {
  19099. if (msg.data == "authenticated") { message_received.store(true); }
  19100. });
  19101. sse.set_reconnect_interval(100);
  19102. sse.set_max_reconnect_attempts(3);
  19103. sse.start_async();
  19104. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19105. sse.stop();
  19106. // Should have reconnected after 401 and succeeded with new token
  19107. EXPECT_GE(connection_count.load(), 2);
  19108. EXPECT_TRUE(message_received.load());
  19109. }
  19110. TEST(Issue2318Test, EmptyHostString) {
  19111. {
  19112. httplib::Client cli_empty("", PORT);
  19113. auto res = cli_empty.Get("/");
  19114. ASSERT_FALSE(res);
  19115. EXPECT_EQ(httplib::Error::Connection, res.error());
  19116. }
  19117. {
  19118. httplib::Client cli(" ", PORT);
  19119. auto res = cli.Get("/");
  19120. ASSERT_FALSE(res);
  19121. EXPECT_EQ(httplib::Error::Connection, res.error());
  19122. }
  19123. }
  19124. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19125. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19126. Server svr;
  19127. // Set a small payload limit (1KB)
  19128. svr.set_payload_max_length(1024);
  19129. svr.Post("/test", [&](const Request &req, Response &res) {
  19130. res.set_content("Body size: " + std::to_string(req.body.size()),
  19131. "text/plain");
  19132. });
  19133. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19134. auto se = detail::scope_exit([&] {
  19135. svr.stop();
  19136. listen_thread.join();
  19137. });
  19138. svr.wait_until_ready();
  19139. // Create data that compresses well but exceeds limit when decompressed
  19140. // 8KB of repeated null bytes compresses to a very small size
  19141. std::string original_data(8 * 1024, '\0');
  19142. // Compress the data using gzip
  19143. std::string compressed_data;
  19144. detail::gzip_compressor compressor;
  19145. compressor.compress(original_data.data(), original_data.size(), true,
  19146. [&](const char *data, size_t size) {
  19147. compressed_data.append(data, size);
  19148. return true;
  19149. });
  19150. // Verify compression worked (compressed should be much smaller)
  19151. ASSERT_LT(compressed_data.size(), original_data.size());
  19152. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19153. // Send compressed data with Content-Encoding: gzip
  19154. Client cli(HOST, PORT);
  19155. Headers headers = {{"Content-Encoding", "gzip"}};
  19156. auto res =
  19157. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19158. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19160. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19161. }
  19162. #endif
  19163. // ============================================================================
  19164. // OpenSSL-Specific Tests
  19165. // ============================================================================
  19166. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19167. X509 *readCertificate(const std::string &strFileName) {
  19168. std::ifstream inStream(strFileName);
  19169. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19170. std::istreambuf_iterator<char>());
  19171. if (strCertPEM.empty()) return (nullptr);
  19172. BIO *pbCert = BIO_new(BIO_s_mem());
  19173. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19174. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19175. BIO_free(pbCert);
  19176. return (pCert);
  19177. }
  19178. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19179. std::ifstream inStream(strFileName);
  19180. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19181. std::istreambuf_iterator<char>());
  19182. if (strPrivateKeyPEM.empty()) return (nullptr);
  19183. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19184. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19185. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19186. BIO_free(pbPrivKey);
  19187. return (pPrivateKey);
  19188. }
  19189. TEST(BindServerTest, UpdateCerts) {
  19190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19191. int port = svr.bind_to_any_port("0.0.0.0");
  19192. ASSERT_TRUE(svr.is_valid());
  19193. ASSERT_TRUE(port > 0);
  19194. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19195. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19196. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19197. ASSERT_TRUE(cert != nullptr);
  19198. ASSERT_TRUE(ca_cert != nullptr);
  19199. ASSERT_TRUE(key != nullptr);
  19200. X509_STORE *cert_store = X509_STORE_new();
  19201. X509_STORE_add_cert(cert_store, ca_cert);
  19202. // svr.update_certs(cert, key, cert_store); // deprecated
  19203. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19204. CLIENT_CA_CERT_FILE);
  19205. ASSERT_TRUE(svr.is_valid());
  19206. svr.stop();
  19207. X509_STORE_free(cert_store);
  19208. X509_free(cert);
  19209. X509_free(ca_cert);
  19210. EVP_PKEY_free(key);
  19211. }
  19212. // Test that update_certs() updates client CA list correctly
  19213. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19214. // Start with file-based constructor
  19215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19216. ASSERT_TRUE(svr.is_valid());
  19217. // Initially no client CA list should be set
  19218. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19219. ASSERT_TRUE(ssl_ctx != nullptr);
  19220. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19221. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19222. EXPECT_EQ(0, count_before);
  19223. // Now update with client CA (PEM string)
  19224. std::string cert_pem, key_pem, ca_pem;
  19225. read_file(SERVER_CERT_FILE, cert_pem);
  19226. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19227. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19228. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19229. ASSERT_TRUE(svr.is_valid());
  19230. // Now client CA list should be set
  19231. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19232. ASSERT_TRUE(ca_list_after != nullptr);
  19233. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19234. }
  19235. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19236. // Test that the file-path SSLServer constructor properly sets the client CA
  19237. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19239. ASSERT_TRUE(svr.is_valid());
  19240. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19241. ASSERT_TRUE(ssl_ctx != nullptr);
  19242. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19243. ASSERT_TRUE(ca_list != nullptr);
  19244. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19245. }
  19246. #endif
  19247. // ============================================================================
  19248. // MbedTLS-Specific Tests
  19249. // ============================================================================
  19250. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19251. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19252. using namespace httplib::tls;
  19253. // Track if callback was invoked
  19254. bool callback_invoked = false;
  19255. // The callback receives void* ctx which is actually MbedTlsContext*
  19256. // We can access the mbedtls_ssl_config via the context
  19257. auto setup_callback = [&callback_invoked](void *ctx) {
  19258. callback_invoked = true;
  19259. // Cast to MbedTlsContext* to access the ssl config
  19260. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19261. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19262. // Use static variables to hold certificate data (simplified for test)
  19263. static mbedtls_x509_crt own_cert;
  19264. static mbedtls_pk_context own_key;
  19265. static mbedtls_x509_crt ca_chain;
  19266. static bool initialized = false;
  19267. if (!initialized) {
  19268. mbedtls_x509_crt_init(&own_cert);
  19269. mbedtls_pk_init(&own_key);
  19270. mbedtls_x509_crt_init(&ca_chain);
  19271. // Load server certificate
  19272. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19273. return false;
  19274. }
  19275. // Load server private key.
  19276. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19277. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19278. #if MBEDTLS_VERSION_MAJOR == 3
  19279. ,
  19280. mbedtls_ctr_drbg_random, nullptr
  19281. #endif
  19282. ) != 0) {
  19283. return false;
  19284. }
  19285. // Load CA chain for client verification
  19286. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19287. return false;
  19288. }
  19289. initialized = true;
  19290. }
  19291. // Configure the SSL config
  19292. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19293. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19294. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19295. // Set minimum TLS version using mbedTLS native API
  19296. #if MBEDTLS_VERSION_MAJOR >= 3
  19297. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19298. #else
  19299. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19300. MBEDTLS_SSL_MINOR_VERSION_3);
  19301. #endif
  19302. return true;
  19303. };
  19304. SSLServer svr(setup_callback);
  19305. ASSERT_TRUE(svr.is_valid());
  19306. ASSERT_TRUE(callback_invoked);
  19307. svr.Get("/test", [&](const Request &req, Response &res) {
  19308. res.set_content("test", "text/plain");
  19309. auto cert = req.peer_cert();
  19310. ASSERT_TRUE(static_cast<bool>(cert));
  19311. auto common_name = cert.subject_cn();
  19312. EXPECT_EQ("Common Name", common_name);
  19313. });
  19314. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19315. auto se = detail::scope_exit([&] {
  19316. svr.stop();
  19317. t.join();
  19318. ASSERT_FALSE(svr.is_running());
  19319. });
  19320. svr.wait_until_ready();
  19321. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19322. cli.enable_server_certificate_verification(false);
  19323. cli.set_connection_timeout(30);
  19324. auto res = cli.Get("/test");
  19325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19326. ASSERT_EQ(StatusCode::OK_200, res->status);
  19327. }
  19328. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19329. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19330. // keep-alive SSL session, which reads through that config in
  19331. // mbedtls_ssl_close_notify.
  19332. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19334. ASSERT_TRUE(svr.is_valid());
  19335. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19336. res.set_content("test", "text/plain");
  19337. });
  19338. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19339. auto se = detail::scope_exit([&] {
  19340. svr.stop();
  19341. t.join();
  19342. ASSERT_FALSE(svr.is_running());
  19343. });
  19344. svr.wait_until_ready();
  19345. {
  19346. SSLClient cli(HOST, PORT);
  19347. cli.enable_server_certificate_verification(false);
  19348. cli.set_keep_alive(true);
  19349. auto res = cli.Get("/test");
  19350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19351. ASSERT_EQ(StatusCode::OK_200, res->status);
  19352. // cli is destructed here with the keep-alive SSL session still open.
  19353. }
  19354. }
  19355. #endif
  19356. // WebSocket Tests
  19357. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19358. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19359. // defining the meaning of these bits has been negotiated.
  19360. auto make_frame = [](uint8_t first_byte) {
  19361. std::string frame;
  19362. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19363. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19364. frame += "Hello";
  19365. return frame;
  19366. };
  19367. // RSV1 set (0x40)
  19368. {
  19369. detail::BufferStream strm;
  19370. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19371. ws::Opcode opcode;
  19372. std::string payload;
  19373. bool fin;
  19374. EXPECT_EQ(
  19375. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19376. ws::impl::FrameRead::Fail);
  19377. }
  19378. // RSV2 set (0x20)
  19379. {
  19380. detail::BufferStream strm;
  19381. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19382. ws::Opcode opcode;
  19383. std::string payload;
  19384. bool fin;
  19385. EXPECT_EQ(
  19386. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19387. ws::impl::FrameRead::Fail);
  19388. }
  19389. // RSV3 set (0x10)
  19390. {
  19391. detail::BufferStream strm;
  19392. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19393. ws::Opcode opcode;
  19394. std::string payload;
  19395. bool fin;
  19396. EXPECT_EQ(
  19397. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19398. ws::impl::FrameRead::Fail);
  19399. }
  19400. // No RSV bits set - should succeed
  19401. {
  19402. detail::BufferStream strm;
  19403. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19404. ws::Opcode opcode;
  19405. std::string payload;
  19406. bool fin;
  19407. EXPECT_EQ(
  19408. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19409. ws::impl::FrameRead::Ok);
  19410. EXPECT_EQ(ws::Opcode::Text, opcode);
  19411. EXPECT_EQ("Hello", payload);
  19412. EXPECT_TRUE(fin);
  19413. }
  19414. }
  19415. TEST(WebSocketTest, ControlFrameValidation) {
  19416. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19417. // payload length <= 125.
  19418. // Ping with FIN=0 - must be rejected
  19419. {
  19420. detail::BufferStream strm;
  19421. std::string frame;
  19422. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19423. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19424. strm.write(frame.data(), frame.size());
  19425. ws::Opcode opcode;
  19426. std::string payload;
  19427. bool fin;
  19428. EXPECT_EQ(
  19429. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19430. ws::impl::FrameRead::Fail);
  19431. }
  19432. // Close with FIN=0 - must be rejected
  19433. {
  19434. detail::BufferStream strm;
  19435. std::string frame;
  19436. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19437. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19438. strm.write(frame.data(), frame.size());
  19439. ws::Opcode opcode;
  19440. std::string payload;
  19441. bool fin;
  19442. EXPECT_EQ(
  19443. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19444. ws::impl::FrameRead::Fail);
  19445. }
  19446. // Ping with payload_len=126 (extended length) - must be rejected
  19447. {
  19448. detail::BufferStream strm;
  19449. std::string frame;
  19450. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19451. frame += static_cast<char>(126); // payload_len=126 (>125)
  19452. frame += static_cast<char>(0x00); // extended length high byte
  19453. frame += static_cast<char>(126); // extended length low byte
  19454. frame += std::string(126, 'x');
  19455. strm.write(frame.data(), frame.size());
  19456. ws::Opcode opcode;
  19457. std::string payload;
  19458. bool fin;
  19459. EXPECT_EQ(
  19460. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19461. ws::impl::FrameRead::Fail);
  19462. }
  19463. // Ping with FIN=1 and payload_len=125 - should succeed
  19464. {
  19465. detail::BufferStream strm;
  19466. std::string frame;
  19467. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19468. frame += static_cast<char>(125); // payload_len=125
  19469. frame += std::string(125, 'x');
  19470. strm.write(frame.data(), frame.size());
  19471. ws::Opcode opcode;
  19472. std::string payload;
  19473. bool fin;
  19474. EXPECT_EQ(
  19475. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19476. ws::impl::FrameRead::Ok);
  19477. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19478. EXPECT_EQ(125u, payload.size());
  19479. EXPECT_TRUE(fin);
  19480. }
  19481. }
  19482. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19483. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19484. // length MUST be 0.
  19485. // MSB set - must be rejected
  19486. {
  19487. detail::BufferStream strm;
  19488. std::string frame;
  19489. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19490. frame += static_cast<char>(127); // 64-bit extended length
  19491. frame += static_cast<char>(0x80); // MSB set (invalid)
  19492. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19493. strm.write(frame.data(), frame.size());
  19494. ws::Opcode opcode;
  19495. std::string payload;
  19496. bool fin;
  19497. EXPECT_EQ(
  19498. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19499. ws::impl::FrameRead::Fail);
  19500. }
  19501. // MSB clear - should pass length parsing (will be rejected by max_len,
  19502. // but that's a different check; use a small length to verify)
  19503. {
  19504. detail::BufferStream strm;
  19505. std::string frame;
  19506. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19507. frame += static_cast<char>(127); // 64-bit extended length
  19508. frame += std::string(7, '\0'); // high bytes = 0
  19509. frame += static_cast<char>(0x03); // length = 3
  19510. frame += "abc";
  19511. strm.write(frame.data(), frame.size());
  19512. ws::Opcode opcode;
  19513. std::string payload;
  19514. bool fin;
  19515. EXPECT_EQ(
  19516. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19517. ws::impl::FrameRead::Ok);
  19518. EXPECT_EQ(ws::Opcode::Text, opcode);
  19519. EXPECT_EQ("abc", payload);
  19520. }
  19521. }
  19522. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19523. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19524. // Valid UTF-8
  19525. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19526. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19527. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19528. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19529. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19530. // Invalid UTF-8
  19531. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19532. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19533. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19534. EXPECT_FALSE(
  19535. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19536. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19537. }
  19538. TEST(WebSocketTest, ConnectAndDisconnect) {
  19539. Server svr;
  19540. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19541. std::string msg;
  19542. while (ws.read(msg)) {}
  19543. });
  19544. auto port = svr.bind_to_any_port(HOST);
  19545. std::thread t([&]() { svr.listen_after_bind(); });
  19546. svr.wait_until_ready();
  19547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19548. auto res = client.connect();
  19549. ASSERT_TRUE(res);
  19550. EXPECT_EQ(Error::Success, res.error());
  19551. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19552. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19553. EXPECT_TRUE(client.is_open());
  19554. client.close();
  19555. EXPECT_FALSE(client.is_open());
  19556. svr.stop();
  19557. t.join();
  19558. }
  19559. TEST(WebSocketTest, ValidURL) {
  19560. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19561. EXPECT_TRUE(ws1.is_valid());
  19562. ws::WebSocketClient ws2("ws://example.com/path");
  19563. EXPECT_TRUE(ws2.is_valid());
  19564. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19565. EXPECT_TRUE(ws3.is_valid());
  19566. #ifdef CPPHTTPLIB_SSL_ENABLED
  19567. ws::WebSocketClient wss1("wss://example.com/path");
  19568. EXPECT_TRUE(wss1.is_valid());
  19569. ws::WebSocketClient wss2("wss://example.com:443/path");
  19570. EXPECT_TRUE(wss2.is_valid());
  19571. #endif
  19572. }
  19573. TEST(WebSocketTest, InvalidURL) {
  19574. // No scheme
  19575. ws::WebSocketClient ws1("localhost:8080/path");
  19576. EXPECT_FALSE(ws1.is_valid());
  19577. // No path
  19578. ws::WebSocketClient ws2("ws://localhost:8080");
  19579. EXPECT_FALSE(ws2.is_valid());
  19580. // Empty string
  19581. ws::WebSocketClient ws3("");
  19582. EXPECT_FALSE(ws3.is_valid());
  19583. // Missing host
  19584. ws::WebSocketClient ws4("ws://:8080/path");
  19585. EXPECT_FALSE(ws4.is_valid());
  19586. // Port number overflow — should not crash
  19587. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19588. EXPECT_FALSE(ws5.is_valid());
  19589. // Port out of range
  19590. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19591. EXPECT_FALSE(ws6.is_valid());
  19592. }
  19593. TEST(WebSocketTest, UnsupportedScheme) {
  19594. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19595. ws::WebSocketClient ws1("http://localhost:8080/path");
  19596. EXPECT_FALSE(ws1.is_valid());
  19597. ws::WebSocketClient ws2("https://localhost:8080/path");
  19598. EXPECT_FALSE(ws2.is_valid());
  19599. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19600. EXPECT_FALSE(ws3.is_valid());
  19601. #else
  19602. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19603. std::invalid_argument);
  19604. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19605. std::invalid_argument);
  19606. #endif
  19607. }
  19608. TEST(WebSocketTest, ConnectWhenInvalid) {
  19609. ws::WebSocketClient ws("not a valid url");
  19610. EXPECT_FALSE(ws.is_valid());
  19611. auto res = ws.connect();
  19612. EXPECT_FALSE(res);
  19613. EXPECT_EQ(Error::Connection, res.error());
  19614. EXPECT_EQ(-1, res.status());
  19615. }
  19616. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19617. // Grab a port that is free, then close it again so nothing listens there
  19618. Server svr;
  19619. auto port = svr.bind_to_any_port(HOST);
  19620. svr.stop();
  19621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19622. auto res = client.connect();
  19623. ASSERT_FALSE(res);
  19624. EXPECT_EQ(Error::Connection, res.error());
  19625. EXPECT_EQ(-1, res.status());
  19626. }
  19627. TEST(WebSocketTest, DefaultPort) {
  19628. ws::WebSocketClient ws1("ws://example.com/path");
  19629. EXPECT_TRUE(ws1.is_valid());
  19630. // ws:// defaults to port 80 (verified by successful parse)
  19631. #ifdef CPPHTTPLIB_SSL_ENABLED
  19632. ws::WebSocketClient ws2("wss://example.com/path");
  19633. EXPECT_TRUE(ws2.is_valid());
  19634. // wss:// defaults to port 443 (verified by successful parse)
  19635. #endif
  19636. }
  19637. TEST(WebSocketTest, IPv6LiteralAddress) {
  19638. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19639. EXPECT_TRUE(ws1.is_valid());
  19640. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19641. EXPECT_TRUE(ws2.is_valid());
  19642. }
  19643. TEST(WebSocketTest, ComplexPath) {
  19644. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19645. EXPECT_TRUE(ws1.is_valid());
  19646. ws::WebSocketClient ws2("ws://localhost:8080/");
  19647. EXPECT_TRUE(ws2.is_valid());
  19648. }
  19649. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19650. Server svr;
  19651. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19652. std::string msg;
  19653. while (ws.read(msg)) {}
  19654. });
  19655. auto port = svr.bind_to_any_port(HOST);
  19656. std::thread t([&]() { svr.listen_after_bind(); });
  19657. svr.wait_until_ready();
  19658. auto another_host = "example.com";
  19659. auto wrong_ip = "192.0.2.1";
  19660. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19661. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19662. ASSERT_TRUE(client.connect());
  19663. EXPECT_TRUE(client.is_open());
  19664. client.close();
  19665. svr.stop();
  19666. t.join();
  19667. }
  19668. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19669. Server svr;
  19670. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19671. std::string msg;
  19672. while (ws.read(msg)) {}
  19673. });
  19674. auto port = svr.bind_to_any_port(HOST);
  19675. std::thread t([&]() { svr.listen_after_bind(); });
  19676. svr.wait_until_ready();
  19677. auto wrong_ip = "192.0.2.1";
  19678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19679. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19680. client.set_connection_timeout(1);
  19681. client.set_read_timeout(1);
  19682. client.set_write_timeout(1);
  19683. EXPECT_FALSE(client.connect());
  19684. EXPECT_FALSE(client.is_open());
  19685. svr.stop();
  19686. t.join();
  19687. }
  19688. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19689. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19690. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19691. // (RFC 6761) is only a map key and the Host header value.
  19692. auto host = "target.invalid";
  19693. Server svr;
  19694. std::string received_host;
  19695. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19696. received_host = req.get_header_value("Host");
  19697. std::string msg;
  19698. while (ws.read(msg)) {}
  19699. });
  19700. auto port = svr.bind_to_any_port(HOST);
  19701. std::thread t([&]() { svr.listen_after_bind(); });
  19702. // ASSERT_* below returns from the test body, which would leave t joinable
  19703. // and make ~thread call std::terminate.
  19704. auto se = detail::scope_exit([&] {
  19705. svr.stop();
  19706. if (t.joinable()) { t.join(); }
  19707. });
  19708. svr.wait_until_ready();
  19709. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19710. std::to_string(port) + "/ws");
  19711. client.set_hostname_addr_map({{host, HOST}});
  19712. ASSERT_TRUE(client.connect());
  19713. EXPECT_TRUE(client.is_open());
  19714. client.close();
  19715. svr.stop();
  19716. t.join();
  19717. // The mapping only redirects the connection; the identity stays host_.
  19718. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19719. }
  19720. class WebSocketIntegrationTest : public ::testing::Test {
  19721. protected:
  19722. void SetUp() override {
  19723. server_ = httplib::detail::make_unique<Server>();
  19724. setup_server();
  19725. start_server();
  19726. }
  19727. void TearDown() override {
  19728. server_->stop();
  19729. if (server_thread_.joinable()) { server_thread_.join(); }
  19730. }
  19731. void setup_server() {
  19732. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19733. std::string msg;
  19734. ws::ReadResult ret;
  19735. while ((ret = ws.read(msg))) {
  19736. if (ret == ws::Binary) {
  19737. ws.send(msg.data(), msg.size());
  19738. } else {
  19739. ws.send(msg);
  19740. }
  19741. }
  19742. });
  19743. server_->WebSocket("/ws-echo-string",
  19744. [](const Request &, ws::WebSocket &ws) {
  19745. std::string msg;
  19746. while (ws.read(msg)) {
  19747. ws.send("echo: " + msg);
  19748. }
  19749. });
  19750. server_->WebSocket(
  19751. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19752. // Echo back request metadata
  19753. ws.send("path:" + req.path);
  19754. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19755. std::string msg;
  19756. while (ws.read(msg)) {}
  19757. });
  19758. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19759. std::string msg;
  19760. ws.read(msg); // wait for a message
  19761. ws.close();
  19762. });
  19763. server_->WebSocket("/ws-close-status",
  19764. [](const Request &, ws::WebSocket &ws) {
  19765. std::string msg;
  19766. ws.read(msg); // wait for a message
  19767. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19768. });
  19769. server_->WebSocket(
  19770. "/ws-subprotocol",
  19771. [](const Request &, ws::WebSocket &ws) {
  19772. std::string msg;
  19773. while (ws.read(msg)) {
  19774. ws.send(msg);
  19775. }
  19776. },
  19777. [](const std::vector<std::string> &protocols) -> std::string {
  19778. for (const auto &p : protocols) {
  19779. if (p == "graphql-ws") { return p; }
  19780. }
  19781. return "";
  19782. });
  19783. }
  19784. void start_server() {
  19785. port_ = server_->bind_to_any_port(HOST);
  19786. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19787. server_->wait_until_ready();
  19788. }
  19789. std::unique_ptr<Server> server_;
  19790. std::thread server_thread_;
  19791. int port_ = 0;
  19792. };
  19793. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19794. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19795. "/ws-echo");
  19796. ASSERT_TRUE(client.connect());
  19797. ASSERT_TRUE(client.is_open());
  19798. ASSERT_TRUE(client.send("Hello WebSocket"));
  19799. std::string msg;
  19800. EXPECT_EQ(ws::Text, client.read(msg));
  19801. EXPECT_EQ("Hello WebSocket", msg);
  19802. client.close();
  19803. }
  19804. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19805. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19806. "/ws-echo");
  19807. ASSERT_TRUE(client.connect());
  19808. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19809. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19810. std::string msg;
  19811. EXPECT_EQ(ws::Binary, client.read(msg));
  19812. EXPECT_EQ(binary_data, msg);
  19813. client.close();
  19814. }
  19815. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19817. "/ws-echo");
  19818. ASSERT_TRUE(client.connect());
  19819. for (int i = 0; i < 10; i++) {
  19820. auto text = "message " + std::to_string(i);
  19821. ASSERT_TRUE(client.send(text));
  19822. std::string msg;
  19823. ASSERT_TRUE(client.read(msg));
  19824. EXPECT_EQ(text, msg);
  19825. }
  19826. client.close();
  19827. }
  19828. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19829. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19830. "/ws-close");
  19831. ASSERT_TRUE(client.connect());
  19832. // Send a message to trigger the server to close
  19833. ASSERT_TRUE(client.send("trigger close"));
  19834. // The server will close, so read should return false
  19835. std::string msg;
  19836. EXPECT_FALSE(client.read(msg));
  19837. EXPECT_FALSE(client.is_open());
  19838. }
  19839. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19841. "/ws-echo");
  19842. ASSERT_TRUE(client.connect());
  19843. // 128KB message
  19844. std::string large_data(128 * 1024, 'X');
  19845. ASSERT_TRUE(client.send(large_data));
  19846. std::string msg;
  19847. ASSERT_TRUE(client.read(msg));
  19848. EXPECT_EQ(large_data, msg);
  19849. client.close();
  19850. }
  19851. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19852. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19853. "/ws-echo");
  19854. ASSERT_TRUE(client.connect());
  19855. const int num_threads = 4;
  19856. std::vector<std::thread> threads;
  19857. std::atomic<int> send_count{0};
  19858. for (int t = 0; t < num_threads; t++) {
  19859. threads.emplace_back([&client, &send_count, t]() {
  19860. for (int i = 0; i < 5; i++) {
  19861. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19862. if (client.send(text)) { send_count++; }
  19863. }
  19864. });
  19865. }
  19866. for (auto &th : threads) {
  19867. th.join();
  19868. }
  19869. int received = 0;
  19870. std::string msg;
  19871. while (received < send_count.load()) {
  19872. if (!client.read(msg)) { break; }
  19873. received++;
  19874. }
  19875. EXPECT_EQ(send_count.load(), received);
  19876. client.close();
  19877. }
  19878. TEST_F(WebSocketIntegrationTest, ReadString) {
  19879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19880. "/ws-echo-string");
  19881. ASSERT_TRUE(client.connect());
  19882. ASSERT_TRUE(client.send("hello"));
  19883. std::string msg;
  19884. ASSERT_TRUE(client.read(msg));
  19885. EXPECT_EQ("echo: hello", msg);
  19886. ASSERT_TRUE(client.send("world"));
  19887. ASSERT_TRUE(client.read(msg));
  19888. EXPECT_EQ("echo: world", msg);
  19889. client.close();
  19890. }
  19891. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19892. Headers headers = {{"X-Test-Header", "test-value"}};
  19893. ws::WebSocketClient client(
  19894. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19895. ASSERT_TRUE(client.connect());
  19896. std::string msg;
  19897. ASSERT_TRUE(client.read(msg));
  19898. EXPECT_EQ("path:/ws-request-info", msg);
  19899. ASSERT_TRUE(client.read(msg));
  19900. EXPECT_EQ("header:test-value", msg);
  19901. client.close();
  19902. }
  19903. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19905. "/ws-echo");
  19906. client.set_read_timeout(1, 0); // 1 second
  19907. ASSERT_TRUE(client.connect());
  19908. // Don't send anything — server echo handler waits for a message, so read()
  19909. // should time out. The connection survives it: nothing was consumed.
  19910. std::string msg;
  19911. EXPECT_EQ(client.read(msg), ws::Timeout);
  19912. EXPECT_TRUE(client.is_open());
  19913. // And it is still usable afterwards.
  19914. EXPECT_TRUE(client.send("after timeout"));
  19915. EXPECT_EQ(client.read(msg), ws::Text);
  19916. EXPECT_EQ(msg, "after timeout");
  19917. }
  19918. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19920. "/ws-echo");
  19921. client.set_read_timeout(1, 0);
  19922. ASSERT_TRUE(client.connect());
  19923. ASSERT_TRUE(client.send("first"));
  19924. std::string msg;
  19925. ASSERT_EQ(client.read(msg), ws::Text);
  19926. ASSERT_EQ(msg, "first");
  19927. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19928. // not be used with a read timeout: it would reprocess the previous message.
  19929. EXPECT_EQ(client.read(msg), ws::Timeout);
  19930. EXPECT_EQ(msg, "first");
  19931. }
  19932. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19934. "/ws-echo");
  19935. ASSERT_TRUE(client.connect());
  19936. // Setting it once the connection is open reaches the live stream, not just
  19937. // the seed for the next connect().
  19938. client.set_read_timeout(1, 0);
  19939. std::string msg;
  19940. EXPECT_EQ(client.read(msg), ws::Timeout);
  19941. EXPECT_TRUE(client.is_open());
  19942. }
  19943. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19945. "/ws-echo");
  19946. client.set_read_timeout(5, 0);
  19947. ASSERT_TRUE(client.connect());
  19948. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19949. // The server should reject it and close the connection.
  19950. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19951. client.send(oversized);
  19952. // The server's read() should have failed due to payload limit,
  19953. // so our read() should return false (connection closed).
  19954. std::string msg;
  19955. EXPECT_FALSE(client.read(msg));
  19956. }
  19957. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19959. "/ws-echo");
  19960. client.set_read_timeout(10, 0);
  19961. ASSERT_TRUE(client.connect());
  19962. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19963. // This should succeed.
  19964. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19965. ASSERT_TRUE(client.send(at_limit));
  19966. std::string msg;
  19967. ASSERT_TRUE(client.read(msg));
  19968. EXPECT_EQ(at_limit.size(), msg.size());
  19969. client.close();
  19970. }
  19971. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19972. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19973. "/nonexistent");
  19974. auto res = client.connect();
  19975. EXPECT_FALSE(res);
  19976. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19977. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19978. EXPECT_FALSE(client.is_open());
  19979. }
  19980. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19982. "/ws-echo");
  19983. ASSERT_TRUE(client.connect());
  19984. ASSERT_TRUE(client.send(""));
  19985. std::string msg;
  19986. EXPECT_EQ(ws::Text, client.read(msg));
  19987. EXPECT_EQ("", msg);
  19988. client.close();
  19989. }
  19990. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19992. "/ws-echo");
  19993. // First connection
  19994. ASSERT_TRUE(client.connect());
  19995. ASSERT_TRUE(client.send("first"));
  19996. std::string msg;
  19997. ASSERT_TRUE(client.read(msg));
  19998. EXPECT_EQ("first", msg);
  19999. client.close();
  20000. EXPECT_FALSE(client.is_open());
  20001. // Reconnect using the same client object
  20002. ASSERT_TRUE(client.connect());
  20003. ASSERT_TRUE(client.is_open());
  20004. ASSERT_TRUE(client.send("second"));
  20005. ASSERT_TRUE(client.read(msg));
  20006. EXPECT_EQ("second", msg);
  20007. client.close();
  20008. }
  20009. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20010. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20011. "/ws-close-status");
  20012. ASSERT_TRUE(client.connect());
  20013. // Trigger the server to close with GoingAway status
  20014. ASSERT_TRUE(client.send("trigger"));
  20015. // read() should return false after receiving the close frame
  20016. std::string msg;
  20017. EXPECT_FALSE(client.read(msg));
  20018. EXPECT_FALSE(client.is_open());
  20019. }
  20020. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20021. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20022. "/ws-echo");
  20023. ASSERT_TRUE(client.connect());
  20024. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20025. EXPECT_FALSE(client.is_open());
  20026. }
  20027. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20028. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20029. ws::WebSocketClient client(
  20030. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20031. ASSERT_TRUE(client.connect());
  20032. // Server should have selected graphql-ws
  20033. EXPECT_EQ("graphql-ws", client.subprotocol());
  20034. client.close();
  20035. }
  20036. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20037. Headers headers;
  20038. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20039. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20040. ws::WebSocketClient client(
  20041. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20042. ASSERT_TRUE(client.connect());
  20043. // The offer on the second field line counts too, so graphql-ws is selected
  20044. EXPECT_EQ("graphql-ws", client.subprotocol());
  20045. client.close();
  20046. }
  20047. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20048. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20049. ws::WebSocketClient client(
  20050. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20051. ASSERT_TRUE(client.connect());
  20052. // Server should not have selected any subprotocol
  20053. EXPECT_TRUE(client.subprotocol().empty());
  20054. client.close();
  20055. }
  20056. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20057. // Connect without requesting any subprotocol
  20058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20059. "/ws-subprotocol");
  20060. ASSERT_TRUE(client.connect());
  20061. EXPECT_TRUE(client.subprotocol().empty());
  20062. client.close();
  20063. }
  20064. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20065. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20066. "/ws-echo");
  20067. client.set_tcp_nodelay(true);
  20068. client.set_connection_timeout(3, 0);
  20069. bool socket_options_called = false;
  20070. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20071. ASSERT_TRUE(client.connect());
  20072. ASSERT_TRUE(client.is_open());
  20073. EXPECT_TRUE(socket_options_called);
  20074. ASSERT_TRUE(client.send("hello"));
  20075. std::string msg;
  20076. auto result = client.read(msg);
  20077. EXPECT_EQ(result, ws::ReadResult::Text);
  20078. EXPECT_EQ(msg, "hello");
  20079. client.close();
  20080. }
  20081. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20083. "/ws-echo");
  20084. client.set_connection_timeout(std::chrono::seconds(3));
  20085. client.set_write_timeout(std::chrono::seconds(3));
  20086. // A sub-second remainder exercises the seconds/microseconds split.
  20087. client.set_read_timeout(std::chrono::milliseconds(1500));
  20088. ASSERT_TRUE(client.connect());
  20089. auto start = std::chrono::steady_clock::now();
  20090. std::string msg;
  20091. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20092. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20093. std::chrono::steady_clock::now() - start)
  20094. .count();
  20095. // Above 1s so that dropping the microseconds half of the split fails here.
  20096. // Ignoring the setter altogether would not reach this line at all: a client
  20097. // waits forever by default.
  20098. EXPECT_GE(elapsed, 1400);
  20099. EXPECT_LT(elapsed, 30000);
  20100. }
  20101. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20102. Server svr;
  20103. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20104. if (!req.has_header("Authorization")) {
  20105. res.status = StatusCode::Unauthorized_401;
  20106. res.set_content("Unauthorized", "text/plain");
  20107. return Server::HandlerResponse::Handled;
  20108. }
  20109. return Server::HandlerResponse::Unhandled;
  20110. });
  20111. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20112. std::string msg;
  20113. while (ws.read(msg)) {
  20114. ws.send(msg);
  20115. }
  20116. });
  20117. auto port = svr.bind_to_any_port("localhost");
  20118. std::thread t([&]() { svr.listen_after_bind(); });
  20119. svr.wait_until_ready();
  20120. // Without Authorization header - should be rejected before upgrade
  20121. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20122. EXPECT_FALSE(client1.connect());
  20123. // The rejection is framed like any other HTTP response
  20124. {
  20125. Client cli("localhost", port);
  20126. Headers headers = {{"Upgrade", "websocket"},
  20127. {"Connection", "Upgrade"},
  20128. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20129. {"Sec-WebSocket-Version", "13"}};
  20130. auto res = cli.Get("/ws", headers);
  20131. ASSERT_TRUE(res);
  20132. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20133. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20134. EXPECT_EQ("Unauthorized", res->body);
  20135. }
  20136. // With Authorization header - should succeed
  20137. Headers headers = {{"Authorization", "Bearer token123"}};
  20138. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20139. headers);
  20140. ASSERT_TRUE(client2.connect());
  20141. ASSERT_TRUE(client2.send("hello"));
  20142. std::string msg;
  20143. ASSERT_TRUE(client2.read(msg));
  20144. EXPECT_EQ("hello", msg);
  20145. client2.close();
  20146. svr.stop();
  20147. t.join();
  20148. }
  20149. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20150. Server svr;
  20151. std::atomic<int> pre_request_calls{0};
  20152. std::atomic<bool> route_matched{false};
  20153. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20154. pre_request_calls++;
  20155. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20156. if (req.get_header_value("Authorization") != "Bearer token123") {
  20157. res.status = StatusCode::Unauthorized_401;
  20158. res.set_content("Unauthorized", "text/plain");
  20159. return Server::HandlerResponse::Handled;
  20160. }
  20161. return Server::HandlerResponse::Unhandled;
  20162. });
  20163. std::atomic<bool> handler_called{false};
  20164. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20165. handler_called = true;
  20166. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20167. });
  20168. auto port = svr.bind_to_any_port("localhost");
  20169. std::thread t([&]() { svr.listen_after_bind(); });
  20170. svr.wait_until_ready();
  20171. // Without Authorization header - should be rejected before upgrade
  20172. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20173. "/ws/1");
  20174. EXPECT_FALSE(client1.connect());
  20175. EXPECT_FALSE(handler_called);
  20176. EXPECT_EQ(1, pre_request_calls);
  20177. EXPECT_TRUE(route_matched);
  20178. // The rejection is an ordinary HTTP response, not a protocol switch
  20179. {
  20180. Client cli("localhost", port);
  20181. Headers headers = {{"Upgrade", "websocket"},
  20182. {"Connection", "Upgrade"},
  20183. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20184. {"Sec-WebSocket-Version", "13"}};
  20185. auto res = cli.Get("/ws/1", headers);
  20186. ASSERT_TRUE(res);
  20187. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20188. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20189. EXPECT_EQ("Unauthorized", res->body);
  20190. }
  20191. EXPECT_FALSE(handler_called);
  20192. // With Authorization header - should succeed
  20193. Headers headers = {{"Authorization", "Bearer token123"}};
  20194. ws::WebSocketClient client2(
  20195. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20196. ASSERT_TRUE(client2.connect());
  20197. std::string msg;
  20198. ASSERT_TRUE(client2.read(msg));
  20199. EXPECT_EQ("/ws/:id 2", msg);
  20200. EXPECT_TRUE(handler_called);
  20201. client2.close();
  20202. svr.stop();
  20203. t.join();
  20204. }
  20205. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20206. Server svr;
  20207. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20208. // A read timeout is how a handler gets control back. Without it, a handler
  20209. // parked in read() can never write on the connection it is reading.
  20210. ws.set_read_timeout(std::chrono::milliseconds(100));
  20211. std::string msg;
  20212. while (ws.is_open()) {
  20213. auto r = ws.read(msg);
  20214. if (r == httplib::ws::Timeout) {
  20215. ws.send("tick");
  20216. continue;
  20217. }
  20218. if (r == httplib::ws::Fail) { break; }
  20219. ws.send(msg);
  20220. }
  20221. });
  20222. auto port = svr.bind_to_any_port("localhost");
  20223. std::thread t([&]() { svr.listen_after_bind(); });
  20224. svr.wait_until_ready();
  20225. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20226. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20227. ASSERT_TRUE(client.connect());
  20228. // The client sends nothing, so anything it receives came out of the
  20229. // handler's timeout path.
  20230. std::string msg;
  20231. ASSERT_EQ(client.read(msg), ws::Text);
  20232. EXPECT_EQ("tick", msg);
  20233. client.close();
  20234. svr.stop();
  20235. t.join();
  20236. }
  20237. // Stream::read may return fewer bytes than asked for. This is that contract at
  20238. // its worst -- one byte per call -- which is what a frame header straddling a
  20239. // read buffer's boundary looks like to the frame parser.
  20240. class WsByteAtATimeStream : public Stream {
  20241. public:
  20242. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20243. bool is_readable() const override { return true; }
  20244. bool wait_readable() const override { return true; }
  20245. bool wait_writable() const override { return true; }
  20246. ssize_t read(char *ptr, size_t size) override {
  20247. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20248. *ptr = data_[pos_++];
  20249. return 1;
  20250. }
  20251. ssize_t write(const char *, size_t size) override {
  20252. return static_cast<ssize_t>(size);
  20253. }
  20254. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20255. ip = "127.0.0.1";
  20256. port = 0;
  20257. }
  20258. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20259. ip = "127.0.0.1";
  20260. port = 0;
  20261. }
  20262. socket_t socket() const override { return INVALID_SOCKET; }
  20263. time_t duration() const override { return 0; }
  20264. private:
  20265. std::string data_;
  20266. size_t pos_ = 0;
  20267. };
  20268. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20269. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20270. // length and the mask key are all multi-byte fields here. Each used to be
  20271. // read with a single read() call, which fails as soon as one is split.
  20272. std::string body(200, 'x');
  20273. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20274. std::string frame;
  20275. frame += static_cast<char>(0x81); // FIN + Text
  20276. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20277. frame += static_cast<char>(body.size() >> 8);
  20278. frame += static_cast<char>(body.size() & 0xff);
  20279. for (size_t i = 0; i < 4; i++) {
  20280. frame += static_cast<char>(mask[i]);
  20281. }
  20282. for (size_t i = 0; i < body.size(); i++) {
  20283. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20284. }
  20285. WsByteAtATimeStream strm(frame);
  20286. ws::Opcode opcode;
  20287. std::string payload;
  20288. bool fin = false;
  20289. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20290. /*expect_masked=*/true, 1024),
  20291. ws::impl::FrameRead::Ok);
  20292. EXPECT_TRUE(fin);
  20293. EXPECT_EQ(opcode, ws::Opcode::Text);
  20294. EXPECT_EQ(payload, body);
  20295. }
  20296. TEST(WebSocketTest, QueryStringInHandshake) {
  20297. Server svr;
  20298. std::mutex mtx;
  20299. std::string received_target;
  20300. std::string received_token;
  20301. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20302. {
  20303. std::lock_guard<std::mutex> lock(mtx);
  20304. received_target = req.target;
  20305. if (req.has_param("token")) {
  20306. received_token = req.get_param_value("token");
  20307. }
  20308. }
  20309. std::string msg;
  20310. while (ws.read(msg)) {
  20311. ws.send(msg);
  20312. }
  20313. });
  20314. auto port = svr.bind_to_any_port("localhost");
  20315. std::thread t([&]() { svr.listen_after_bind(); });
  20316. svr.wait_until_ready();
  20317. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20318. "/ws?token=ABC&session=123");
  20319. ASSERT_TRUE(client.connect());
  20320. // Round-trip ensures the handler has run and captured the request.
  20321. ASSERT_TRUE(client.send("hello"));
  20322. std::string msg;
  20323. ASSERT_TRUE(client.read(msg));
  20324. EXPECT_EQ("hello", msg);
  20325. client.close();
  20326. {
  20327. std::lock_guard<std::mutex> lock(mtx);
  20328. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20329. EXPECT_EQ("ABC", received_token);
  20330. }
  20331. svr.stop();
  20332. t.join();
  20333. }
  20334. // Run a handshake against a throwaway server and hand the request the server
  20335. // received back to the caller, so tests can assert on the headers the client
  20336. // actually put on the wire.
  20337. static void capture_websocket_handshake_request(
  20338. const Headers &client_headers,
  20339. std::function<void(const Request &, int port)> verify) {
  20340. Server svr;
  20341. std::mutex mtx;
  20342. Request received;
  20343. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20344. {
  20345. std::lock_guard<std::mutex> lock(mtx);
  20346. received = req;
  20347. }
  20348. std::string msg;
  20349. while (ws.read(msg)) {
  20350. ws.send(msg);
  20351. }
  20352. });
  20353. auto port = svr.bind_to_any_port("localhost");
  20354. std::thread t([&]() { svr.listen_after_bind(); });
  20355. auto se = detail::scope_exit([&] {
  20356. svr.stop();
  20357. t.join();
  20358. });
  20359. svr.wait_until_ready();
  20360. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20361. client_headers);
  20362. ASSERT_TRUE(client.connect());
  20363. ASSERT_TRUE(client.send("hello"));
  20364. std::string msg;
  20365. ASSERT_TRUE(client.read(msg));
  20366. client.close();
  20367. {
  20368. std::lock_guard<std::mutex> lock(mtx);
  20369. verify(received, port);
  20370. }
  20371. }
  20372. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20373. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20374. // Non-default port must be present in the Host header. Default ports
  20375. // (80/443) are omitted; that logic is covered by
  20376. // MakeHostAndPortStringTest.
  20377. EXPECT_EQ("localhost:" + std::to_string(port),
  20378. req.get_header_value("Host"));
  20379. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20380. req.get_header_value("User-Agent"));
  20381. EXPECT_FALSE(req.has_header("Accept"));
  20382. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20383. EXPECT_FALSE(req.has_header("Content-Length"));
  20384. });
  20385. }
  20386. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20387. capture_websocket_handshake_request(
  20388. {{"Host", "example.com"},
  20389. {"User-Agent", "custom-agent"},
  20390. {"X-Custom", "value"}},
  20391. [](const Request &req, int) {
  20392. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20393. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20394. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20395. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20396. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20397. });
  20398. }
  20399. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20400. capture_websocket_handshake_request(
  20401. {{"Upgrade", "bogus"},
  20402. {"Connection", "close"},
  20403. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20404. {"Sec-WebSocket-Version", "8"}},
  20405. [](const Request &req, int) {
  20406. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20407. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20408. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20409. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20410. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20411. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20412. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20413. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20414. req.get_header_value("Sec-WebSocket-Key"));
  20415. });
  20416. }
  20417. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20418. // A header the client refuses to send must abort the handshake before any
  20419. // part of it reaches the wire; a lone request line would otherwise sit in
  20420. // the peer's buffer as a truncated request.
  20421. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20422. ASSERT_NE(INVALID_SOCKET, srv);
  20423. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20424. sockaddr_in addr{};
  20425. addr.sin_family = AF_INET;
  20426. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20427. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20428. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20429. ASSERT_EQ(0, ::listen(srv, 1));
  20430. sockaddr_in bound{};
  20431. socklen_t bound_len = sizeof(bound);
  20432. ASSERT_EQ(
  20433. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20434. auto port = ntohs(bound.sin_port);
  20435. ssize_t received = -1;
  20436. std::thread t([&] {
  20437. // Bound every blocking call so a regression fails the test with a bad
  20438. // value instead of hanging the suite.
  20439. fd_set rfds;
  20440. FD_ZERO(&rfds);
  20441. FD_SET(srv, &rfds);
  20442. timeval tv{5, 0};
  20443. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20444. 0) {
  20445. return;
  20446. }
  20447. sockaddr_in cli_addr{};
  20448. socklen_t cli_len = sizeof(cli_addr);
  20449. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20450. if (cli == INVALID_SOCKET) { return; }
  20451. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20452. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20453. char buf[4096];
  20454. received = ::recv(cli, buf, sizeof(buf), 0);
  20455. });
  20456. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20457. // connect() has already shut the socket down by the time it returns false,
  20458. // so the peer sees EOF without waiting for the client to be destroyed.
  20459. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20460. {{"X-Bad", "a\r\nInjected: 1"}});
  20461. EXPECT_FALSE(client.connect());
  20462. t.join();
  20463. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20464. EXPECT_EQ(0, received);
  20465. }
  20466. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20467. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20468. // contains "upgrade" as a substring is a different token and must not
  20469. // start a WebSocket handshake.
  20470. auto make_request = [](const std::vector<std::string> &connection_values) {
  20471. Request req;
  20472. req.method = "GET";
  20473. req.headers.emplace("Upgrade", "websocket");
  20474. for (const auto &value : connection_values) {
  20475. req.headers.emplace("Connection", value);
  20476. }
  20477. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20478. req.headers.emplace("Sec-WebSocket-Version", "13");
  20479. return req;
  20480. };
  20481. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20482. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20483. EXPECT_TRUE(
  20484. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20485. EXPECT_TRUE(
  20486. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20487. EXPECT_TRUE(
  20488. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20489. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20490. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20491. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20492. EXPECT_FALSE(
  20493. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20494. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20495. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20496. }
  20497. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20498. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20499. // asks recipients to match each protocol-name case-insensitively, and RFC
  20500. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20501. // client naming websocket alongside another protocol, or on a second field
  20502. // line, is offering websocket; a value that merely contains "websocket" as a
  20503. // substring is a different protocol name and is not.
  20504. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20505. Request req;
  20506. req.method = "GET";
  20507. for (const auto &value : upgrade_values) {
  20508. req.headers.emplace("Upgrade", value);
  20509. }
  20510. req.headers.emplace("Connection", "Upgrade");
  20511. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20512. req.headers.emplace("Sec-WebSocket-Version", "13");
  20513. return req;
  20514. };
  20515. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20516. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20517. EXPECT_TRUE(
  20518. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20519. EXPECT_TRUE(
  20520. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20521. EXPECT_TRUE(
  20522. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20523. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20524. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20525. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20526. EXPECT_FALSE(
  20527. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20528. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20529. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20530. }
  20531. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20532. Server svr;
  20533. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20534. auto port = svr.bind_to_any_port("localhost");
  20535. std::thread t([&]() { svr.listen_after_bind(); });
  20536. auto se = detail::scope_exit([&] {
  20537. svr.stop();
  20538. t.join();
  20539. });
  20540. svr.wait_until_ready();
  20541. Headers headers = {{"Upgrade", "websocket"},
  20542. {"Connection", "notupgrade"},
  20543. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20544. {"Sec-WebSocket-Version", "13"}};
  20545. Client cli("localhost", port);
  20546. auto res = cli.Get("/ws", headers);
  20547. // The route exists only as a WebSocket route, so a request that fails the
  20548. // handshake check falls through to ordinary routing.
  20549. ASSERT_TRUE(res);
  20550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20551. }
  20552. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20553. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20554. // Connection value is the only thing left for the client to reject.
  20555. Server svr;
  20556. svr.Get("/ws", [](const Request &req, Response &res) {
  20557. res.status = StatusCode::SwitchingProtocol_101;
  20558. res.set_header("Upgrade", "websocket");
  20559. res.set_header("Connection", "notupgrade");
  20560. res.set_header("Sec-WebSocket-Accept",
  20561. detail::websocket_accept_key(
  20562. req.get_header_value("Sec-WebSocket-Key")));
  20563. });
  20564. auto port = svr.bind_to_any_port("localhost");
  20565. std::thread t([&]() { svr.listen_after_bind(); });
  20566. auto se = detail::scope_exit([&] {
  20567. svr.stop();
  20568. t.join();
  20569. });
  20570. svr.wait_until_ready();
  20571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20572. auto res = client.connect();
  20573. EXPECT_FALSE(res);
  20574. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20575. EXPECT_FALSE(client.is_open());
  20576. }
  20577. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20578. // The socket path doubles as the URL host, so it must not contain '/'.
  20579. const char *shard = getenv("GTEST_SHARD_INDEX");
  20580. const std::string sock_path =
  20581. shard ? std::string("httplib-ws-") + shard + ".sock"
  20582. : std::string("httplib-ws.sock");
  20583. std::remove(sock_path.c_str());
  20584. Server svr;
  20585. std::mutex mtx;
  20586. std::string received_host;
  20587. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20588. {
  20589. std::lock_guard<std::mutex> lock(mtx);
  20590. received_host = req.get_header_value("Host");
  20591. }
  20592. std::string msg;
  20593. while (ws.read(msg)) {
  20594. ws.send(msg);
  20595. }
  20596. });
  20597. svr.set_address_family(AF_UNIX);
  20598. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20599. auto se = detail::scope_exit([&] {
  20600. svr.stop();
  20601. t.join();
  20602. std::remove(sock_path.c_str());
  20603. });
  20604. svr.wait_until_ready();
  20605. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20606. client.set_address_family(AF_UNIX);
  20607. ASSERT_TRUE(client.connect());
  20608. ASSERT_TRUE(client.send("hello"));
  20609. std::string msg;
  20610. ASSERT_TRUE(client.read(msg));
  20611. client.close();
  20612. {
  20613. std::lock_guard<std::mutex> lock(mtx);
  20614. // There is no host:port for a Unix socket, so the same "localhost"
  20615. // placeholder the HTTP client uses is expected.
  20616. EXPECT_EQ("localhost", received_host);
  20617. }
  20618. }
  20619. // Two threads must never parse WebSocket frames from the same stream.
  20620. // close() used to read the peer's Close reply with its own frame read, so it
  20621. // raced a reader thread that was in the middle of a payload: the payload loop
  20622. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20623. // so bytes taken by close() were replaced with bytes from further along the
  20624. // stream. The message kept its length and silently changed content.
  20625. //
  20626. // The raw peer below sends a frame header plus part of the payload, waits for
  20627. // the handler to call close(), and only then sends the rest. Whichever thread
  20628. // would win the race for those bytes, the message must arrive intact, because
  20629. // close() must not touch the stream while read() owns it.
  20630. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20631. #ifndef _WIN32
  20632. signal(SIGPIPE, SIG_IGN);
  20633. #endif
  20634. const size_t payload_len = 120; // fits the 7-bit length field
  20635. const size_t prefix_len = 8;
  20636. const int attempts = 8;
  20637. std::string expected(payload_len, '\0');
  20638. for (size_t i = 0; i < payload_len; i++) {
  20639. expected[i] = static_cast<char>('a' + i % 26);
  20640. }
  20641. std::atomic<bool> peer_stalled{false};
  20642. std::atomic<bool> handler_done{false};
  20643. std::mutex received_mutex;
  20644. std::vector<std::string> received;
  20645. // Bound every wait, so a regression fails the test instead of hanging the
  20646. // suite.
  20647. auto wait_for = [](const std::atomic<bool> &flag) {
  20648. for (int i = 0; i < 500 && !flag; i++) {
  20649. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20650. }
  20651. };
  20652. Server svr;
  20653. svr.set_websocket_ping_interval(0);
  20654. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20655. std::thread reader([&]() {
  20656. std::string msg;
  20657. while (ws.read(msg)) {
  20658. std::lock_guard<std::mutex> guard(received_mutex);
  20659. received.push_back(msg);
  20660. }
  20661. });
  20662. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20663. // inside read_websocket_frame() when close() runs.
  20664. wait_for(peer_stalled);
  20665. ws.close();
  20666. reader.join();
  20667. handler_done = true;
  20668. });
  20669. auto port = svr.bind_to_any_port("127.0.0.1");
  20670. std::thread t([&]() { svr.listen_after_bind(); });
  20671. auto se = detail::scope_exit([&] {
  20672. svr.stop();
  20673. t.join();
  20674. });
  20675. svr.wait_until_ready();
  20676. auto send_bytes = [](socket_t s, const std::string &data) {
  20677. #ifdef _WIN32
  20678. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20679. #else
  20680. auto n = ::send(s, data.data(), data.size(), 0);
  20681. #endif
  20682. return n == static_cast<decltype(n)>(data.size());
  20683. };
  20684. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20685. // Every length used here fits the 7-bit length field.
  20686. auto masked_header = [](uint8_t first_byte, size_t len) {
  20687. std::string h;
  20688. h += static_cast<char>(first_byte);
  20689. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20690. h.append(4, '\0'); // mask key
  20691. return h;
  20692. };
  20693. for (int attempt = 0; attempt < attempts; attempt++) {
  20694. peer_stalled = false;
  20695. handler_done = false;
  20696. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20697. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20698. auto se_sock = detail::scope_exit([&] {
  20699. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20700. });
  20701. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20702. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20703. sockaddr_in addr{};
  20704. addr.sin_family = AF_INET;
  20705. addr.sin_port = htons(static_cast<uint16_t>(port));
  20706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20707. ASSERT_EQ(
  20708. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20709. << "attempt " << attempt;
  20710. ASSERT_TRUE(send_bytes(sock,
  20711. "GET /ws HTTP/1.1\r\n"
  20712. "Host: 127.0.0.1\r\n"
  20713. "Upgrade: websocket\r\n"
  20714. "Connection: Upgrade\r\n"
  20715. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20716. "Sec-WebSocket-Version: 13\r\n"
  20717. "\r\n"))
  20718. << "attempt " << attempt;
  20719. std::string response;
  20720. while (response.find("\r\n\r\n") == std::string::npos) {
  20721. char buf[512];
  20722. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20723. if (n <= 0) { break; }
  20724. response.append(buf, static_cast<size_t>(n));
  20725. }
  20726. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20727. << "attempt " << attempt;
  20728. // Send the header of a Binary message but only the first prefix_len bytes
  20729. // of its payload, leaving the reader thread stalled inside the payload.
  20730. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20731. expected.substr(0, prefix_len)))
  20732. << "attempt " << attempt;
  20733. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20734. peer_stalled = true;
  20735. // Let close() send its Close frame and park in its own read before the
  20736. // rest of the payload arrives, so both threads are waiting for it.
  20737. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20738. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20739. close_frame += static_cast<char>(0x03); // status 1000
  20740. close_frame += static_cast<char>(0xE8);
  20741. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20742. << "attempt " << attempt;
  20743. // Closing the peer releases the reader thread even on the buggy path,
  20744. // where it waits for bytes another thread already consumed.
  20745. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20746. detail::close_socket(sock);
  20747. sock = INVALID_SOCKET;
  20748. wait_for(handler_done);
  20749. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20750. }
  20751. std::lock_guard<std::mutex> guard(received_mutex);
  20752. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20753. << "a message in flight when close() ran was dropped";
  20754. for (size_t i = 0; i < received.size(); i++) {
  20755. EXPECT_EQ(expected, received[i]) << "message " << i;
  20756. }
  20757. }
  20758. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20759. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20760. protected:
  20761. void SetUp() override {
  20762. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20763. SERVER_PRIVATE_KEY_FILE);
  20764. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20765. std::string msg;
  20766. ws::ReadResult ret;
  20767. while ((ret = ws.read(msg))) {
  20768. if (ret == ws::Binary) {
  20769. ws.send(msg.data(), msg.size());
  20770. } else {
  20771. ws.send(msg);
  20772. }
  20773. }
  20774. });
  20775. port_ = server_->bind_to_any_port(HOST);
  20776. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20777. server_->wait_until_ready();
  20778. }
  20779. void TearDown() override {
  20780. server_->stop();
  20781. if (server_thread_.joinable()) { server_thread_.join(); }
  20782. }
  20783. std::unique_ptr<SSLServer> server_;
  20784. std::thread server_thread_;
  20785. int port_ = 0;
  20786. };
  20787. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20788. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20789. "/ws-echo");
  20790. client.enable_server_certificate_verification(false);
  20791. ASSERT_TRUE(client.connect());
  20792. ASSERT_TRUE(client.is_open());
  20793. ASSERT_TRUE(client.send("Hello WSS"));
  20794. std::string msg;
  20795. EXPECT_EQ(ws::Text, client.read(msg));
  20796. EXPECT_EQ("Hello WSS", msg);
  20797. client.close();
  20798. }
  20799. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20800. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20801. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20802. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20803. // client (without calling close() first) is the only path that runs
  20804. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20805. // bug exactly.
  20806. //
  20807. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20808. // when linked against an instrumented libssl; run under Valgrind to catch it
  20809. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20810. // suite (the freed session otherwise stalls on the close handshake) — this test
  20811. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20812. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20813. {
  20814. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20815. "/ws-echo");
  20816. client.enable_server_certificate_verification(false);
  20817. client.set_read_timeout(2, 0);
  20818. client.set_write_timeout(2, 0);
  20819. ASSERT_TRUE(client.connect());
  20820. ASSERT_TRUE(client.is_open());
  20821. ASSERT_TRUE(client.send("still open"));
  20822. // Intentionally do NOT call client.close(): leaving scope runs
  20823. // shutdown_and_close() with the WebSocket still open, which must send the
  20824. // close frame while the TLS session is still alive.
  20825. }
  20826. }
  20827. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20828. // shutdown_and_close() at the start of connect(), reproducing the same
  20829. // use-after-free within the test body rather than at scope exit. The second
  20830. // connect must succeed and echo, proving the close handshake ran over a live
  20831. // session. See the note above about memory-tool requirements.
  20832. TEST_F(WebSocketSSLIntegrationTest,
  20833. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20834. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20835. "/ws-echo");
  20836. client.enable_server_certificate_verification(false);
  20837. client.set_read_timeout(2, 0);
  20838. client.set_write_timeout(2, 0);
  20839. ASSERT_TRUE(client.connect());
  20840. ASSERT_TRUE(client.is_open());
  20841. ASSERT_TRUE(client.send("still open"));
  20842. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20843. // the still-open connection, which must not touch a freed TLS session.
  20844. ASSERT_TRUE(client.connect());
  20845. ASSERT_TRUE(client.is_open());
  20846. ASSERT_TRUE(client.send("after reconnect"));
  20847. std::string msg;
  20848. EXPECT_EQ(ws::Text, client.read(msg));
  20849. EXPECT_EQ("after reconnect", msg);
  20850. client.close();
  20851. }
  20852. #endif
  20853. #ifdef CPPHTTPLIB_SSL_ENABLED
  20854. class WebSocketSSLCATest : public ::testing::Test {
  20855. protected:
  20856. void SetUp() override {
  20857. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20858. SERVER_PRIVATE_KEY_FILE);
  20859. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20860. std::string msg;
  20861. while (ws.read(msg)) {
  20862. ws.send(msg);
  20863. }
  20864. });
  20865. port_ = server_->bind_to_any_port("127.0.0.1");
  20866. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20867. server_->wait_until_ready();
  20868. }
  20869. void TearDown() override {
  20870. server_->stop();
  20871. if (server_thread_.joinable()) { server_thread_.join(); }
  20872. }
  20873. std::string url() const {
  20874. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20875. }
  20876. std::unique_ptr<SSLServer> server_;
  20877. std::thread server_thread_;
  20878. int port_ = 0;
  20879. };
  20880. // A custom CA loaded as PEM verifies the server with full certificate
  20881. // verification enabled
  20882. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20883. ws::WebSocketClient client(url());
  20884. std::string cert;
  20885. read_file(SERVER_CERT2_FILE, cert);
  20886. client.load_ca_cert_store(cert.c_str(), cert.size());
  20887. ASSERT_TRUE(client.connect());
  20888. ASSERT_TRUE(client.send("hello"));
  20889. std::string msg;
  20890. EXPECT_EQ(ws::Text, client.read(msg));
  20891. EXPECT_EQ("hello", msg);
  20892. client.close();
  20893. }
  20894. // A custom CA that does not cover the server must fail verification (the
  20895. // custom CA is exclusive; system certs are not loaded alongside it)
  20896. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20897. ws::WebSocketClient client(url());
  20898. std::string cert;
  20899. read_file(CLIENT_CA_CERT_FILE, cert);
  20900. client.load_ca_cert_store(cert.c_str(), cert.size());
  20901. auto res = client.connect();
  20902. ASSERT_FALSE(res);
  20903. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20904. EXPECT_EQ(-1, res.status());
  20905. EXPECT_NE(0u, res.ssl_backend_error());
  20906. }
  20907. // The same CA as a file path rather than PEM in memory
  20908. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20909. ws::WebSocketClient client(url());
  20910. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20911. ASSERT_TRUE(client.connect());
  20912. ASSERT_TRUE(client.send("hello"));
  20913. std::string msg;
  20914. EXPECT_EQ(ws::Text, client.read(msg));
  20915. EXPECT_EQ("hello", msg);
  20916. client.close();
  20917. }
  20918. // ...and a CA file that does not cover the server still fails, so it is the
  20919. // path above that decides the outcome
  20920. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20921. ws::WebSocketClient client(url());
  20922. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20923. ASSERT_FALSE(client.connect());
  20924. }
  20925. // Regression test: reconnecting with a native custom CA store used to reuse
  20926. // a store handle the previous TLS context had already freed (use-after-free
  20927. // under the OpenSSL backend). The context now lives as long as the client.
  20928. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20929. ws::WebSocketClient client(url());
  20930. std::string cert;
  20931. read_file(SERVER_CERT2_FILE, cert);
  20932. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20933. ASSERT_TRUE(client.connect());
  20934. client.close();
  20935. ASSERT_TRUE(client.connect());
  20936. ASSERT_TRUE(client.send("again"));
  20937. std::string msg;
  20938. EXPECT_EQ(ws::Text, client.read(msg));
  20939. EXPECT_EQ("again", msg);
  20940. client.close();
  20941. }
  20942. // Regression test: a certificate with a trusted chain but no identity match
  20943. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20944. // verification entirely for IP hosts, so this connection succeeded there.
  20945. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20946. // chain verification while the identity check must still fail.
  20947. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20949. ASSERT_TRUE(svr.is_valid());
  20950. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20951. std::string msg;
  20952. while (ws.read(msg)) {
  20953. ws.send(msg);
  20954. }
  20955. });
  20956. auto port = svr.bind_to_any_port("127.0.0.1");
  20957. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20958. auto se = detail::scope_exit([&] {
  20959. svr.stop();
  20960. t.join();
  20961. });
  20962. svr.wait_until_ready();
  20963. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20964. "/echo");
  20965. std::string cert;
  20966. read_file(SERVER_CERT_FILE, cert);
  20967. client.load_ca_cert_store(cert.c_str(), cert.size());
  20968. ASSERT_FALSE(client.connect());
  20969. }
  20970. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20971. // SNI, so nothing binds the host name to the TLS session. These bind the
  20972. // server to "localhost" instead, the only shape that exercises the SNI and
  20973. // hostname-verification path with certificate verification left enabled.
  20974. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20975. protected:
  20976. void Start(const char *cert_file) {
  20977. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20978. SERVER_PRIVATE_KEY_FILE);
  20979. ASSERT_TRUE(server_->is_valid());
  20980. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20981. std::string msg;
  20982. while (ws.read(msg)) {
  20983. ws.send(msg);
  20984. }
  20985. });
  20986. port_ = server_->bind_to_any_port("localhost");
  20987. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20988. server_->wait_until_ready();
  20989. }
  20990. void TearDown() override {
  20991. if (server_) { server_->stop(); }
  20992. if (server_thread_.joinable()) { server_thread_.join(); }
  20993. }
  20994. std::string url() const {
  20995. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20996. }
  20997. std::unique_ptr<SSLServer> server_;
  20998. std::thread server_thread_;
  20999. int port_ = 0;
  21000. };
  21001. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21002. // out and the connection is usable
  21003. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21004. Start(SERVER_CERT2_FILE);
  21005. ws::WebSocketClient client(url());
  21006. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21007. ASSERT_TRUE(client.connect());
  21008. ASSERT_TRUE(client.send("hello"));
  21009. std::string msg;
  21010. EXPECT_EQ(ws::Text, client.read(msg));
  21011. EXPECT_EQ("hello", msg);
  21012. client.close();
  21013. }
  21014. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21015. // while the identity check must still reject "localhost"
  21016. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21017. Start(SERVER_CERT_FILE);
  21018. ws::WebSocketClient client(url());
  21019. client.set_ca_cert_path(SERVER_CERT_FILE);
  21020. auto res = client.connect();
  21021. ASSERT_FALSE(res);
  21022. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21023. EXPECT_EQ(-1, res.status());
  21024. }
  21025. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21026. // disabled: the chain is still checked, only the identity check is skipped
  21027. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21028. Start(SERVER_CERT_FILE);
  21029. ws::WebSocketClient client(url());
  21030. client.set_ca_cert_path(SERVER_CERT_FILE);
  21031. client.enable_server_hostname_verification(false);
  21032. ASSERT_TRUE(client.connect());
  21033. ASSERT_TRUE(client.send("hello"));
  21034. std::string msg;
  21035. EXPECT_EQ(ws::Text, client.read(msg));
  21036. EXPECT_EQ("hello", msg);
  21037. client.close();
  21038. }
  21039. // A CA that did not sign the server certificate fails the chain, even though
  21040. // the name would match
  21041. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21042. Start(SERVER_CERT2_FILE);
  21043. ws::WebSocketClient client(url());
  21044. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21045. ASSERT_FALSE(client.connect());
  21046. }
  21047. // With verification disabled, neither the chain nor the name is checked
  21048. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21049. Start(SERVER_CERT_FILE);
  21050. ws::WebSocketClient client(url());
  21051. client.enable_server_certificate_verification(false);
  21052. ASSERT_TRUE(client.connect());
  21053. ASSERT_TRUE(client.send("hello"));
  21054. std::string msg;
  21055. EXPECT_EQ(ws::Text, client.read(msg));
  21056. EXPECT_EQ("hello", msg);
  21057. client.close();
  21058. }
  21059. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21060. protected:
  21061. void SetUp() override {
  21062. server_ = httplib::detail::make_unique<SSLServer>(
  21063. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21064. ASSERT_TRUE(server_->is_valid());
  21065. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21066. std::string msg;
  21067. while (ws.read(msg)) {
  21068. ws.send(msg);
  21069. }
  21070. });
  21071. port_ = server_->bind_to_any_port("localhost");
  21072. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21073. server_->wait_until_ready();
  21074. }
  21075. void TearDown() override {
  21076. server_->stop();
  21077. if (server_thread_.joinable()) { server_thread_.join(); }
  21078. }
  21079. std::string url() const {
  21080. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21081. }
  21082. void ConnectWithClientCert(const std::string &client_cert_file,
  21083. const std::string &client_private_key_file,
  21084. const char *private_key_password) {
  21085. std::string cert_pem, key_pem;
  21086. read_file(client_cert_file, cert_pem);
  21087. read_file(client_private_key_file, key_pem);
  21088. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21089. key_pem.c_str(), key_pem.size(),
  21090. private_key_password};
  21091. ws::WebSocketClient client(url(), pem);
  21092. ASSERT_TRUE(client.is_valid());
  21093. client.enable_server_certificate_verification(false);
  21094. ASSERT_TRUE(client.connect());
  21095. ASSERT_TRUE(client.send("hello"));
  21096. std::string msg;
  21097. EXPECT_EQ(ws::Text, client.read(msg));
  21098. EXPECT_EQ("hello", msg);
  21099. client.close();
  21100. }
  21101. std::unique_ptr<SSLServer> server_;
  21102. std::thread server_thread_;
  21103. int port_ = 0;
  21104. };
  21105. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21106. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21107. }
  21108. // Control for the tests above: the fixture's server really does require a
  21109. // client certificate, so it is the PEM the constructor installed that decides
  21110. // the outcome.
  21111. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21112. ws::WebSocketClient client(url());
  21113. ASSERT_TRUE(client.is_valid());
  21114. client.enable_server_certificate_verification(false);
  21115. EXPECT_FALSE(client.connect());
  21116. }
  21117. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21118. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21119. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21120. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21121. }
  21122. #endif
  21123. #if !defined(_WIN32)
  21124. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21125. auto secret_dir = std::string("./symlink_test_secret");
  21126. auto served_dir = std::string("./symlink_test_served");
  21127. auto secret_file = secret_dir + "/secret.txt";
  21128. auto symlink_path = served_dir + "/escape";
  21129. // Setup: create directories and files
  21130. mkdir(secret_dir.c_str(), 0755);
  21131. mkdir(served_dir.c_str(), 0755);
  21132. {
  21133. std::ofstream ofs(secret_file);
  21134. ofs << "SECRET_DATA";
  21135. }
  21136. // Create symlink using absolute path so it resolves correctly
  21137. #ifdef PATH_MAX
  21138. char abs_secret[PATH_MAX];
  21139. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21140. #else
  21141. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21142. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21143. ASSERT_NE(nullptr, abs_secret);
  21144. #endif
  21145. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21146. auto se = detail::scope_exit([&] {
  21147. unlink(symlink_path.c_str());
  21148. unlink(secret_file.c_str());
  21149. rmdir(served_dir.c_str());
  21150. rmdir(secret_dir.c_str());
  21151. });
  21152. Server svr;
  21153. svr.set_mount_point("/", served_dir);
  21154. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21155. auto se2 = detail::scope_exit([&] {
  21156. svr.stop();
  21157. listen_thread.join();
  21158. });
  21159. svr.wait_until_ready();
  21160. Client cli("localhost", PORT);
  21161. // Symlink pointing outside base dir should be blocked
  21162. auto res = cli.Get("/escape/secret.txt");
  21163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21164. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21165. }
  21166. #endif
  21167. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21168. // A GET request with Content-Length to a static file handler must have its
  21169. // body drained before the keep-alive connection is reused. Otherwise the
  21170. // unread body bytes are interpreted as the next HTTP request.
  21171. //
  21172. // The body is sent AFTER receiving the first response (as in the original
  21173. // PoC) so that the stream_line_reader cannot buffer it together with the
  21174. // headers of the first request.
  21175. Server svr;
  21176. svr.set_mount_point("/", "./www");
  21177. std::atomic<int> smuggled_count(0);
  21178. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21179. smuggled_count++;
  21180. res.set_content("oops", "text/plain");
  21181. });
  21182. auto port = svr.bind_to_any_port("localhost");
  21183. thread t = thread([&] { svr.listen_after_bind(); });
  21184. auto se = detail::scope_exit([&] {
  21185. svr.stop();
  21186. t.join();
  21187. });
  21188. svr.wait_until_ready();
  21189. auto error = Error::Success;
  21190. auto sock = detail::create_client_socket(
  21191. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21192. /*connection_timeout_sec=*/2, 0,
  21193. /*read_timeout_sec=*/2, 0,
  21194. /*write_timeout_sec=*/2, 0, std::string(), error);
  21195. ASSERT_NE(INVALID_SOCKET, sock);
  21196. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21197. // The "smuggled" request will be sent as the body of the outer GET
  21198. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21199. "Host: localhost\r\n"
  21200. "Connection: close\r\n"
  21201. "\r\n";
  21202. // Step 1: Send only the outer request headers (no body yet)
  21203. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  21204. "Host: localhost\r\n"
  21205. "Content-Length: " +
  21206. std::to_string(smuggled.size()) +
  21207. "\r\n"
  21208. "\r\n";
  21209. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  21210. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  21211. // Step 2: Read the first response (server serves file without reading body)
  21212. std::string first_response;
  21213. char buf[4096];
  21214. for (;;) {
  21215. auto n = recv(sock, buf, sizeof(buf), 0);
  21216. if (n <= 0) break;
  21217. first_response.append(buf, static_cast<size_t>(n));
  21218. // Stop once we have a complete response (headers + body)
  21219. auto hdr_end = first_response.find("\r\n\r\n");
  21220. if (hdr_end != std::string::npos) {
  21221. // Check for Content-Length to know when the body is complete
  21222. auto cl_pos = first_response.find("Content-Length:");
  21223. if (cl_pos != std::string::npos) {
  21224. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21225. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21226. auto cl = std::stoul(
  21227. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21228. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21229. } else {
  21230. break; // No Content-Length, assume headers-only response
  21231. }
  21232. }
  21233. }
  21234. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  21235. // Step 3: Now send the body, which looks like a new HTTP request.
  21236. // On a vulnerable server the keep-alive loop reads this as a second request.
  21237. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  21238. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  21239. // Step 4: Try to read a second response (should NOT exist after fix)
  21240. std::string second_response;
  21241. for (;;) {
  21242. auto n = recv(sock, buf, sizeof(buf), 0);
  21243. if (n <= 0) break;
  21244. second_response.append(buf, static_cast<size_t>(n));
  21245. }
  21246. // The smuggled request must NOT have been processed
  21247. EXPECT_EQ(0, smuggled_count.load());
  21248. }
  21249. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21250. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21251. // must be rejected with 400 Bad Request.
  21252. Server svr;
  21253. svr.Post("/test", [&](const Request &, Response &res) {
  21254. res.set_content("ok", "text/plain");
  21255. });
  21256. thread t = thread([&] { svr.listen(HOST, PORT); });
  21257. auto se = detail::scope_exit([&] {
  21258. svr.stop();
  21259. t.join();
  21260. ASSERT_FALSE(svr.is_running());
  21261. });
  21262. svr.wait_until_ready();
  21263. // Exact "chunked"
  21264. {
  21265. auto req = "POST /test HTTP/1.1\r\n"
  21266. "Host: localhost\r\n"
  21267. "Content-Length: 5\r\n"
  21268. "Transfer-Encoding: chunked\r\n"
  21269. "Connection: close\r\n"
  21270. "\r\n"
  21271. "hello";
  21272. std::string response;
  21273. ASSERT_TRUE(send_request(1, req, &response));
  21274. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21275. response.substr(0, response.find("\r\n")));
  21276. }
  21277. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21278. {
  21279. auto req = "POST /test HTTP/1.1\r\n"
  21280. "Host: localhost\r\n"
  21281. "Content-Length: 5\r\n"
  21282. "Transfer-Encoding: gzip, chunked\r\n"
  21283. "Connection: close\r\n"
  21284. "\r\n"
  21285. "hello";
  21286. std::string response;
  21287. ASSERT_TRUE(send_request(1, req, &response));
  21288. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21289. response.substr(0, response.find("\r\n")));
  21290. }
  21291. }
  21292. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21293. Server svr;
  21294. svr.Post("/test", [&](const Request &, Response &res) {
  21295. res.set_content("ok", "text/plain");
  21296. });
  21297. thread t = thread([&] { svr.listen(HOST, PORT); });
  21298. auto se = detail::scope_exit([&] {
  21299. svr.stop();
  21300. t.join();
  21301. ASSERT_FALSE(svr.is_running());
  21302. });
  21303. svr.wait_until_ready();
  21304. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21305. // length cannot be determined, so the server must answer 400 and close
  21306. // rather than treat the request as bodyless and leave the body in the
  21307. // socket for the next request to pick up.
  21308. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21309. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21310. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21311. std::string response;
  21312. ASSERT_TRUE(send_request(1, req, &response));
  21313. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21314. response.substr(0, response.find("\r\n")))
  21315. << transfer_encoding;
  21316. }
  21317. // RFC 9110 5.3: the codings may also be split across several
  21318. // Transfer-Encoding lines, which combine in the order they were received.
  21319. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21320. // just like the single-line "chunked, gzip" above.
  21321. {
  21322. auto req = "POST /test HTTP/1.1\r\n"
  21323. "Host: localhost\r\n"
  21324. "Transfer-Encoding: chunked\r\n"
  21325. "Transfer-Encoding: gzip\r\n"
  21326. "\r\n"
  21327. "0\r\n\r\n";
  21328. std::string response;
  21329. ASSERT_TRUE(send_request(1, req, &response));
  21330. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21331. response.substr(0, response.find("\r\n")));
  21332. }
  21333. // A sequence ending in chunked stays valid.
  21334. auto req = "POST /test HTTP/1.1\r\n"
  21335. "Host: localhost\r\n"
  21336. "Transfer-Encoding: gzip, chunked\r\n"
  21337. "Connection: close\r\n"
  21338. "\r\n"
  21339. "0\r\n\r\n";
  21340. std::string response;
  21341. ASSERT_TRUE(send_request(1, req, &response));
  21342. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21343. // ...including when it is spread over several lines.
  21344. auto split_req = "POST /test HTTP/1.1\r\n"
  21345. "Host: localhost\r\n"
  21346. "Transfer-Encoding: gzip\r\n"
  21347. "Transfer-Encoding: chunked\r\n"
  21348. "Connection: close\r\n"
  21349. "\r\n"
  21350. "0\r\n\r\n";
  21351. std::string split_response;
  21352. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21353. EXPECT_EQ("HTTP/1.1 200 OK",
  21354. split_response.substr(0, split_response.find("\r\n")));
  21355. }
  21356. // Regression for issue #2450: a DELETE without Content-Length on a
  21357. // keep-alive connection must not let the post-response drain consume the
  21358. // next request's bytes.
  21359. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21360. Server svr;
  21361. std::atomic<int> delete_count(0);
  21362. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21363. delete_count++;
  21364. res.status = StatusCode::NoContent_204;
  21365. });
  21366. auto port = svr.bind_to_any_port(HOST);
  21367. thread t = thread([&] { svr.listen_after_bind(); });
  21368. auto se = detail::scope_exit([&] {
  21369. svr.stop();
  21370. t.join();
  21371. });
  21372. svr.wait_until_ready();
  21373. auto error = Error::Success;
  21374. auto sock = detail::create_client_socket(
  21375. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21376. /*connection_timeout_sec=*/2, 0,
  21377. /*read_timeout_sec=*/2, 0,
  21378. /*write_timeout_sec=*/2, 0, std::string(), error);
  21379. ASSERT_NE(INVALID_SOCKET, sock);
  21380. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21381. auto send_request_and_read_response = [&](const std::string &req,
  21382. std::string &out) -> bool {
  21383. auto sent = send(sock, req.data(), req.size(), 0);
  21384. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21385. char buf[4096];
  21386. for (;;) {
  21387. auto n = recv(sock, buf, sizeof(buf), 0);
  21388. if (n <= 0) { return !out.empty(); }
  21389. out.append(buf, static_cast<size_t>(n));
  21390. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21391. }
  21392. };
  21393. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21394. "Host: localhost\r\n"
  21395. "\r\n";
  21396. std::string resp1;
  21397. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21398. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21399. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21400. "Host: localhost\r\n"
  21401. "Connection: close\r\n"
  21402. "\r\n";
  21403. std::string resp2;
  21404. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21405. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21406. EXPECT_EQ(2, delete_count.load());
  21407. }
  21408. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21409. Server svr;
  21410. svr.Post("/ingest", [&](const Request &, Response &res,
  21411. const ContentReader &content_reader) {
  21412. auto consumed = content_reader([](const char *, size_t) { return false; });
  21413. EXPECT_FALSE(consumed);
  21414. res.status = StatusCode::Conflict_409;
  21415. res.set_header("Connection", "close");
  21416. });
  21417. auto port = svr.bind_to_any_port(HOST);
  21418. thread t = thread([&] { svr.listen_after_bind(); });
  21419. auto se = detail::scope_exit([&] {
  21420. svr.stop();
  21421. t.join();
  21422. });
  21423. svr.wait_until_ready();
  21424. auto error = Error::Success;
  21425. auto sock = detail::create_client_socket(
  21426. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21427. /*connection_timeout_sec=*/2, 0,
  21428. /*read_timeout_sec=*/1, 0,
  21429. /*write_timeout_sec=*/2, 0, std::string(), error);
  21430. ASSERT_NE(INVALID_SOCKET, sock);
  21431. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21432. std::string request = "POST /ingest HTTP/1.1\r\n"
  21433. "Host: localhost\r\n"
  21434. "Transfer-Encoding: chunked\r\n"
  21435. "\r\n"
  21436. "4\r\n"
  21437. "data\r\n";
  21438. auto sent = send(sock, request.data(), request.size(), 0);
  21439. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21440. std::string response;
  21441. ssize_t received = 0;
  21442. do {
  21443. char buf[4096];
  21444. received = recv(sock, buf, sizeof(buf), 0);
  21445. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21446. } while (received > 0);
  21447. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21448. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21449. EXPECT_EQ(0, received);
  21450. }
  21451. namespace no_proxy_test {
  21452. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21453. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21454. // calling listen().
  21455. class ScopedServer {
  21456. public:
  21457. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21458. ~ScopedServer() {
  21459. svr_.stop();
  21460. if (th_.joinable()) { th_.join(); }
  21461. }
  21462. Server &svr() { return svr_; }
  21463. int port() const { return port_; }
  21464. void listen() {
  21465. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21466. svr_.wait_until_ready();
  21467. }
  21468. private:
  21469. Server svr_;
  21470. std::thread th_;
  21471. int port_ = 0;
  21472. };
  21473. class ProxyAndTargetServers {
  21474. public:
  21475. ProxyAndTargetServers() {
  21476. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21477. proxy_hits_++;
  21478. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21479. res.set_content("via-proxy", "text/plain");
  21480. });
  21481. target_.Get(".*", [this](const Request &req, Response &res) {
  21482. target_hits_++;
  21483. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21484. res.set_content("direct", "text/plain");
  21485. });
  21486. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21487. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21488. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21489. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21490. proxy_mock_.wait_until_ready();
  21491. target_.wait_until_ready();
  21492. }
  21493. ~ProxyAndTargetServers() {
  21494. proxy_mock_.stop();
  21495. target_.stop();
  21496. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21497. if (target_thread_.joinable()) { target_thread_.join(); }
  21498. }
  21499. Server &proxy_mock() { return proxy_mock_; }
  21500. Server &target() { return target_; }
  21501. int proxy_port() const { return proxy_port_; }
  21502. int target_port() const { return target_port_; }
  21503. int proxy_hits() const { return proxy_hits_.load(); }
  21504. int target_hits() const { return target_hits_.load(); }
  21505. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21506. void reset_counters() {
  21507. proxy_hits_ = 0;
  21508. target_hits_ = 0;
  21509. last_had_proxy_authz_ = false;
  21510. }
  21511. private:
  21512. Server proxy_mock_;
  21513. Server target_;
  21514. std::thread proxy_thread_;
  21515. std::thread target_thread_;
  21516. int proxy_port_ = 0;
  21517. int target_port_ = 0;
  21518. std::atomic<int> proxy_hits_{0};
  21519. std::atomic<int> target_hits_{0};
  21520. std::atomic<bool> last_had_proxy_authz_{false};
  21521. };
  21522. inline std::unique_ptr<Client> make_client(const std::string &host,
  21523. ProxyAndTargetServers &s) {
  21524. auto cli = detail::make_unique<Client>(host, s.target_port());
  21525. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21526. cli->set_proxy("127.0.0.1", s.proxy_port());
  21527. return cli;
  21528. }
  21529. } // namespace no_proxy_test
  21530. using no_proxy_test::make_client;
  21531. using no_proxy_test::ProxyAndTargetServers;
  21532. TEST(NoProxyTest, ExactHostnameBypasses) {
  21533. ProxyAndTargetServers s;
  21534. auto cli = make_client("example.com", s);
  21535. cli->set_no_proxy({"example.com"});
  21536. auto res = cli->Get("/");
  21537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21538. EXPECT_EQ(0, s.proxy_hits());
  21539. EXPECT_EQ(1, s.target_hits());
  21540. }
  21541. TEST(NoProxyTest, SubdomainBypasses) {
  21542. ProxyAndTargetServers s;
  21543. auto cli = make_client("foo.example.com", s);
  21544. cli->set_no_proxy({"example.com"});
  21545. auto res = cli->Get("/");
  21546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21547. EXPECT_EQ(0, s.proxy_hits());
  21548. EXPECT_EQ(1, s.target_hits());
  21549. }
  21550. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21551. // Regression guard: "evilexample.com" must not be considered a subdomain
  21552. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21553. // check would let traffic bypass the proxy and leak credentials direct
  21554. // to the attacker host.
  21555. ProxyAndTargetServers s;
  21556. auto cli = make_client("evilexample.com", s);
  21557. cli->set_no_proxy({"example.com"});
  21558. auto res = cli->Get("/");
  21559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21560. EXPECT_GE(s.proxy_hits(), 1);
  21561. EXPECT_EQ(0, s.target_hits());
  21562. }
  21563. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21564. ProxyAndTargetServers s;
  21565. auto cli = make_client("example.com.evil.com", s);
  21566. cli->set_no_proxy({"example.com"});
  21567. auto res = cli->Get("/");
  21568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21569. EXPECT_GE(s.proxy_hits(), 1);
  21570. EXPECT_EQ(0, s.target_hits());
  21571. }
  21572. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21573. ProxyAndTargetServers s;
  21574. auto cli = make_client("example.com", s);
  21575. cli->set_no_proxy({".example.com"});
  21576. auto res = cli->Get("/");
  21577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21578. EXPECT_EQ(0, s.proxy_hits());
  21579. EXPECT_EQ(1, s.target_hits());
  21580. }
  21581. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21582. ProxyAndTargetServers s;
  21583. auto cli = make_client("Example.COM", s);
  21584. cli->set_no_proxy({"EXAMPLE.com"});
  21585. auto res = cli->Get("/");
  21586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21587. EXPECT_EQ(0, s.proxy_hits());
  21588. EXPECT_EQ(1, s.target_hits());
  21589. }
  21590. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21591. ProxyAndTargetServers s;
  21592. auto cli = make_client("example.com.", s);
  21593. cli->set_no_proxy({"example.com"});
  21594. auto res = cli->Get("/");
  21595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21596. EXPECT_EQ(0, s.proxy_hits());
  21597. EXPECT_EQ(1, s.target_hits());
  21598. }
  21599. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21600. // Trailing dots must be normalized on BOTH sides — host and entry.
  21601. // An implementation that only strips the host-side trailing dot would
  21602. // fail to match host "example.com" against entry "example.com." because
  21603. // a literal substring search would compare 11 chars against 12.
  21604. ProxyAndTargetServers s;
  21605. auto cli = make_client("example.com", s);
  21606. cli->set_no_proxy({"example.com."});
  21607. auto res = cli->Get("/");
  21608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21609. EXPECT_EQ(0, s.proxy_hits());
  21610. EXPECT_EQ(1, s.target_hits());
  21611. }
  21612. TEST(NoProxyTest, WildcardBypassesEverything) {
  21613. ProxyAndTargetServers s;
  21614. auto cli = make_client("anything.invalid.test", s);
  21615. cli->set_no_proxy({"*"});
  21616. auto res = cli->Get("/");
  21617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21618. EXPECT_EQ(0, s.proxy_hits());
  21619. EXPECT_EQ(1, s.target_hits());
  21620. }
  21621. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21622. ProxyAndTargetServers s;
  21623. Client cli("127.0.0.1", s.target_port());
  21624. cli.set_proxy("127.0.0.1", s.proxy_port());
  21625. cli.set_no_proxy({"127.0.0.1"});
  21626. auto res = cli.Get("/");
  21627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21628. EXPECT_EQ(0, s.proxy_hits());
  21629. EXPECT_EQ(1, s.target_hits());
  21630. }
  21631. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21632. ProxyAndTargetServers s;
  21633. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21634. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21635. cli.set_proxy("127.0.0.1", s.proxy_port());
  21636. cli.set_no_proxy({"::1"});
  21637. auto res = cli.Get("/");
  21638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21639. EXPECT_EQ(0, s.proxy_hits());
  21640. EXPECT_EQ(1, s.target_hits());
  21641. }
  21642. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21643. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21644. // must still be recognized as IPv6 for CIDR matching. Implementations
  21645. // that detect IPv6 only when the host begins with '[' would parse the
  21646. // host as a hostname and miss the match.
  21647. ProxyAndTargetServers s;
  21648. Client cli("fe80::1", s.target_port());
  21649. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21650. cli.set_proxy("127.0.0.1", s.proxy_port());
  21651. cli.set_no_proxy({"fe80::/10"});
  21652. auto res = cli.Get("/");
  21653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21654. EXPECT_EQ(0, s.proxy_hits());
  21655. EXPECT_EQ(1, s.target_hits());
  21656. }
  21657. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21658. ProxyAndTargetServers s;
  21659. Client cli("::1", s.target_port());
  21660. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21661. cli.set_proxy("127.0.0.1", s.proxy_port());
  21662. cli.set_no_proxy({"[::1]"});
  21663. auto res = cli.Get("/");
  21664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21665. EXPECT_EQ(0, s.proxy_hits());
  21666. EXPECT_EQ(1, s.target_hits());
  21667. }
  21668. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21669. ProxyAndTargetServers s;
  21670. Client cli("fe80::1", s.target_port());
  21671. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21672. cli.set_proxy("127.0.0.1", s.proxy_port());
  21673. cli.set_no_proxy({"[fe80::]/10"});
  21674. auto res = cli.Get("/");
  21675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21676. EXPECT_EQ(0, s.proxy_hits());
  21677. EXPECT_EQ(1, s.target_hits());
  21678. }
  21679. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21680. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21681. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21682. // tricks via address-family conversion.
  21683. ProxyAndTargetServers s;
  21684. Client cli("::ffff:127.0.0.1", s.target_port());
  21685. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21686. cli.set_proxy("127.0.0.1", s.proxy_port());
  21687. cli.set_no_proxy({"127.0.0.1"});
  21688. auto res = cli.Get("/");
  21689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21690. EXPECT_GE(s.proxy_hits(), 1);
  21691. EXPECT_EQ(0, s.target_hits());
  21692. }
  21693. TEST(NoProxyTest, IPv4CidrMatch) {
  21694. ProxyAndTargetServers s;
  21695. Client cli("127.0.0.1", s.target_port());
  21696. cli.set_proxy("127.0.0.1", s.proxy_port());
  21697. cli.set_no_proxy({"127.0.0.0/8"});
  21698. auto res = cli.Get("/");
  21699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21700. EXPECT_EQ(0, s.proxy_hits());
  21701. EXPECT_EQ(1, s.target_hits());
  21702. }
  21703. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21704. ProxyAndTargetServers s;
  21705. Client cli("127.0.0.1", s.target_port());
  21706. cli.set_proxy("127.0.0.1", s.proxy_port());
  21707. cli.set_no_proxy({"10.0.0.0/8"});
  21708. auto res = cli.Get("/");
  21709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21710. EXPECT_GE(s.proxy_hits(), 1);
  21711. EXPECT_EQ(0, s.target_hits());
  21712. }
  21713. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21714. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21715. // IPv4 target matches.
  21716. ProxyAndTargetServers s;
  21717. Client cli("127.0.0.1", s.target_port());
  21718. cli.set_proxy("127.0.0.1", s.proxy_port());
  21719. cli.set_no_proxy({"0.0.0.0/0"});
  21720. auto res = cli.Get("/");
  21721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21722. EXPECT_EQ(0, s.proxy_hits());
  21723. EXPECT_EQ(1, s.target_hits());
  21724. }
  21725. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21726. ProxyAndTargetServers s;
  21727. Client cli("127.0.0.1", s.target_port());
  21728. cli.set_proxy("127.0.0.1", s.proxy_port());
  21729. cli.set_no_proxy({"127.0.0.1"});
  21730. auto res = cli.Get("/");
  21731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21732. EXPECT_EQ(0, s.proxy_hits());
  21733. EXPECT_EQ(1, s.target_hits());
  21734. }
  21735. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21736. ProxyAndTargetServers s;
  21737. Client cli("127.0.0.1", s.target_port());
  21738. cli.set_proxy("127.0.0.1", s.proxy_port());
  21739. cli.set_no_proxy({"127.0.0.0/33"});
  21740. auto res = cli.Get("/");
  21741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21742. EXPECT_GE(s.proxy_hits(), 1);
  21743. EXPECT_EQ(0, s.target_hits());
  21744. }
  21745. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21746. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21747. ProxyAndTargetServers s;
  21748. Client cli("127.0.0.1", s.target_port());
  21749. cli.set_proxy("127.0.0.1", s.proxy_port());
  21750. cli.set_no_proxy({"127.0.0.1/"});
  21751. auto res = cli.Get("/");
  21752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21753. EXPECT_GE(s.proxy_hits(), 1);
  21754. EXPECT_EQ(0, s.target_hits());
  21755. }
  21756. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21757. ProxyAndTargetServers s;
  21758. auto cli = make_client("internal.corp", s);
  21759. cli->set_proxy_basic_auth("u", "p");
  21760. cli->set_no_proxy({"internal.corp"});
  21761. auto res = cli->Get("/");
  21762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21763. EXPECT_EQ(1, s.target_hits());
  21764. EXPECT_EQ(0, s.proxy_hits());
  21765. EXPECT_FALSE(s.last_had_proxy_authz())
  21766. << "Proxy-Authorization must not be sent direct to the target";
  21767. }
  21768. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21769. ProxyAndTargetServers s;
  21770. auto cli = make_client("public.example", s);
  21771. cli->set_proxy_basic_auth("u", "p");
  21772. cli->set_no_proxy({"internal.corp"}); // does not match
  21773. auto res = cli->Get("/");
  21774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21775. EXPECT_GE(s.proxy_hits(), 1);
  21776. EXPECT_TRUE(s.last_had_proxy_authz());
  21777. }
  21778. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21779. ProxyAndTargetServers s;
  21780. auto cli = make_client("anything.test", s);
  21781. auto res = cli->Get("/");
  21782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21783. EXPECT_GE(s.proxy_hits(), 1);
  21784. EXPECT_EQ(0, s.target_hits());
  21785. }
  21786. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21787. ProxyAndTargetServers s;
  21788. auto cli = make_client("example.com", s);
  21789. cli->set_no_proxy({"example.com:8080"});
  21790. auto res = cli->Get("/");
  21791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21792. EXPECT_GE(s.proxy_hits(), 1);
  21793. EXPECT_EQ(0, s.target_hits());
  21794. }
  21795. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21796. ProxyAndTargetServers s;
  21797. auto cli = make_client("anything.test", s);
  21798. cli->set_no_proxy({"", " ", "\t"});
  21799. auto res = cli->Get("/");
  21800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21801. EXPECT_GE(s.proxy_hits(), 1);
  21802. EXPECT_EQ(0, s.target_hits());
  21803. }
  21804. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21805. // An entry with leading/trailing whitespace must still match — env-style
  21806. // values are commonly pasted with stray spaces and an implementation
  21807. // that feeds the raw token directly to inet_pton would fail to match
  21808. // valid CIDRs because of the spaces.
  21809. ProxyAndTargetServers s;
  21810. Client cli("127.0.0.1", s.target_port());
  21811. cli.set_proxy("127.0.0.1", s.proxy_port());
  21812. cli.set_no_proxy({" 127.0.0.0/8 "});
  21813. auto res = cli.Get("/");
  21814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21815. EXPECT_EQ(0, s.proxy_hits());
  21816. EXPECT_EQ(1, s.target_hits());
  21817. }
  21818. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21819. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21820. // go direct and must NOT carry Proxy-Authorization.
  21821. std::atomic<int> proxy_hits{0};
  21822. std::atomic<int> target_hits{0};
  21823. std::atomic<bool> target_saw_authz{false};
  21824. no_proxy_test::ScopedServer proxy_mock, target;
  21825. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21826. proxy_hits++;
  21827. res.status = 302;
  21828. res.set_header("Location", "http://127.0.0.1:" +
  21829. std::to_string(target.port()) + "/landed");
  21830. });
  21831. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21832. target_hits++;
  21833. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21834. res.set_content("direct", "text/plain");
  21835. });
  21836. proxy_mock.listen();
  21837. target.listen();
  21838. Client cli("public.example", target.port());
  21839. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21840. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21841. cli.set_proxy_basic_auth("u", "p");
  21842. cli.set_no_proxy({"127.0.0.1"});
  21843. cli.set_follow_location(true);
  21844. auto res = cli.Get("/redir");
  21845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21846. EXPECT_GE(proxy_hits.load(), 1);
  21847. EXPECT_GE(target_hits.load(), 1);
  21848. EXPECT_FALSE(target_saw_authz.load());
  21849. }
  21850. #ifdef CPPHTTPLIB_SSL_ENABLED
  21851. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21852. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21853. // proxy creds would be sent to the (possibly hostile) origin.
  21854. std::atomic<int> target_hits{0};
  21855. std::atomic<bool> target_saw_proxy_authz{false};
  21856. no_proxy_test::ScopedServer target;
  21857. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21858. target_hits++;
  21859. if (req.has_header("Proxy-Authorization")) {
  21860. target_saw_proxy_authz = true;
  21861. }
  21862. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21863. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21864. "nonce=\"abc\", algorithm=MD5");
  21865. });
  21866. target.listen();
  21867. // The proxy address is set to the target's port: the bypass MUST kick in;
  21868. // if it doesn't, the test still routes "via proxy" to the same server and
  21869. // the Proxy-Authorization assertion below catches the leak.
  21870. Client cli("evil.example", target.port());
  21871. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21872. cli.set_proxy("127.0.0.1", target.port());
  21873. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21874. cli.set_no_proxy({"evil.example"});
  21875. auto res = cli.Get("/x");
  21876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21877. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21878. EXPECT_EQ(1, target_hits.load());
  21879. EXPECT_FALSE(target_saw_proxy_authz.load());
  21880. }
  21881. #endif
  21882. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21883. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21884. std::atomic<int> proxy_hits{0};
  21885. std::atomic<int> bypass_hits{0};
  21886. std::atomic<bool> proxy_saw_c_url{false};
  21887. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21888. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21889. proxy_hits++;
  21890. if (req.path.find("/start") != std::string::npos) {
  21891. res.status = 302;
  21892. res.set_header("Location", "http://127.0.0.1:" +
  21893. std::to_string(bypass_server.port()) +
  21894. "/middle");
  21895. return;
  21896. }
  21897. if (req.path.find("/end") != std::string::npos) {
  21898. proxy_saw_c_url = true;
  21899. res.set_content("c-via-proxy", "text/plain");
  21900. return;
  21901. }
  21902. res.set_content("unexpected", "text/plain");
  21903. });
  21904. // public.example's "advertised" port is arbitrary (the request never lands
  21905. // there — it goes through the proxy), but use a dynamic value to stay
  21906. // friendly with sharded parallel runs.
  21907. int public_port = bypass_server.port();
  21908. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21909. bypass_hits++;
  21910. res.status = 302;
  21911. res.set_header("Location", "http://public.example:" +
  21912. std::to_string(public_port) + "/end");
  21913. });
  21914. proxy_mock.listen();
  21915. bypass_server.listen();
  21916. Client cli("public.example", public_port);
  21917. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21918. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21919. cli.set_no_proxy({"127.0.0.1"});
  21920. cli.set_follow_location(true);
  21921. auto res = cli.Get("/start");
  21922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21923. EXPECT_EQ(StatusCode::OK_200, res->status);
  21924. EXPECT_EQ("c-via-proxy", res->body);
  21925. EXPECT_GE(proxy_hits.load(), 2);
  21926. EXPECT_GE(bypass_hits.load(), 1);
  21927. EXPECT_TRUE(proxy_saw_c_url.load());
  21928. }
  21929. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21930. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21931. // request reconnects to the correct endpoint.
  21932. std::atomic<int> proxy_hits{0};
  21933. std::atomic<int> target_hits{0};
  21934. no_proxy_test::ScopedServer proxy_mock, target;
  21935. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21936. proxy_hits++;
  21937. res.set_content("via-proxy", "text/plain");
  21938. });
  21939. target.svr().Get(".*", [&](const Request &, Response &res) {
  21940. target_hits++;
  21941. res.set_content("direct", "text/plain");
  21942. });
  21943. proxy_mock.listen();
  21944. target.listen();
  21945. Client cli("public.example", target.port());
  21946. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21947. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21948. cli.set_keep_alive(true);
  21949. auto res1 = cli.Get("/a");
  21950. ASSERT_TRUE(res1);
  21951. EXPECT_EQ("via-proxy", res1->body);
  21952. EXPECT_EQ(1, proxy_hits.load());
  21953. EXPECT_EQ(0, target_hits.load());
  21954. cli.set_no_proxy({"public.example"});
  21955. auto res2 = cli.Get("/b");
  21956. ASSERT_TRUE(res2);
  21957. EXPECT_EQ("direct", res2->body);
  21958. EXPECT_EQ(1, proxy_hits.load());
  21959. EXPECT_EQ(1, target_hits.load());
  21960. }
  21961. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21962. namespace proxy_tunnel_test {
  21963. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21964. class ScopedSSLServer {
  21965. public:
  21966. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21967. port_ = svr_.bind_to_any_port("127.0.0.1");
  21968. }
  21969. ~ScopedSSLServer() {
  21970. svr_.stop();
  21971. if (th_.joinable()) { th_.join(); }
  21972. }
  21973. SSLServer &svr() { return svr_; }
  21974. int port() const { return port_; }
  21975. void listen() {
  21976. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21977. svr_.wait_until_ready();
  21978. }
  21979. private:
  21980. SSLServer svr_;
  21981. std::thread th_;
  21982. int port_ = 0;
  21983. };
  21984. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21985. class ScopedConnectProxy {
  21986. public:
  21987. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21988. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21989. if (listen_fd_ < 0) { return; }
  21990. int yes = 1;
  21991. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21992. sockaddr_in a{};
  21993. a.sin_family = AF_INET;
  21994. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21995. a.sin_port = 0;
  21996. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21997. return;
  21998. }
  21999. socklen_t alen = sizeof(a);
  22000. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22001. 0) {
  22002. return;
  22003. }
  22004. port_ = ntohs(a.sin_port);
  22005. if (::listen(listen_fd_, 1) != 0) { return; }
  22006. th_ = std::thread([this] { run(); });
  22007. }
  22008. ~ScopedConnectProxy() {
  22009. stop_ = true;
  22010. if (listen_fd_ >= 0) {
  22011. ::shutdown(listen_fd_, SHUT_RDWR);
  22012. ::close(listen_fd_);
  22013. }
  22014. if (th_.joinable()) { th_.join(); }
  22015. }
  22016. int port() const { return port_; }
  22017. int connect_hits() const { return connect_hits_.load(); }
  22018. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22019. std::string connect_request() const {
  22020. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22021. return connect_request_;
  22022. }
  22023. private:
  22024. void run() {
  22025. while (!stop_.load()) {
  22026. fd_set rfds;
  22027. FD_ZERO(&rfds);
  22028. FD_SET(listen_fd_, &rfds);
  22029. timeval tv{0, 100 * 1000};
  22030. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22031. if (sel <= 0) { continue; }
  22032. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22033. if (client_fd < 0) { continue; }
  22034. std::string req;
  22035. char buf[2048];
  22036. while (req.find("\r\n\r\n") == std::string::npos) {
  22037. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22038. if (n <= 0) { break; }
  22039. req.append(buf, static_cast<size_t>(n));
  22040. }
  22041. if (req.compare(0, 7, "CONNECT") != 0) {
  22042. ::close(client_fd);
  22043. continue;
  22044. }
  22045. connect_hits_++;
  22046. {
  22047. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22048. connect_request_ = req;
  22049. }
  22050. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22051. ::send(client_fd, ok, std::strlen(ok), 0);
  22052. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22053. sockaddr_in o{};
  22054. o.sin_family = AF_INET;
  22055. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22056. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22057. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22058. 0) {
  22059. ::close(client_fd);
  22060. ::close(origin_fd);
  22061. continue;
  22062. }
  22063. auto forward = [](int from, int to) {
  22064. char b[8192];
  22065. for (;;) {
  22066. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22067. if (n <= 0) { break; }
  22068. ssize_t off = 0;
  22069. while (off < n) {
  22070. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22071. if (s <= 0) {
  22072. off = n;
  22073. break;
  22074. }
  22075. off += s;
  22076. }
  22077. }
  22078. ::shutdown(to, SHUT_WR);
  22079. };
  22080. std::thread t1([&] { forward(client_fd, origin_fd); });
  22081. std::thread t2([&] { forward(origin_fd, client_fd); });
  22082. t1.join();
  22083. t2.join();
  22084. ::close(client_fd);
  22085. ::close(origin_fd);
  22086. }
  22087. }
  22088. int forward_port_ = -1;
  22089. int listen_fd_ = -1;
  22090. int port_ = 0;
  22091. std::thread th_;
  22092. std::atomic<bool> stop_{false};
  22093. std::atomic<int> connect_hits_{0};
  22094. mutable std::mutex connect_request_mutex_;
  22095. std::string connect_request_;
  22096. };
  22097. // Sends one request through the CONNECT proxy to the TLS origin with a
  22098. // credential configured for each hop, and checks that each credential reaches
  22099. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22100. // origin's (every header in origin_headers) on the tunnelled request.
  22101. void CredentialsStayWithTheirHop(
  22102. const std::function<void(SSLClient &)> &set_credentials,
  22103. const std::string &scheme,
  22104. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22105. std::atomic<int> origin_hits{0};
  22106. std::atomic<bool> origin_saw_proxy_authz{false};
  22107. std::atomic<bool> origin_saw_headers{false};
  22108. ScopedSSLServer origin;
  22109. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22110. origin_hits++;
  22111. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22112. origin_saw_headers =
  22113. std::all_of(origin_headers.begin(), origin_headers.end(),
  22114. [&](const std::string &h) { return req.has_header(h); });
  22115. res.set_content("ok", "text/plain");
  22116. });
  22117. origin.listen();
  22118. ScopedConnectProxy proxy(origin.port());
  22119. ASSERT_NE(0, proxy.port());
  22120. // Pinned to 127.0.0.1 for the same reason as the test below.
  22121. SSLClient cli("127.0.0.1", origin.port());
  22122. cli.enable_server_certificate_verification(false);
  22123. cli.set_proxy("127.0.0.1", proxy.port());
  22124. set_credentials(cli);
  22125. auto res = cli.Get("/x");
  22126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22127. EXPECT_EQ(StatusCode::OK_200, res->status);
  22128. EXPECT_EQ(1, origin_hits.load());
  22129. EXPECT_EQ(1, proxy.connect_hits());
  22130. EXPECT_TRUE(origin_saw_headers.load());
  22131. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22132. << "Proxy-Authorization must not be sent inside the tunnel";
  22133. auto connect_req = proxy.connect_request();
  22134. EXPECT_NE(std::string::npos,
  22135. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22136. for (const auto &h : origin_headers) {
  22137. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22138. << h << " must not be sent to the proxy on CONNECT";
  22139. }
  22140. }
  22141. } // namespace proxy_tunnel_test
  22142. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22143. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22144. [](SSLClient &cli) {
  22145. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22146. cli.set_basic_auth("origin-user", "origin-pass");
  22147. },
  22148. "Basic");
  22149. }
  22150. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22151. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22152. [](SSLClient &cli) {
  22153. cli.set_proxy_bearer_token_auth("proxy-token");
  22154. cli.set_bearer_token_auth("origin-token");
  22155. },
  22156. "Bearer");
  22157. }
  22158. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22159. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22160. [](SSLClient &cli) {
  22161. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22162. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22163. {"Cookie", "sid=origin-session"},
  22164. {"X-Api-Key", "origin-key"}});
  22165. },
  22166. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22167. }
  22168. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22169. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22170. // retry; otherwise proxy creds would be sent to the origin.
  22171. std::atomic<int> origin_hits{0};
  22172. std::atomic<bool> origin_saw_proxy_authz{false};
  22173. proxy_tunnel_test::ScopedSSLServer origin;
  22174. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22175. origin_hits++;
  22176. if (req.has_header("Proxy-Authorization")) {
  22177. origin_saw_proxy_authz = true;
  22178. }
  22179. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22180. res.set_header("Proxy-Authenticate",
  22181. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22182. "algorithm=MD5");
  22183. });
  22184. origin.listen();
  22185. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22186. ASSERT_NE(0, proxy.port());
  22187. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22188. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22189. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22190. // and answer with its own status, making this test flaky.
  22191. SSLClient cli("127.0.0.1", origin.port());
  22192. cli.enable_server_certificate_verification(false);
  22193. cli.set_proxy("127.0.0.1", proxy.port());
  22194. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22195. auto res = cli.Get("/x");
  22196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22197. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22198. EXPECT_EQ(1, origin_hits.load());
  22199. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22200. EXPECT_EQ(1, proxy.connect_hits());
  22201. }
  22202. #endif