1
0

test.cc 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 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. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. #ifndef _WIN32
  253. TEST(SocketStream, wait_writable_UNIX) {
  254. int fds[2];
  255. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  256. const auto asSocketStream = [&](socket_t fd,
  257. std::function<bool(Stream &)> func) {
  258. return detail::process_client_socket(
  259. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  260. };
  261. asSocketStream(fds[0], [&](Stream &s0) {
  262. EXPECT_EQ(s0.socket(), fds[0]);
  263. EXPECT_TRUE(s0.wait_writable());
  264. EXPECT_TRUE(s0.is_peer_alive());
  265. EXPECT_EQ(0, close(fds[1]));
  266. EXPECT_FALSE(s0.is_peer_alive());
  267. return true;
  268. });
  269. EXPECT_EQ(0, close(fds[0]));
  270. }
  271. TEST(SocketStream, wait_writable_INET) {
  272. sockaddr_in addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin_family = AF_INET;
  275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  276. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  277. int disconnected_svr_sock = -1;
  278. std::thread svr{[&] {
  279. const int s = socket(AF_INET, SOCK_STREAM, 0);
  280. ASSERT_LE(0, s);
  281. // PORT + 1 is shared with the SSL redirect tests and with
  282. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  283. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  284. // because that happens on a worker thread the ASSERT does not stop the
  285. // test: it runs on and fails at the disconnected_svr_sock check instead.
  286. default_socket_options(s);
  287. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  288. ASSERT_EQ(0, listen(s, 1));
  289. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  290. ASSERT_EQ(0, close(s));
  291. }};
  292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  293. std::thread cli{[&] {
  294. const int s = socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_LE(0, s);
  296. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  297. ASSERT_EQ(0, close(s));
  298. }};
  299. cli.join();
  300. svr.join();
  301. ASSERT_NE(disconnected_svr_sock, -1);
  302. const auto asSocketStream = [&](socket_t fd,
  303. std::function<bool(Stream &)> func) {
  304. return detail::process_client_socket(
  305. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  306. };
  307. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  308. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  309. // wait_writable() returns true because select_write() only checks if the
  310. // send buffer has space. Peer disconnection is detected later by send().
  311. EXPECT_TRUE(ss.wait_writable());
  312. return true;
  313. });
  314. ASSERT_EQ(0, close(disconnected_svr_sock));
  315. }
  316. #endif // #ifndef _WIN32
  317. TEST(SetSocketOptTest, TcpNoDelay) {
  318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  319. ASSERT_NE(sock, INVALID_SOCKET);
  320. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  321. int val = 0;
  322. socklen_t len = sizeof(val);
  323. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  324. reinterpret_cast<char *>(&val), &len));
  325. EXPECT_NE(val, 0);
  326. detail::close_socket(sock);
  327. }
  328. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  329. // accept() reports failures through WSAGetLastError() on Windows and through
  330. // errno everywhere else. Asking the wrong one is what made the accept loop
  331. // treat every recoverable failure as fatal on Windows.
  332. struct Classification {
  333. bool resource;
  334. bool transient;
  335. };
  336. auto classify = [](int err) {
  337. #ifdef _WIN32
  338. WSASetLastError(err);
  339. #else
  340. errno = err;
  341. #endif
  342. // Read both before asserting: an assertion may clobber the error slot.
  343. Classification c;
  344. c.resource = detail::is_accept_resource_error();
  345. c.transient = detail::is_accept_transient_error();
  346. return c;
  347. };
  348. #ifdef _WIN32
  349. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  350. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  351. WSAECONNRESET, WSAECONNABORTED};
  352. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  353. #else
  354. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  355. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  356. ECONNABORTED};
  357. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  358. #endif
  359. for (auto err : resource_errors) {
  360. const auto c = classify(err);
  361. EXPECT_TRUE(c.resource) << "error " << err;
  362. EXPECT_FALSE(c.transient) << "error " << err;
  363. }
  364. for (auto err : transient_errors) {
  365. const auto c = classify(err);
  366. EXPECT_TRUE(c.transient) << "error " << err;
  367. EXPECT_FALSE(c.resource) << "error " << err;
  368. }
  369. for (auto err : fatal_errors) {
  370. const auto c = classify(err);
  371. EXPECT_FALSE(c.resource) << "error " << err;
  372. EXPECT_FALSE(c.transient) << "error " << err;
  373. }
  374. #ifdef _WIN32
  375. WSASetLastError(0);
  376. #else
  377. errno = 0;
  378. #endif
  379. }
  380. TEST(ClientTest, MoveConstructible) {
  381. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  382. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  383. }
  384. TEST(ClientTest, MoveAssignable) {
  385. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  386. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  387. }
  388. #ifdef _WIN32
  389. TEST(StartupTest, WSAStartup) {
  390. WSADATA wsaData;
  391. int ret = WSAStartup(0x0002, &wsaData);
  392. ASSERT_EQ(0, ret);
  393. }
  394. #endif
  395. TEST(DecodePathTest, PercentCharacter) {
  396. EXPECT_EQ(
  397. decode_path_component(
  398. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  399. U8("descrip=Gastos áéíóúñÑ 6"));
  400. }
  401. TEST(DecodePathTest, PercentCharacterNUL) {
  402. string expected;
  403. expected.push_back('x');
  404. expected.push_back('\0');
  405. expected.push_back('x');
  406. EXPECT_EQ(decode_path_component("x%00x"), expected);
  407. }
  408. TEST(DecodePathTest, UnicodeEncoding) {
  409. // %u0041 = 'A' (1-byte UTF-8)
  410. EXPECT_EQ("A", decode_path_component("%u0041"));
  411. // %u00E9 = 'é' (2-byte UTF-8)
  412. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  413. // %u3042 = 'あ' (3-byte UTF-8)
  414. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  415. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  416. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  417. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  418. // neighbours)
  419. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  420. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  421. }
  422. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  423. // A sign or whitespace inside the two-character escape window must not be
  424. // accepted as a valid percent-encoding; the sequence is passed through
  425. // literally, matching decode_uri_component / decode_path_component.
  426. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  427. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  428. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  429. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  430. // Well-formed escapes still decode.
  431. EXPECT_EQ("-", decode_query_component("%2D", false));
  432. EXPECT_EQ("A", decode_query_component("%41", false));
  433. }
  434. TEST(SanitizeFilenameTest, VariousPatterns) {
  435. // Path traversal
  436. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  437. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  438. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  439. // Normal and edge cases
  440. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  441. EXPECT_EQ("filename.txt",
  442. httplib::sanitize_filename("/path/to/filename.txt"));
  443. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  444. EXPECT_EQ("", httplib::sanitize_filename(".."));
  445. EXPECT_EQ("", httplib::sanitize_filename(""));
  446. // Null bytes stripped
  447. EXPECT_EQ("safe.txt",
  448. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  449. // Whitespace-only rejected
  450. EXPECT_EQ("", httplib::sanitize_filename(" "));
  451. }
  452. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  453. // before it is dropped; anywhere else it is an ordinary file name character.
  454. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  455. #ifdef _WIN32
  456. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  457. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  458. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  459. #else
  460. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  461. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  462. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  463. #endif
  464. }
  465. // Forward declaration (see the base64_encode note below): split builds move the
  466. // definition into httplib.cc, so re-declaring it here lets the test link.
  467. namespace httplib {
  468. namespace detail {
  469. bool is_chunked_transfer_encoding(const Headers &headers);
  470. } // namespace detail
  471. } // namespace httplib
  472. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  473. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  474. auto make = [](std::initializer_list<const char *> lines) {
  475. Headers h;
  476. for (auto te : lines) {
  477. if (te) { h.emplace("Transfer-Encoding", te); }
  478. }
  479. return h;
  480. };
  481. // Sole coding, matched case-insensitively.
  482. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  483. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  484. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  485. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  486. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  488. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  489. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  490. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  491. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  492. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  493. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  494. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  495. // were received, into one list. Headers preserves that order, so the answer
  496. // is decided by the last coding of the last line and the order the lines
  497. // arrived in is significant.
  498. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  499. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  500. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  501. // The split can fall anywhere in the list.
  502. EXPECT_TRUE(
  503. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  504. EXPECT_FALSE(
  505. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  506. // A trailing line naming no coding leaves the list ending in nothing, so it
  507. // must not inherit the chunked from the line before it.
  508. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  509. }
  510. // Forward declarations (see the base64_encode note below).
  511. namespace httplib {
  512. namespace detail {
  513. bool parse_status_line(const char *line, std::string &version, int &status,
  514. std::string &reason);
  515. std::string file_extension(const std::string &path);
  516. std::string
  517. find_content_type(const std::string &path,
  518. const std::map<std::string, std::string> &user_data,
  519. const std::string &default_content_type);
  520. bool can_compress_content_type(const std::string &content_type);
  521. bool is_prohibited_header_name(const std::string &name);
  522. bool is_valid_path(const std::string &path);
  523. #ifdef CPPHTTPLIB_SSL_ENABLED
  524. bool match_hostname(const std::string &pattern, const std::string &hostname);
  525. #endif
  526. } // namespace detail
  527. } // namespace httplib
  528. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  529. struct {
  530. const char *line;
  531. const char *version;
  532. int status;
  533. const char *reason;
  534. } cases[] = {
  535. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  536. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  537. // The reason phrase may be empty, or left out along with its space.
  538. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  539. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  540. };
  541. for (const auto &c : cases) {
  542. std::string version;
  543. int status = 0;
  544. std::string reason = "unset";
  545. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  546. << c.line;
  547. EXPECT_EQ(c.version, version);
  548. EXPECT_EQ(c.status, status);
  549. EXPECT_EQ(c.reason, reason);
  550. }
  551. }
  552. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  553. const char *lines[] = {
  554. "HTTP/2 200 OK\r\n",
  555. "HTTP/1.2 200 OK\r\n",
  556. "HTTP/1.1 20 OK\r\n",
  557. "HTTP/1.1 2000 OK\r\n",
  558. "HTTP/1.1 2x0 OK\r\n",
  559. "HTTP/1.1 200 OK\r\n",
  560. "HTTP/1.1 200OK\r\n",
  561. "HTTP/1.1 200 O\rK\r\n",
  562. "HTTP/1.1 200 OK",
  563. "HTTP/1.1 200 OK\r\nX",
  564. "",
  565. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  566. "HTTP/1.1 200 OK\n",
  567. #endif
  568. };
  569. for (auto line : lines) {
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  574. << line;
  575. }
  576. }
  577. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  578. // Long enough to overflow the stack when matched with std::regex.
  579. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  580. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  581. std::string version;
  582. int status = 0;
  583. std::string reason;
  584. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  585. EXPECT_EQ(200, status);
  586. EXPECT_EQ(long_reason, reason);
  587. }
  588. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  589. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  590. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  591. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  592. EXPECT_EQ("", detail::file_extension("noext"));
  593. EXPECT_EQ("", detail::file_extension("a."));
  594. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  595. EXPECT_EQ("", detail::file_extension("a.b-c"));
  596. // Long enough to overflow the stack when matched with std::regex.
  597. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  598. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  599. }
  600. #ifdef CPPHTTPLIB_SSL_ENABLED
  601. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  602. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  603. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  604. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  605. // A wildcard needs two labels after it, in the leftmost label only
  606. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  607. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  608. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  609. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  610. EXPECT_FALSE(
  611. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  612. // No name may have an empty label
  613. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  614. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  615. }
  616. #endif
  617. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  618. detail::case_ignore::hash hash;
  619. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  620. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  621. // Long enough to overflow the stack if hashed one call per character.
  622. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  623. }
  624. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  625. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  626. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  627. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  628. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  629. // Same 26-bit hash as html, svg and js.
  630. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  631. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  632. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  633. }
  634. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  635. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  636. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  637. }
  638. }
  639. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  640. // name anywhere else.
  641. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  642. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  643. #ifdef _WIN32
  644. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  645. #else
  646. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  647. #endif
  648. }
  649. }
  650. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  651. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  652. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  653. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  654. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  655. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  656. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  657. // Same 26-bit hash as application/json.
  658. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  659. }
  660. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  661. Request req;
  662. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  663. EXPECT_TRUE(req.is_multipart_form_data());
  664. std::string boundary;
  665. EXPECT_TRUE(detail::parse_multipart_boundary(
  666. req.get_header_value("Content-Type"), boundary));
  667. EXPECT_EQ("x", boundary);
  668. }
  669. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  670. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  671. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  672. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  673. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  674. // Same 26-bit hash as REMOTE_ADDR.
  675. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  676. }
  677. // Forward declaration: in split builds split.py strips `inline` and moves the
  678. // definition into httplib.cc, so detail::base64_encode is not visible from the
  679. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  680. // in both header-only and split builds.
  681. namespace httplib {
  682. namespace detail {
  683. std::string base64_encode(const std::string &in);
  684. } // namespace detail
  685. } // namespace httplib
  686. TEST(Base64EncodeTest, KnownAnswers) {
  687. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  688. // where the accumulator's top bit is already set before the next shift.
  689. EXPECT_EQ("", detail::base64_encode(""));
  690. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  691. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  692. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  693. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  694. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  695. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  696. // High bytes keep the top bit set across several rounds.
  697. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  698. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  699. }
  700. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  701. string unescapedCharacters = "-_.!~*'()";
  702. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  703. }
  704. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  705. string reservedCharacters = ";,/?:@&=+$";
  706. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  707. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  708. }
  709. TEST(ClientQueryOrder, PreserveOrder) {
  710. // This test reproduces Issue #2259: client may reorder query parameters
  711. // when sending a GET request. The expected behavior is that the client
  712. // preserves the original query string order when the caller supplied it
  713. // as part of the path.
  714. Server svr;
  715. svr.Get("/", [&](const Request &req, Response &res) {
  716. // Echo back the raw target so the test can assert ordering
  717. res.set_content(req.target, "text/plain");
  718. });
  719. std::thread t{[&] { svr.listen(HOST, PORT); }};
  720. auto se = detail::scope_exit([&] {
  721. svr.stop();
  722. t.join();
  723. ASSERT_FALSE(svr.is_running());
  724. });
  725. svr.wait_until_ready();
  726. Client cli(HOST, PORT);
  727. ASSERT_TRUE(cli.is_valid());
  728. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  729. auto res = cli.Get(original);
  730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  731. // Expect the echoed target to exactly match the original path (order
  732. // preserved)
  733. EXPECT_EQ(res->body, original);
  734. }
  735. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  736. string chineseCharacters = U8("中国語");
  737. string russianCharacters = U8("дом");
  738. string brazilianCharacters = U8("óculos");
  739. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  740. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  741. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  742. "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  746. string unescapedCharacters = "-_.!~*'()";
  747. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  748. }
  749. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  750. string reservedCharacters = ";,/?:@&=+$";
  751. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  752. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  753. }
  754. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  761. "%D0%B4%D0%BE%D0%BC");
  762. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  763. }
  764. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  765. // Issue #2082 use case: encoding path component with ampersand
  766. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  767. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  768. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  769. }
  770. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  775. string reservedCharacters = ";,/?:@&=+$#";
  776. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  777. }
  778. TEST(EncodeUriTest, TestUTF8Characters) {
  779. string chineseCharacters = U8("中国語");
  780. string russianCharacters = U8("дом");
  781. string brazilianCharacters = U8("óculos");
  782. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  783. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  784. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  785. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  786. }
  787. TEST(EncodeUriTest, TestCompleteUri) {
  788. string uri =
  789. "https://example.com/path/to/resource?query=value&param=test#fragment";
  790. EXPECT_EQ(
  791. httplib::encode_uri(uri),
  792. "https://example.com/path/to/resource?query=value&param=test#fragment");
  793. }
  794. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  795. string uri =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. EXPECT_EQ(httplib::encode_uri(uri),
  798. "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world");
  800. }
  801. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  802. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  803. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  804. }
  805. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  806. string unescapedCharacters = "-_.!~*'()";
  807. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  808. }
  809. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  810. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  811. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  812. string encodedBrazilian = "%C3%B3culos";
  813. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  814. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  815. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  816. }
  817. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  818. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  819. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  820. "Piri Tommy Villiers - on & on");
  821. }
  822. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  823. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  824. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  825. }
  826. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  827. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  828. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  829. }
  830. TEST(DecodeUriTest, TestUTF8Characters) {
  831. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  832. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  833. string encodedBrazilian = "%C3%B3culos";
  834. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  835. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  836. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  837. }
  838. TEST(DecodeUriTest, TestCompleteUri) {
  839. string encodedUri = "https://example.com/path%20with%20spaces/"
  840. "file%20name.html?q=hello%20world";
  841. EXPECT_EQ(
  842. httplib::decode_uri(encodedUri),
  843. "https://example.com/path with spaces/file name.html?q=hello world");
  844. }
  845. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  846. string original =
  847. "https://example.com/path with spaces/file name.html?q=hello world";
  848. string encoded = httplib::encode_uri(original);
  849. string decoded = httplib::decode_uri(encoded);
  850. EXPECT_EQ(decoded, original);
  851. }
  852. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  853. // decode_uri is the inverse of encode_uri: an escaped reserved character
  854. // stays encoded so it is not promoted into a real delimiter, while
  855. // non-reserved escapes still decode (like JS decodeURI).
  856. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  857. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  858. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  859. "%3F%3A%40%26%3D%2B%24%2C%3B");
  860. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  861. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  862. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  863. "http://example.com/a%2Fb");
  864. // decode_uri_component still decodes the reserved character.
  865. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  866. }
  867. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  868. string original = "Piri Tommy Villiers - on & on";
  869. string encoded = httplib::encode_uri_component(original);
  870. string decoded = httplib::decode_uri_component(encoded);
  871. EXPECT_EQ(decoded, original);
  872. }
  873. TEST(TrimTests, TrimStringTests) {
  874. EXPECT_EQ("abc", detail::trim_copy("abc"));
  875. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  876. EXPECT_TRUE(detail::trim_copy("").empty());
  877. }
  878. TEST(AsciiTest, LocaleIndependentClassification) {
  879. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  880. // which consult the global C locale: std::isalnum(0xC5) can return true
  881. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  882. // helpers must classify every byte by the ASCII grammar alone.
  883. for (int i = 0; i < 256; i++) {
  884. auto c = static_cast<char>(i);
  885. auto is_digit = i >= '0' && i <= '9';
  886. auto is_upper = i >= 'A' && i <= 'Z';
  887. auto is_lower = i >= 'a' && i <= 'z';
  888. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  889. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  890. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  891. << "byte " << i;
  892. }
  893. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  894. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  895. // Non-ASCII bytes must be percent-encoded, never passed through as
  896. // alphanumeric.
  897. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  898. }
  899. TEST(FromCharsTest, Double) {
  900. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  901. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  902. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  903. auto parse = [](const std::string &s, double &v) {
  904. return detail::from_chars(s.data(), s.data() + s.size(), v);
  905. };
  906. double v = -1.0;
  907. // Representative quality values.
  908. EXPECT_EQ(parse("0", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse("1", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 1.0);
  912. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  913. EXPECT_DOUBLE_EQ(v, 0.8);
  914. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 0.001);
  916. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  917. EXPECT_DOUBLE_EQ(v, 1.0);
  918. // A missing integer or fractional part is tolerated.
  919. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  920. EXPECT_DOUBLE_EQ(v, 0.5);
  921. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  922. EXPECT_DOUBLE_EQ(v, 5.0);
  923. // Values outside [0, 1] still parse; the caller range-checks them.
  924. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  925. EXPECT_DOUBLE_EQ(v, 123.456);
  926. // Stops at the first byte that is not part of the number and reports where.
  927. std::string trailing = "0.9, text/html";
  928. auto r = parse(trailing, v);
  929. EXPECT_EQ(r.ec, std::errc{});
  930. EXPECT_DOUBLE_EQ(v, 0.9);
  931. EXPECT_EQ(*r.ptr, ',');
  932. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  933. // outright, and an 'e'/'E' simply ends the number.
  934. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  936. std::string exp_input = "1.5e3";
  937. r = parse(exp_input, v);
  938. EXPECT_EQ(r.ec, std::errc{});
  939. EXPECT_DOUBLE_EQ(v, 1.5);
  940. EXPECT_EQ(*r.ptr, 'e');
  941. // Invalid inputs.
  942. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  943. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  944. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  945. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  946. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  947. // Pathological but well-formed inputs must stay bounded (no overflow, no
  948. // out-of-bounds table access) and stay within [0, 1] for the caller.
  949. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  950. std::errc{});
  951. EXPECT_DOUBLE_EQ(v, 0.0);
  952. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  953. std::errc{});
  954. EXPECT_GE(v, 0.0);
  955. EXPECT_LE(v, 1.0);
  956. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  957. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  958. }
  959. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  960. // Simple case without quality values
  961. std::vector<std::string> result1;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html,application/json,text/plain", result1));
  964. EXPECT_EQ(result1.size(), 3U);
  965. EXPECT_EQ(result1[0], "text/html");
  966. EXPECT_EQ(result1[1], "application/json");
  967. EXPECT_EQ(result1[2], "text/plain");
  968. // With quality values
  969. std::vector<std::string> result2;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  972. EXPECT_EQ(result2.size(), 3U);
  973. EXPECT_EQ(result2[0], "application/json"); // highest q value
  974. EXPECT_EQ(result2[1], "text/html");
  975. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  976. }
  977. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  978. // Mixed with and without quality values
  979. std::vector<std::string> result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  982. EXPECT_EQ(result.size(), 3U);
  983. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  984. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  985. EXPECT_EQ(result[2], "application/json"); // q=0.5
  986. }
  987. TEST(ParseAcceptHeaderTest, EdgeCases) {
  988. // Empty header
  989. std::vector<std::string> empty_result;
  990. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  991. EXPECT_TRUE(empty_result.empty());
  992. // Single type
  993. std::vector<std::string> single_result;
  994. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  995. EXPECT_EQ(single_result.size(), 1U);
  996. EXPECT_EQ(single_result[0], "application/json");
  997. // Wildcard types
  998. std::vector<std::string> wildcard_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1001. EXPECT_EQ(wildcard_result.size(), 3U);
  1002. EXPECT_EQ(wildcard_result[0], "application/json");
  1003. EXPECT_EQ(wildcard_result[1], "text/*");
  1004. EXPECT_EQ(wildcard_result[2], "*/*");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1007. // Common browser Accept header
  1008. std::vector<std::string> browser_result;
  1009. EXPECT_TRUE(
  1010. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1011. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1012. browser_result));
  1013. EXPECT_EQ(browser_result.size(), 6U);
  1014. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1015. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1016. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1017. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1018. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1019. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1020. // API client header
  1021. std::vector<std::string> api_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1024. api_result));
  1025. EXPECT_EQ(api_result.size(), 3U);
  1026. EXPECT_EQ(api_result[0], "application/json");
  1027. EXPECT_EQ(api_result[1], "application/xml");
  1028. EXPECT_EQ(api_result[2], "text/plain");
  1029. }
  1030. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1031. // Quality value with 3 decimal places
  1032. std::vector<std::string> decimal_result;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1035. EXPECT_EQ(decimal_result.size(), 2U);
  1036. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1037. EXPECT_EQ(decimal_result[1], "text/html");
  1038. // Zero quality (should still be included but with lowest priority)
  1039. std::vector<std::string> zero_q_result;
  1040. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1041. zero_q_result));
  1042. EXPECT_EQ(zero_q_result.size(), 2U);
  1043. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1044. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1045. // No spaces around commas
  1046. std::vector<std::string> no_space_result;
  1047. EXPECT_TRUE(detail::parse_accept_header(
  1048. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1049. no_space_result));
  1050. EXPECT_EQ(no_space_result.size(), 3U);
  1051. EXPECT_EQ(no_space_result[0], "text/html");
  1052. EXPECT_EQ(no_space_result[1], "application/json");
  1053. EXPECT_EQ(no_space_result[2], "text/plain");
  1054. }
  1055. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1056. // Quality values always use '.' as the decimal separator, so parsing must
  1057. // not depend on the process locale. An embedding application may have
  1058. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1059. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1060. std::string saved = cur ? cur : "C";
  1061. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1062. "fr_FR.UTF-8"};
  1063. bool switched = false;
  1064. for (const auto loc : comma_locales) {
  1065. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1066. std::localeconv()->decimal_point[0] == ',') {
  1067. switched = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!switched) {
  1072. std::setlocale(LC_NUMERIC, saved.c_str());
  1073. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1074. }
  1075. // The higher-weighted type appears later in the list, so a correct parse
  1076. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1077. // sensitive parse reads both weights as 0 and leaves the original order.
  1078. std::vector<std::string> result;
  1079. EXPECT_TRUE(detail::parse_accept_header(
  1080. "application/json;q=0.1,text/html;q=0.9", result));
  1081. ASSERT_EQ(result.size(), 2U);
  1082. EXPECT_EQ(result[0], "text/html");
  1083. EXPECT_EQ(result[1], "application/json");
  1084. std::setlocale(LC_NUMERIC, saved.c_str());
  1085. }
  1086. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1087. std::vector<std::string> result;
  1088. // Invalid quality value (> 1.0)
  1089. EXPECT_FALSE(
  1090. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1091. // Invalid quality value (< 0.0)
  1092. EXPECT_FALSE(
  1093. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1094. // Invalid quality value (not a number)
  1095. EXPECT_FALSE(detail::parse_accept_header(
  1096. "text/html;q=invalid,application/json", result));
  1097. // A valid numeric prefix does not make the entire quality value valid.
  1098. EXPECT_FALSE(detail::parse_accept_header(
  1099. "text/html;q=0.5junk,application/json", result));
  1100. // Empty quality value
  1101. EXPECT_FALSE(
  1102. detail::parse_accept_header("text/html;q=,application/json", result));
  1103. // Invalid media type format (no slash and not wildcard)
  1104. EXPECT_FALSE(
  1105. detail::parse_accept_header("invalidtype,application/json", result));
  1106. // Valid cases should still work
  1107. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1108. EXPECT_EQ(result.size(), 1U);
  1109. EXPECT_EQ(result[0], "*/*");
  1110. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1111. EXPECT_EQ(result.size(), 1U);
  1112. EXPECT_EQ(result[0], "*");
  1113. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1114. EXPECT_EQ(result.size(), 1U);
  1115. EXPECT_EQ(result[0], "text/*");
  1116. }
  1117. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1118. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1119. // and must not be answered with 400 Bad Request.
  1120. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1121. struct {
  1122. const char *value;
  1123. std::vector<std::string> expected;
  1124. } cases[] = {
  1125. {",application/json", {"application/json"}},
  1126. {"text/html,", {"text/html"}},
  1127. {"text/html,,*/*", {"text/html", "*/*"}},
  1128. // An empty element may be spelled with whitespace in it
  1129. {"text/html, , application/json", {"text/html", "application/json"}},
  1130. // Nothing but empty elements is an empty list, which means the same
  1131. // thing as no Accept header at all
  1132. {",,,", {}},
  1133. // Quality values still apply across ignored empty elements
  1134. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1135. };
  1136. for (const auto &c : cases) {
  1137. std::vector<std::string> result;
  1138. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1139. << "value: " << c.value;
  1140. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1141. }
  1142. // An invalid entry is still rejected when empty elements surround it
  1143. std::vector<std::string> result;
  1144. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1145. }
  1146. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1147. // or ';' inside one does not end the list element or the parameter. Section
  1148. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1149. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1150. struct {
  1151. const char *value;
  1152. std::vector<std::string> expected;
  1153. } cases[] = {
  1154. {"text/html;profile=\"a,b\",application/json",
  1155. {"text/html", "application/json"}},
  1156. // A "q=" inside a quoted value is not the weight
  1157. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1158. {"text/html", "application/json"}},
  1159. // The weight after a quoted value still applies
  1160. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1161. {"application/json", "text/html"}},
  1162. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1163. {"application/json", "text/html"}},
  1164. {"text/html;profile=\"a\\\"b\",application/json",
  1165. {"text/html", "application/json"}},
  1166. // An escaped backslash does not escape the '"' after it
  1167. {"text/html;profile=\"a\\\\\",application/json",
  1168. {"text/html", "application/json"}},
  1169. };
  1170. for (const auto &c : cases) {
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1173. << "value: " << c.value;
  1174. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1175. }
  1176. }
  1177. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1178. Server svr;
  1179. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1180. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1181. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1182. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1183. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1184. res.set_content("ok", "text/plain");
  1185. });
  1186. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1187. EXPECT_TRUE(false);
  1188. res.set_content("bad request", "text/plain");
  1189. });
  1190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1191. auto se = detail::scope_exit([&] {
  1192. svr.stop();
  1193. listen_thread.join();
  1194. ASSERT_FALSE(svr.is_running());
  1195. });
  1196. svr.wait_until_ready();
  1197. Client cli("localhost", PORT);
  1198. {
  1199. auto res = cli.Get(
  1200. "/accept_ok",
  1201. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. auto res = cli.Get("/accept_bad_request",
  1207. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1209. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1210. }
  1211. }
  1212. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1213. Server svr;
  1214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1215. res.set_content("ok", "text/plain");
  1216. });
  1217. std::atomic<int> start_count{0};
  1218. std::atomic<bool> running_when_called{false};
  1219. svr.set_start_handler([&]() {
  1220. running_when_called = svr.is_running();
  1221. start_count++;
  1222. });
  1223. auto port = svr.bind_to_any_port(HOST);
  1224. std::thread t([&]() { svr.listen_after_bind(); });
  1225. auto se = detail::scope_exit([&] {
  1226. svr.stop();
  1227. t.join();
  1228. ASSERT_FALSE(svr.is_running());
  1229. });
  1230. svr.wait_until_ready();
  1231. // A successful request proves the accept loop is running, which the start
  1232. // handler precedes; so by now the handler must have run exactly once.
  1233. Client cli(HOST, port);
  1234. cli.set_connection_timeout(std::chrono::seconds(5));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1237. EXPECT_EQ(StatusCode::OK_200, res->status);
  1238. EXPECT_EQ(1, start_count.load());
  1239. EXPECT_TRUE(running_when_called.load());
  1240. }
  1241. TEST(DivideTest, DivideStringTests) {
  1242. auto divide = [](const std::string &str, char d) {
  1243. std::string lhs;
  1244. std::string rhs;
  1245. detail::divide(str, d,
  1246. [&](const char *lhs_data, std::size_t lhs_size,
  1247. const char *rhs_data, std::size_t rhs_size) {
  1248. lhs.assign(lhs_data, lhs_size);
  1249. rhs.assign(rhs_data, rhs_size);
  1250. });
  1251. return std::make_pair(std::move(lhs), std::move(rhs));
  1252. };
  1253. {
  1254. const auto res = divide("", '=');
  1255. EXPECT_EQ(res.first, "");
  1256. EXPECT_EQ(res.second, "");
  1257. }
  1258. {
  1259. const auto res = divide("=", '=');
  1260. EXPECT_EQ(res.first, "");
  1261. EXPECT_EQ(res.second, "");
  1262. }
  1263. {
  1264. const auto res = divide(" ", '=');
  1265. EXPECT_EQ(res.first, " ");
  1266. EXPECT_EQ(res.second, "");
  1267. }
  1268. {
  1269. const auto res = divide("a", '=');
  1270. EXPECT_EQ(res.first, "a");
  1271. EXPECT_EQ(res.second, "");
  1272. }
  1273. {
  1274. const auto res = divide("a=", '=');
  1275. EXPECT_EQ(res.first, "a");
  1276. EXPECT_EQ(res.second, "");
  1277. }
  1278. {
  1279. const auto res = divide("=b", '=');
  1280. EXPECT_EQ(res.first, "");
  1281. EXPECT_EQ(res.second, "b");
  1282. }
  1283. {
  1284. const auto res = divide("a=b", '=');
  1285. EXPECT_EQ(res.first, "a");
  1286. EXPECT_EQ(res.second, "b");
  1287. }
  1288. {
  1289. const auto res = divide("a=b=", '=');
  1290. EXPECT_EQ(res.first, "a");
  1291. EXPECT_EQ(res.second, "b=");
  1292. }
  1293. {
  1294. const auto res = divide("a=b=c", '=');
  1295. EXPECT_EQ(res.first, "a");
  1296. EXPECT_EQ(res.second, "b=c");
  1297. }
  1298. }
  1299. TEST(SplitTest, ParseQueryString) {
  1300. string s = "key1=val1&key2=val2&key3=val3";
  1301. Params dic;
  1302. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1303. [&](const char *b, const char *e) {
  1304. string key, val;
  1305. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1306. if (key.empty()) {
  1307. key.assign(b2, e2);
  1308. } else {
  1309. val.assign(b2, e2);
  1310. }
  1311. });
  1312. dic.emplace(key, val);
  1313. });
  1314. EXPECT_EQ("val1", dic.find("key1")->second);
  1315. EXPECT_EQ("val2", dic.find("key2")->second);
  1316. EXPECT_EQ("val3", dic.find("key3")->second);
  1317. }
  1318. TEST(SplitTest, ParseInvalidQueryTests) {
  1319. {
  1320. string s = " ";
  1321. Params dict;
  1322. detail::parse_query_text(s, dict);
  1323. EXPECT_TRUE(dict.empty());
  1324. }
  1325. {
  1326. string s = " = =";
  1327. Params dict;
  1328. detail::parse_query_text(s, dict);
  1329. EXPECT_TRUE(dict.empty());
  1330. }
  1331. }
  1332. TEST(ParseQueryTest, ParseQueryString) {
  1333. {
  1334. std::string s = "key1=val1&key2=val2&key3=val3";
  1335. Params dic;
  1336. detail::parse_query_text(s, dic);
  1337. EXPECT_EQ("val1", dic.find("key1")->second);
  1338. EXPECT_EQ("val2", dic.find("key2")->second);
  1339. EXPECT_EQ("val3", dic.find("key3")->second);
  1340. }
  1341. {
  1342. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1343. Params dic;
  1344. detail::parse_query_text(s, dic);
  1345. EXPECT_EQ("", dic.find("key1")->second);
  1346. EXPECT_EQ("val1", dic.find("key2")->second);
  1347. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1348. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1349. }
  1350. }
  1351. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1352. Params dic;
  1353. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1354. dic.emplace("key1", "val1");
  1355. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1356. dic.emplace("key2", "val2");
  1357. dic.emplace("key3", "val3");
  1358. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1359. }
  1360. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1361. Params params;
  1362. params.emplace("a", "1");
  1363. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1364. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1365. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1366. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1367. // Long enough to overflow the stack when matched with std::regex.
  1368. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1369. EXPECT_EQ("/p?" + long_query + "&a=1",
  1370. append_query_params("/p?" + long_query, params));
  1371. }
  1372. // Joins every entry of a Headers or Params into "key=value " so a whole
  1373. // traversal can be compared in one assertion. Both are instantiations of the
  1374. // same insertion-ordered container, so one helper serves both.
  1375. template <typename Map> static std::string entries_to_string(const Map &m) {
  1376. std::string s;
  1377. for (const auto &entry : m) {
  1378. s += entry.first + "=" + entry.second + " ";
  1379. }
  1380. return s;
  1381. }
  1382. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1383. // Params used to be a std::multimap, which sorted by name and handed the
  1384. // caller's query back alphabetised. A client signing its query string could
  1385. // not reproduce the order it asked for.
  1386. Params dic;
  1387. dic.emplace("zulu", "1");
  1388. dic.emplace("alpha", "2");
  1389. dic.emplace("mike", "3");
  1390. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1391. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1392. }
  1393. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1394. Params dic;
  1395. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1396. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1397. }
  1398. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1399. Request req;
  1400. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1401. req.params);
  1402. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1403. EXPECT_EQ("first", req.get_param_value("tag"));
  1404. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1405. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1406. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1407. EXPECT_EQ("", req.get_param_value("tag", 3));
  1408. }
  1409. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1410. // Params shares its container with Headers, which matches field names
  1411. // case-insensitively. Parameter names must not pick that up.
  1412. Params dic;
  1413. dic.emplace("Key", "upper");
  1414. dic.emplace("key", "lower");
  1415. EXPECT_EQ(2U, dic.size());
  1416. EXPECT_EQ(1U, dic.count("Key"));
  1417. EXPECT_EQ(1U, dic.count("key"));
  1418. EXPECT_EQ("upper", dic.find("Key")->second);
  1419. EXPECT_EQ("lower", dic.find("key")->second);
  1420. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1421. }
  1422. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1423. Server svr;
  1424. std::string order;
  1425. svr.Get("/order", [&](const Request &req, Response &res) {
  1426. order = entries_to_string(req.params);
  1427. res.set_content("ok", "text/plain");
  1428. });
  1429. auto port = svr.bind_to_any_port(HOST);
  1430. thread t = thread([&] { svr.listen_after_bind(); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. t.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, port);
  1438. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1441. }
  1442. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1443. Server svr;
  1444. std::string field_order, file_order;
  1445. svr.Post("/order", [&](const Request &req, Response &res) {
  1446. for (const auto &field : req.form.fields) {
  1447. field_order += field.first + "=" + field.second.content + " ";
  1448. }
  1449. for (const auto &file : req.form.files) {
  1450. file_order += file.first + "=" + file.second.filename + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. UploadFormDataItems items = {
  1463. {"zulu", "1", "", ""},
  1464. {"alpha", "2", "", ""},
  1465. {"mike", "3", "", ""},
  1466. {"zebra", "z", "z.txt", "text/plain"},
  1467. {"apple", "a", "a.txt", "text/plain"},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/order", items);
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1473. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1474. }
  1475. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1476. Server svr;
  1477. std::vector<std::string> values;
  1478. std::string first, second, out_of_range, order;
  1479. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1480. values = req.form.get_fields("tag");
  1481. first = req.form.get_field("tag", 0);
  1482. second = req.form.get_field("tag", 1);
  1483. out_of_range = req.form.get_field("tag", 2);
  1484. for (const auto &field : req.form.fields) {
  1485. order += field.first + "=" + field.second.content + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1498. // not adjacent in the container.
  1499. UploadFormDataItems items = {
  1500. {"tag", "first", "", ""},
  1501. {"other", "x", "", ""},
  1502. {"tag", "second", "", ""},
  1503. };
  1504. Client cli(HOST, port);
  1505. auto res = cli.Post("/repeated", items);
  1506. ASSERT_TRUE(res);
  1507. ASSERT_EQ(2U, values.size());
  1508. EXPECT_EQ("first", values[0]);
  1509. EXPECT_EQ("second", values[1]);
  1510. EXPECT_EQ("first", first);
  1511. EXPECT_EQ("second", second);
  1512. // std::multimap already kept entries sharing a name in insertion order, so
  1513. // everything above passes without this change too. The whole traversal is
  1514. // what tells the two apart: sorting by name would hoist "other" to the front
  1515. // and the two "tag" parts would end up adjacent.
  1516. EXPECT_EQ("tag=first other=x tag=second ", order);
  1517. // Advancing past the last entry of a name used to run off the container;
  1518. // the container's saturating increment makes it return the default instead.
  1519. EXPECT_EQ("", out_of_range);
  1520. }
  1521. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1522. Server svr;
  1523. std::string file_names;
  1524. svr.Post("/upload", [&](const Request &req, Response &res) {
  1525. for (const auto &file : req.form.files) {
  1526. file_names += file.first + "|" + file.second.filename + " ";
  1527. }
  1528. res.set_content("ok", "text/plain");
  1529. });
  1530. auto port = svr.bind_to_any_port(HOST);
  1531. thread t = thread([&] { svr.listen_after_bind(); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. t.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. // A trailing backslash would otherwise escape the closing quote.
  1539. UploadFormDataItems items = {
  1540. {"dir\\", "x", "a.txt", "text/plain"},
  1541. {"b", "y", "a\\\\b.txt", "text/plain"},
  1542. };
  1543. Client cli(HOST, port);
  1544. auto res = cli.Post("/upload", items);
  1545. ASSERT_TRUE(res);
  1546. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1547. }
  1548. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1549. // Server::read_content() keeps a FormFields::iterator alive across the
  1550. // content callbacks that fill the part it points at. The container is
  1551. // vector-backed, so a later emplace can reallocate and invalidate an older
  1552. // iterator; 64 parts grow the vector through seven reallocations, which
  1553. // checks that every part's content still lands in its own entry.
  1554. const size_t part_count = 64;
  1555. // One formula for both the parts sent and the values expected back, so the
  1556. // two cannot drift apart.
  1557. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1558. auto content_of = [](size_t i) {
  1559. return std::string(64, static_cast<char>('a' + (i % 26)));
  1560. };
  1561. Server svr;
  1562. std::vector<std::pair<std::string, std::string>> received;
  1563. svr.Post("/many", [&](const Request &req, Response &res) {
  1564. for (const auto &field : req.form.fields) {
  1565. received.emplace_back(field.first, field.second.content);
  1566. }
  1567. res.set_content("ok", "text/plain");
  1568. });
  1569. auto port = svr.bind_to_any_port(HOST);
  1570. thread t = thread([&] { svr.listen_after_bind(); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. t.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. UploadFormDataItems items;
  1578. for (size_t i = 0; i < part_count; i++) {
  1579. items.push_back({name_of(i), content_of(i), "", ""});
  1580. }
  1581. Client cli(HOST, port);
  1582. auto res = cli.Post("/many", items);
  1583. ASSERT_TRUE(res);
  1584. ASSERT_EQ(part_count, received.size());
  1585. for (size_t i = 0; i < part_count; i++) {
  1586. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1587. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1588. }
  1589. }
  1590. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1591. string content_type = "multipart/form-data; boundary=something";
  1592. string boundary;
  1593. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1594. EXPECT_TRUE(ret);
  1595. EXPECT_EQ(boundary, "something");
  1596. }
  1597. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1598. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1599. string boundary;
  1600. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1605. string content_type =
  1606. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1607. string boundary;
  1608. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1609. EXPECT_TRUE(ret);
  1610. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1613. string content_type =
  1614. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1615. string boundary;
  1616. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1617. EXPECT_TRUE(ret);
  1618. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1619. }
  1620. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1621. const string boundary(70, 'a');
  1622. string content_type = "multipart/form-data; boundary=" + boundary;
  1623. string parsed;
  1624. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1625. EXPECT_TRUE(ret);
  1626. EXPECT_EQ(parsed, boundary);
  1627. }
  1628. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1629. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1630. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1631. string parsed;
  1632. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1633. EXPECT_FALSE(ret);
  1634. }
  1635. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1636. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1637. // is 72 characters on the wire and still valid.
  1638. const string boundary(70, 'a');
  1639. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1640. string parsed;
  1641. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1642. EXPECT_EQ(parsed, boundary);
  1643. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1644. parsed.clear();
  1645. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1646. }
  1647. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1648. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1649. // The parameter parser must not treat that '=' as the key/value separator.
  1650. string content_type =
  1651. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1652. "charset=UTF-8";
  1653. string parsed;
  1654. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1655. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1656. }
  1657. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1658. // A ';' inside the quoted-string is part of the value, not a parameter
  1659. // separator, so it must not truncate the boundary.
  1660. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1661. string parsed;
  1662. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1663. EXPECT_EQ(parsed, "a;b");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1666. string parsed;
  1667. EXPECT_TRUE(detail::parse_multipart_boundary(
  1668. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1669. EXPECT_EQ("a\\b", parsed);
  1670. EXPECT_TRUE(detail::parse_multipart_boundary(
  1671. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1672. EXPECT_EQ("a\"b", parsed);
  1673. }
  1674. TEST(ParseDispositionParamsTest, QuotedValues) {
  1675. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1676. // ';' and '=' are ordinary characters inside one.
  1677. struct {
  1678. const char *value;
  1679. std::vector<std::pair<const char *, const char *>> expected;
  1680. } cases[] = {
  1681. {"name=\"file1\"; filename=\"a.txt\"",
  1682. {{"name", "file1"}, {"filename", "a.txt"}}},
  1683. // Whitespace around '=' and ';' is still trimmed
  1684. {"name=\"file2\" ;filename = \"a.html\"",
  1685. {{"name", "file2"}, {"filename", "a.html"}}},
  1686. // '=' inside the value used to leave only the text after the last one
  1687. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1688. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1689. {"name=\"x=y\"", {{"name", "x=y"}}},
  1690. // ';' inside the value used to truncate the pair and leave a bogus one
  1691. {"name=\"file3\"; filename=\"a;b.txt\"",
  1692. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1693. // An unquoted value keeps working, and so does filename*
  1694. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1695. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1696. // A parameter with no key is dropped rather than turned into one whose
  1697. // key is the value
  1698. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1699. // An escaped quote does not end the value
  1700. {"name=\"a\\\"; filename=evil.php\"",
  1701. {{"name", "a\"; filename=evil.php"}}},
  1702. // Other backslashes, as in a Windows path, are kept
  1703. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1704. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1705. };
  1706. for (const auto &c : cases) {
  1707. Params params;
  1708. detail::parse_disposition_params(c.value, params);
  1709. for (const auto &kv : c.expected) {
  1710. auto it = params.find(kv.first);
  1711. ASSERT_NE(it, params.end())
  1712. << "value: " << c.value << ", key: " << kv.first;
  1713. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1714. }
  1715. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1716. }
  1717. }
  1718. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1719. Server svr;
  1720. std::string filename;
  1721. std::string content;
  1722. svr.Post("/upload", [&](const Request &req, Response &) {
  1723. const auto &file = req.form.get_file("file");
  1724. filename = file.filename;
  1725. content = file.content;
  1726. });
  1727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. std::string body = "--B\r\n"
  1735. "Content-Disposition: form-data; name=\"file\"; "
  1736. "filename=\"a.txt\"\r\n"
  1737. "Content-Type: text/plain\r\n"
  1738. "\r\n"
  1739. "hello\r\n"
  1740. "--B--\r\n";
  1741. Client cli(HOST, PORT);
  1742. auto res = cli.Post(
  1743. "/upload",
  1744. [&](size_t offset, DataSink &sink) {
  1745. if (offset < body.size()) {
  1746. sink.write(&body[offset], 1);
  1747. } else {
  1748. sink.done();
  1749. }
  1750. return true;
  1751. },
  1752. "multipart/form-data; boundary=B");
  1753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1754. EXPECT_EQ(StatusCode::OK_200, res->status);
  1755. EXPECT_EQ("a.txt", filename);
  1756. EXPECT_EQ("hello", content);
  1757. }
  1758. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1759. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1760. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1761. Server svr;
  1762. std::string field_value, file_name, file_filename;
  1763. bool has_field = false, has_file = false;
  1764. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1765. has_field = req.form.has_field("x=y");
  1766. field_value = req.form.get_field("x=y");
  1767. has_file = req.form.has_file("file1");
  1768. const auto &file = req.form.get_file("file1");
  1769. file_name = file.name;
  1770. file_filename = file.filename;
  1771. res.set_content("ok", "text/plain");
  1772. });
  1773. auto port = svr.bind_to_any_port(HOST);
  1774. thread t = thread([&] { svr.listen_after_bind(); });
  1775. auto se = detail::scope_exit([&] {
  1776. svr.stop();
  1777. t.join();
  1778. ASSERT_FALSE(svr.is_running());
  1779. });
  1780. svr.wait_until_ready();
  1781. UploadFormDataItems items = {
  1782. {"x=y", "field-value", "", ""},
  1783. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1784. };
  1785. Client cli(HOST, port);
  1786. auto res = cli.Post("/quoted", items);
  1787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1788. ASSERT_EQ(StatusCode::OK_200, res->status);
  1789. EXPECT_TRUE(has_field);
  1790. EXPECT_EQ("field-value", field_value);
  1791. EXPECT_TRUE(has_file);
  1792. EXPECT_EQ("file1", file_name);
  1793. EXPECT_EQ("a;b=report.pdf", file_filename);
  1794. }
  1795. TEST(GetHeaderValueTest, DefaultValue) {
  1796. Headers headers = {{"Dummy", "Dummy"}};
  1797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1798. EXPECT_STREQ("text/plain", val);
  1799. }
  1800. TEST(GetHeaderValueTest, DefaultValueInt) {
  1801. Headers headers = {{"Dummy", "Dummy"}};
  1802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1803. EXPECT_EQ(100ull, val);
  1804. }
  1805. TEST(GetHeaderValueTest, RegularValue) {
  1806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1808. EXPECT_STREQ("text/html", val);
  1809. }
  1810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1813. EXPECT_STREQ("text/html", val);
  1814. }
  1815. TEST(GetHeaderValueTest, SetContent) {
  1816. Response res;
  1817. res.set_content("html", "text/html");
  1818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1819. res.set_content("text", "text/plain");
  1820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1822. }
  1823. TEST(GetHeaderValueTest, RegularValueInt) {
  1824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1826. EXPECT_EQ(100ull, val);
  1827. }
  1828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1829. Headers headers = {{"Content-Length", "x"}};
  1830. auto is_invalid_value = false;
  1831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1832. is_invalid_value);
  1833. EXPECT_EQ(0ull, val);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. }
  1836. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1837. // An all-digit value that overflows size_t must be reported as invalid, not
  1838. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1839. // a large length to a small one on 32-bit builds, leaving the framing length
  1840. // wrong while is_invalid_value stayed false.
  1841. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1842. auto is_invalid_value = false;
  1843. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1844. is_invalid_value);
  1845. EXPECT_TRUE(is_invalid_value);
  1846. // A well-formed length is unaffected.
  1847. Headers ok = {{"Content-Length", "1234"}};
  1848. is_invalid_value = false;
  1849. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1850. is_invalid_value);
  1851. EXPECT_EQ(1234ull, val);
  1852. EXPECT_FALSE(is_invalid_value);
  1853. }
  1854. TEST(GetHeaderValueTest, Range) {
  1855. {
  1856. Headers headers = {make_range_header({{1, -1}})};
  1857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1858. EXPECT_STREQ("bytes=1-", val);
  1859. }
  1860. {
  1861. Headers headers = {make_range_header({{-1, 1}})};
  1862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1863. EXPECT_STREQ("bytes=-1", val);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, 10}})};
  1867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1868. EXPECT_STREQ("bytes=1-10", val);
  1869. }
  1870. {
  1871. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1873. EXPECT_STREQ("bytes=1-10, 100-", val);
  1874. }
  1875. {
  1876. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1878. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1879. }
  1880. {
  1881. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1883. EXPECT_STREQ("bytes=0-0, -1", val);
  1884. }
  1885. }
  1886. TEST(BearerTokenAuthTest, SchemeValidation) {
  1887. // A value shorter than "Bearer " must not throw from the fixed-length
  1888. // substr, and a non-Bearer scheme must not be reported as a token.
  1889. struct {
  1890. const char *value;
  1891. const char *expected;
  1892. } cases[] = {
  1893. {"x", ""},
  1894. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1895. {"Bearer abc123", "abc123"},
  1896. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1897. };
  1898. for (const auto &c : cases) {
  1899. Request req;
  1900. req.set_header("Authorization", c.value);
  1901. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1905. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1906. // to depend on the standard library (libstdc++ handed back duplicates in
  1907. // reverse insertion order, libc++ in insertion order).
  1908. Request req;
  1909. req.set_header("Accept-Encoding", "gzip");
  1910. req.set_header("Accept-Encoding", "deflate");
  1911. req.set_header("Accept-Encoding", "br");
  1912. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1913. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1914. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1915. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1916. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1917. }
  1918. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1919. Request req;
  1920. req.set_header("X-Test", "only");
  1921. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1922. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1923. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1924. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1925. }
  1926. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1927. Request req;
  1928. req.set_header("X-First", "1");
  1929. req.set_header("X-Test", "2");
  1930. req.params.emplace("first", "1");
  1931. req.params.emplace("test", "2");
  1932. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1933. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1934. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1935. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1936. // The second one is negative when read as a signed value
  1937. const auto max_id = (std::numeric_limits<size_t>::max)();
  1938. for (auto id : {max_id / 2, max_id}) {
  1939. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1940. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1941. EXPECT_EQ("", req.get_param_value("test", id));
  1942. EXPECT_EQ("", req.form.get_field("test", id));
  1943. EXPECT_EQ("", req.form.get_file("test", id).content);
  1944. }
  1945. }
  1946. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1947. Headers headers;
  1948. headers.emplace("Host", "example.com");
  1949. headers.emplace("Accept-Encoding", "gzip");
  1950. headers.emplace("User-Agent", "test");
  1951. headers.emplace("Accept-Encoding", "deflate");
  1952. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1953. "Accept-Encoding=deflate ",
  1954. entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1957. Headers headers = {{"Content-Type", "text/html"},
  1958. {"CONTENT-TYPE", "text/xml"}};
  1959. EXPECT_EQ(2U, headers.count("content-type"));
  1960. auto it = headers.find("content-type");
  1961. ASSERT_TRUE(it != headers.end());
  1962. EXPECT_EQ("text/html", it->second);
  1963. }
  1964. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1965. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1966. // drop only those fields and leave everything positioned between them.
  1967. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1968. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1969. auto rng = headers.equal_range("a");
  1970. headers.erase(rng.first, rng.second);
  1971. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1972. }
  1973. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1974. Headers headers = {
  1975. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1976. EXPECT_EQ(3U, headers.erase("A"));
  1977. EXPECT_EQ(0U, headers.count("A"));
  1978. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1979. }
  1980. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1981. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1982. headers.emplace_front("Host", "example.com");
  1983. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1984. entries_to_string(headers));
  1985. }
  1986. TEST(ParseHeaderValueTest, Range) {
  1987. {
  1988. Ranges ranges;
  1989. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1990. EXPECT_TRUE(ret);
  1991. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1992. }
  1993. {
  1994. Ranges ranges;
  1995. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2008. EXPECT_FALSE(ret);
  2009. }
  2010. {
  2011. Ranges ranges;
  2012. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2013. EXPECT_TRUE(ret);
  2014. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2015. }
  2016. {
  2017. Ranges ranges;
  2018. auto ret =
  2019. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2020. EXPECT_TRUE(ret);
  2021. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2022. }
  2023. {
  2024. Ranges ranges;
  2025. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2027. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2028. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2029. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2030. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2031. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2032. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2033. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2034. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2035. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2036. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2037. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2038. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2039. EXPECT_FALSE(
  2040. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2041. EXPECT_TRUE(ranges.empty());
  2042. }
  2043. {
  2044. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2045. // remainder of the representation, so it stays accepted.
  2046. Ranges ranges;
  2047. auto ret =
  2048. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2049. EXPECT_TRUE(ret);
  2050. ASSERT_EQ(1u, ranges.size());
  2051. EXPECT_EQ(0, ranges[0].first);
  2052. EXPECT_EQ(-1, ranges[0].second);
  2053. }
  2054. // RFC 9110 14.1: range unit names are case-insensitive.
  2055. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2056. Ranges ranges;
  2057. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2058. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2059. }
  2060. }
  2061. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2062. Request req;
  2063. req.set_header("Accept-Encoding", "gzip");
  2064. Response res;
  2065. res.set_header("Content-Type", "text/plain");
  2066. auto ret = detail::encoding_type(req, res);
  2067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2081. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #else
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. #endif
  2088. }
  2089. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding",
  2092. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2098. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2100. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2102. #else
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. #endif
  2105. }
  2106. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2107. // All supported encodings rejected with q=0 should return None
  2108. Request req;
  2109. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2110. Response res;
  2111. res.set_header("Content-Type", "text/plain");
  2112. auto ret = detail::encoding_type(req, res);
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. }
  2115. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2116. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. EXPECT_TRUE(ret == detail::EncodingType::None);
  2123. }
  2124. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2125. Request req;
  2126. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2127. Response res;
  2128. res.set_header("Content-Type", "text/plain");
  2129. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2130. }
  2131. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2132. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2133. Request req;
  2134. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2135. Response res;
  2136. res.set_header("Content-Type", "text/plain");
  2137. auto ret = detail::encoding_type(req, res);
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. }
  2140. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2141. // RFC 7231: Accept-Encoding values are case-insensitive
  2142. Request req;
  2143. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2144. Response res;
  2145. res.set_header("Content-Type", "text/plain");
  2146. auto ret = detail::encoding_type(req, res);
  2147. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2149. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2151. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2152. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2153. #else
  2154. EXPECT_TRUE(ret == detail::EncodingType::None);
  2155. #endif
  2156. }
  2157. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2158. // q value should determine priority, not hardcoded order
  2159. Request req;
  2160. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2161. Response res;
  2162. res.set_header("Content-Type", "text/plain");
  2163. auto ret = detail::encoding_type(req, res);
  2164. // gzip has highest q=1.0, so it should be selected even though
  2165. // br and zstd are also supported
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2169. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2170. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2171. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2172. #else
  2173. EXPECT_TRUE(ret == detail::EncodingType::None);
  2174. #endif
  2175. }
  2176. TEST(BufferStreamTest, read) {
  2177. detail::BufferStream strm1;
  2178. Stream &strm = strm1;
  2179. EXPECT_EQ(5, strm.write("hello"));
  2180. char buf[512];
  2181. EXPECT_EQ(2, strm.read(buf, 2));
  2182. EXPECT_EQ('h', buf[0]);
  2183. EXPECT_EQ('e', buf[1]);
  2184. EXPECT_EQ(2, strm.read(buf, 2));
  2185. EXPECT_EQ('l', buf[0]);
  2186. EXPECT_EQ('l', buf[1]);
  2187. EXPECT_EQ(1, strm.read(buf, 1));
  2188. EXPECT_EQ('o', buf[0]);
  2189. EXPECT_EQ(0, strm.read(buf, 1));
  2190. }
  2191. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2192. auto host = "www.httpwatch.com";
  2193. auto ip = hosted_at(host);
  2194. EXPECT_EQ("23.96.13.243", ip);
  2195. std::vector<std::string> addrs;
  2196. hosted_at(host, addrs);
  2197. EXPECT_EQ(1u, addrs.size());
  2198. }
  2199. #if 0 // It depends on each test environment...
  2200. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2201. auto host = "www.youtube.com";
  2202. std::vector<std::string> addrs;
  2203. hosted_at(host, addrs);
  2204. EXPECT_EQ(20u, addrs.size());
  2205. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2206. EXPECT_TRUE(it != addrs.end());
  2207. }
  2208. #endif
  2209. class ChunkedEncodingTest : public ::testing::Test {
  2210. protected:
  2211. ChunkedEncodingTest()
  2212. : cli_(HOST, PORT)
  2213. #ifdef CPPHTTPLIB_SSL_ENABLED
  2214. ,
  2215. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2216. #endif
  2217. {
  2218. cli_.set_connection_timeout(2);
  2219. #ifdef CPPHTTPLIB_SSL_ENABLED
  2220. cli_.enable_server_certificate_verification(false);
  2221. #endif
  2222. }
  2223. virtual void SetUp() {
  2224. read_file("./image.jpg", image_data_);
  2225. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2226. res.set_content("Hello World!", "text/plain");
  2227. });
  2228. svr_.Get(
  2229. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2230. res.set_chunked_content_provider(
  2231. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2232. size_t remaining = image_data_.size() - offset;
  2233. if (remaining == 0) {
  2234. sink.done();
  2235. } else {
  2236. constexpr size_t CHUNK_SIZE = 1024;
  2237. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2238. sink.write(&image_data_[offset], send_size);
  2239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2240. }
  2241. return true;
  2242. });
  2243. });
  2244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2245. svr_.wait_until_ready();
  2246. }
  2247. virtual void TearDown() {
  2248. svr_.stop();
  2249. if (!request_threads_.empty()) {
  2250. std::this_thread::sleep_for(std::chrono::seconds(1));
  2251. for (auto &t : request_threads_) {
  2252. t.join();
  2253. }
  2254. }
  2255. t_.join();
  2256. }
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. SSLClient cli_;
  2259. SSLServer svr_;
  2260. #else
  2261. Client cli_;
  2262. Server svr_;
  2263. #endif
  2264. thread t_;
  2265. std::vector<thread> request_threads_;
  2266. std::string image_data_;
  2267. };
  2268. TEST_F(ChunkedEncodingTest, NormalGet) {
  2269. auto res = cli_.Get("/chunked");
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. std::string out;
  2272. read_file("./image.jpg", out);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. EXPECT_EQ(out, res->body);
  2275. }
  2276. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2277. std::string body;
  2278. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2279. body.append(data, data_length);
  2280. return true;
  2281. });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. std::string out;
  2284. read_file("./image.jpg", out);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. EXPECT_EQ(out, body);
  2287. }
  2288. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2289. std::string body;
  2290. auto res = cli_.Get(
  2291. "/chunked",
  2292. [&](const Response &response) {
  2293. EXPECT_EQ(StatusCode::OK_200, response.status);
  2294. return true;
  2295. },
  2296. [&](const char *data, size_t data_length) {
  2297. body.append(data, data_length);
  2298. return true;
  2299. });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. std::string out;
  2302. read_file("./image.jpg", out);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ(out, body);
  2305. }
  2306. TEST(RangeTest, FromHTTPBin_Online) {
  2307. auto host = "httpbingo.org";
  2308. auto path = std::string{"/range/32"};
  2309. #ifdef CPPHTTPLIB_SSL_ENABLED
  2310. auto port = 443;
  2311. SSLClient cli(host, port);
  2312. #else
  2313. auto port = 80;
  2314. Client cli(host, port);
  2315. #endif
  2316. cli.set_connection_timeout(5);
  2317. {
  2318. auto res = cli.Get(path);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. }
  2323. {
  2324. Headers headers = {make_range_header({{1, -1}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2329. }
  2330. {
  2331. Headers headers = {make_range_header({{1, 10}})};
  2332. auto res = cli.Get(path, headers);
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ("bcdefghijk", res->body);
  2335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2336. }
  2337. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2338. // entire resource, while the original httpbin returned 200. Both are
  2339. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2340. {
  2341. Headers headers = {make_range_header({{0, 31}})};
  2342. auto res = cli.Get(path, headers);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2345. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2346. res->status == StatusCode::PartialContent_206);
  2347. }
  2348. {
  2349. Headers headers = {make_range_header({{0, -1}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2354. res->status == StatusCode::PartialContent_206);
  2355. }
  2356. // go-httpbin returns 206 with clamped range for over-range requests,
  2357. // while the original httpbin returned 416. Both behaviors are observed
  2358. // in real servers, so we only verify the request succeeds.
  2359. {
  2360. Headers headers = {make_range_header({{0, 32}})};
  2361. auto res = cli.Get(path, headers);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. }
  2364. }
  2365. TEST(RangeTest, IgnoredForPost) {
  2366. Server svr;
  2367. svr.Post("/", [](const Request &, Response &res) {
  2368. res.set_content("abcdefg", "text/plain");
  2369. });
  2370. auto port = svr.bind_to_any_port(HOST);
  2371. ASSERT_GT(port, 0);
  2372. thread t = thread([&] { svr.listen_after_bind(); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. t.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, port);
  2380. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2381. auto res = cli.Post("/", Headers{{"Range", range}});
  2382. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2383. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2384. EXPECT_EQ("abcdefg", res->body) << range;
  2385. }
  2386. }
  2387. TEST(RangeTest, IgnoredForUnknownUnit) {
  2388. Server svr;
  2389. svr.Get("/", [](const Request &, Response &res) {
  2390. res.set_content("abcdefg", "text/plain");
  2391. });
  2392. auto port = svr.bind_to_any_port(HOST);
  2393. ASSERT_GT(port, 0);
  2394. thread t = thread([&] { svr.listen_after_bind(); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. t.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. Client cli(HOST, port);
  2402. for (auto range : {"items=1-2", "none=x"}) {
  2403. auto res = cli.Get("/", Headers{{"Range", range}});
  2404. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2405. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2406. EXPECT_EQ("abcdefg", res->body) << range;
  2407. }
  2408. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2409. ASSERT_TRUE(res) << to_string(res.error());
  2410. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2411. }
  2412. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2413. auto host = "unresolvableaddress.local";
  2414. auto path = std::string{"/"};
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. auto port = 443;
  2417. SSLClient cli(host, port);
  2418. #else
  2419. auto port = 80;
  2420. Client cli(host, port);
  2421. #endif
  2422. cli.set_connection_timeout(1);
  2423. {
  2424. auto res = cli.Get(path);
  2425. ASSERT_FALSE(res);
  2426. }
  2427. std::this_thread::sleep_for(std::chrono::seconds(8));
  2428. }
  2429. #if defined(__linux__) && defined(__GLIBC__) && \
  2430. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2431. // Forward declaration: in split builds split.py strips `inline` and moves the
  2432. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2433. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2434. // against the symbol in both header-only and split builds.
  2435. namespace httplib {
  2436. namespace detail {
  2437. int getaddrinfo_with_timeout(const char *node, const char *service,
  2438. const struct addrinfo *hints,
  2439. struct addrinfo **res, time_t timeout_sec);
  2440. } // namespace detail
  2441. } // namespace httplib
  2442. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2443. //
  2444. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2445. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2446. // gai_suspend() call hits the connection timeout the function calls
  2447. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2448. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2449. // still alive and still references the now-destroyed stack frame.
  2450. //
  2451. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2452. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2453. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2454. // and runs them in a container.
  2455. namespace {
  2456. bool should_run_issue_2431_tests() {
  2457. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2458. return v && *v && std::string(v) != "0";
  2459. }
  2460. std::string unique_unresolvable_host(int n) {
  2461. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2462. // glibc still asks the configured nameserver — which is exactly the path
  2463. // we want to exercise. A unique label per call avoids the resolver cache.
  2464. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2465. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2466. std::to_string(n) + ".invalid";
  2467. }
  2468. } // namespace
  2469. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2470. if (!should_run_issue_2431_tests()) {
  2471. GTEST_SKIP()
  2472. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2473. }
  2474. for (int i = 0; i < 8; ++i) {
  2475. struct addrinfo hints;
  2476. memset(&hints, 0, sizeof(hints));
  2477. hints.ai_family = AF_UNSPEC;
  2478. hints.ai_socktype = SOCK_STREAM;
  2479. auto host = unique_unresolvable_host(i);
  2480. struct addrinfo *result = nullptr;
  2481. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2482. &result, /*timeout_sec=*/1);
  2483. if (rc == 0 && result) { freeaddrinfo(result); }
  2484. }
  2485. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2486. // stack region they still believe holds their gaicb.
  2487. std::this_thread::sleep_for(std::chrono::seconds(3));
  2488. }
  2489. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2490. if (!should_run_issue_2431_tests()) {
  2491. GTEST_SKIP()
  2492. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2493. }
  2494. std::atomic<bool> stop{false};
  2495. std::vector<std::thread> threads;
  2496. for (int t = 0; t < 8; ++t) {
  2497. threads.emplace_back([t, &stop] {
  2498. int i = 0;
  2499. while (!stop.load(std::memory_order_relaxed)) {
  2500. struct addrinfo hints;
  2501. memset(&hints, 0, sizeof(hints));
  2502. hints.ai_family = AF_UNSPEC;
  2503. hints.ai_socktype = SOCK_STREAM;
  2504. auto host = unique_unresolvable_host(t * 100000 + i++);
  2505. struct addrinfo *result = nullptr;
  2506. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2507. &result, /*timeout_sec=*/1);
  2508. if (rc == 0 && result) { freeaddrinfo(result); }
  2509. }
  2510. });
  2511. }
  2512. std::this_thread::sleep_for(std::chrono::seconds(8));
  2513. stop.store(true, std::memory_order_relaxed);
  2514. for (auto &th : threads) {
  2515. th.join();
  2516. }
  2517. std::this_thread::sleep_for(std::chrono::seconds(3));
  2518. }
  2519. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2520. if (!should_run_issue_2431_tests()) {
  2521. GTEST_SKIP()
  2522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2523. }
  2524. std::atomic<bool> stop{false};
  2525. std::vector<std::thread> threads;
  2526. for (int t = 0; t < 8; ++t) {
  2527. threads.emplace_back([t, &stop] {
  2528. int i = 0;
  2529. while (!stop.load(std::memory_order_relaxed)) {
  2530. auto host = unique_unresolvable_host(t * 100000 + i++);
  2531. Client cli(host, 80);
  2532. cli.set_connection_timeout(1, 0);
  2533. cli.set_read_timeout(1, 0);
  2534. cli.set_write_timeout(1, 0);
  2535. (void)cli.Get("/");
  2536. }
  2537. });
  2538. }
  2539. std::this_thread::sleep_for(std::chrono::seconds(8));
  2540. stop.store(true, std::memory_order_relaxed);
  2541. for (auto &th : threads) {
  2542. th.join();
  2543. }
  2544. std::this_thread::sleep_for(std::chrono::seconds(3));
  2545. }
  2546. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2547. TEST(ConnectionErrorTest, InvalidHost) {
  2548. auto host = "-abcde.com";
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(2));
  2557. auto res = cli.Get("/");
  2558. ASSERT_TRUE(!res);
  2559. EXPECT_EQ(Error::Connection, res.error());
  2560. }
  2561. TEST(ConnectionErrorTest, InvalidHost2) {
  2562. auto host = "httpcan.org/";
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. SSLClient cli(host);
  2565. #else
  2566. Client cli(host);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(2));
  2569. auto res = cli.Get("/");
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Connection, res.error());
  2572. }
  2573. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2574. auto host = "httpcan.org/";
  2575. #ifdef CPPHTTPLIB_SSL_ENABLED
  2576. SSLClient cli(host);
  2577. #else
  2578. Client cli(host);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(2));
  2581. auto res = cli.Get("/");
  2582. ASSERT_TRUE(!res);
  2583. stringstream s;
  2584. s << "error code: " << res.error();
  2585. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2586. }
  2587. TEST(ConnectionErrorTest, InvalidPort) {
  2588. auto host = "localhost";
  2589. auto port = 44380;
  2590. #ifdef CPPHTTPLIB_SSL_ENABLED
  2591. SSLClient cli(host, port);
  2592. #else
  2593. Client cli(host, port);
  2594. #endif
  2595. cli.set_connection_timeout(std::chrono::seconds(2));
  2596. auto res = cli.Get("/");
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_TRUE(Error::Connection == res.error() ||
  2599. Error::ConnectionTimeout == res.error());
  2600. }
  2601. TEST(ConnectionErrorTest, Timeout_Online) {
  2602. auto host = "google.com";
  2603. #ifdef CPPHTTPLIB_SSL_ENABLED
  2604. auto port = 44380;
  2605. SSLClient cli(host, port);
  2606. #else
  2607. auto port = 8080;
  2608. Client cli(host, port);
  2609. #endif
  2610. cli.set_connection_timeout(std::chrono::seconds(2));
  2611. // only probe one address type so that the error reason
  2612. // correlates to the timed-out IPv4, not the unsupported
  2613. // IPv6 connection attempt
  2614. cli.set_address_family(AF_INET);
  2615. auto res = cli.Get("/");
  2616. ASSERT_TRUE(!res);
  2617. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2618. }
  2619. TEST(CancelTest, NoCancel_Online) {
  2620. auto host = "httpbingo.org";
  2621. auto path = std::string{"/range/32"};
  2622. #ifdef CPPHTTPLIB_SSL_ENABLED
  2623. auto port = 443;
  2624. SSLClient cli(host, port);
  2625. #else
  2626. auto port = 80;
  2627. Client cli(host, port);
  2628. #endif
  2629. cli.set_connection_timeout(std::chrono::seconds(5));
  2630. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2636. // Use /bytes with a large payload so that the DownloadProgress callback
  2637. // (which only fires for Content-Length responses) is invoked before the
  2638. // entire body is received, giving cancellation a chance to fire.
  2639. auto host = "httpbingo.org";
  2640. auto path = std::string{"/bytes/524288"};
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. auto port = 443;
  2643. SSLClient cli(host, port);
  2644. #else
  2645. auto port = 80;
  2646. Client cli(host, port);
  2647. #endif
  2648. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2649. cli.set_connection_timeout(std::chrono::seconds(5));
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, WithCancelLargePayload_Online) {
  2654. auto host = "httpbingo.org";
  2655. auto path = std::string{"/bytes/524288"};
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. auto port = 443;
  2658. SSLClient cli(host, port);
  2659. #else
  2660. auto port = 80;
  2661. Client cli(host, port);
  2662. #endif
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. uint32_t count = 0;
  2665. auto res =
  2666. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2667. ASSERT_TRUE(!res);
  2668. EXPECT_EQ(Error::Canceled, res.error());
  2669. }
  2670. TEST(CancelTest, NoCancelPost) {
  2671. Server svr;
  2672. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2673. res.set_content("Hello World!", "text/plain");
  2674. });
  2675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2676. auto se = detail::scope_exit([&] {
  2677. svr.stop();
  2678. thread.join();
  2679. ASSERT_FALSE(svr.is_running());
  2680. });
  2681. svr.wait_until_ready();
  2682. Client cli(HOST, PORT);
  2683. cli.set_connection_timeout(std::chrono::seconds(5));
  2684. auto res =
  2685. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2686. "application/json", [](uint64_t, uint64_t) { return true; });
  2687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2688. EXPECT_EQ("Hello World!", res->body);
  2689. EXPECT_EQ(StatusCode::OK_200, res->status);
  2690. }
  2691. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2692. Server svr;
  2693. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2694. res.set_content("Hello World!", "text/plain");
  2695. });
  2696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2697. auto se = detail::scope_exit([&] {
  2698. svr.stop();
  2699. thread.join();
  2700. ASSERT_FALSE(svr.is_running());
  2701. });
  2702. svr.wait_until_ready();
  2703. Client cli(HOST, PORT);
  2704. cli.set_connection_timeout(std::chrono::seconds(5));
  2705. auto res =
  2706. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2707. "application/json", [](uint64_t, uint64_t) { return false; });
  2708. ASSERT_TRUE(!res);
  2709. EXPECT_EQ(Error::Canceled, res.error());
  2710. }
  2711. TEST(CancelTest, WithCancelLargePayloadPost) {
  2712. Server svr;
  2713. svr.set_payload_max_length(200 * 1024 * 1024);
  2714. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2715. res.set_content(LARGE_DATA, "text/plain");
  2716. });
  2717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2718. auto se = detail::scope_exit([&] {
  2719. svr.stop();
  2720. thread.join();
  2721. ASSERT_FALSE(svr.is_running());
  2722. });
  2723. svr.wait_until_ready();
  2724. Client cli(HOST, PORT);
  2725. cli.set_payload_max_length(200 * 1024 * 1024);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return false; });
  2730. ASSERT_TRUE(!res);
  2731. EXPECT_EQ(Error::Canceled, res.error());
  2732. }
  2733. TEST(CancelTest, NoCancelPut) {
  2734. Server svr;
  2735. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2736. res.set_content("Hello World!", "text/plain");
  2737. });
  2738. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2739. auto se = detail::scope_exit([&] {
  2740. svr.stop();
  2741. thread.join();
  2742. ASSERT_FALSE(svr.is_running());
  2743. });
  2744. svr.wait_until_ready();
  2745. Client cli(HOST, PORT);
  2746. cli.set_connection_timeout(std::chrono::seconds(5));
  2747. auto res =
  2748. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2749. "application/json", [](uint64_t, uint64_t) { return true; });
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ("Hello World!", res->body);
  2752. EXPECT_EQ(StatusCode::OK_200, res->status);
  2753. }
  2754. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2755. Server svr;
  2756. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!", "text/plain");
  2758. });
  2759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2760. auto se = detail::scope_exit([&] {
  2761. svr.stop();
  2762. thread.join();
  2763. ASSERT_FALSE(svr.is_running());
  2764. });
  2765. svr.wait_until_ready();
  2766. Client cli(HOST, PORT);
  2767. cli.set_connection_timeout(std::chrono::seconds(5));
  2768. auto res =
  2769. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2770. "application/json", [](uint64_t, uint64_t) { return false; });
  2771. ASSERT_TRUE(!res);
  2772. EXPECT_EQ(Error::Canceled, res.error());
  2773. }
  2774. TEST(CancelTest, WithCancelLargePayloadPut) {
  2775. Server svr;
  2776. svr.set_payload_max_length(200 * 1024 * 1024);
  2777. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2778. res.set_content(LARGE_DATA, "text/plain");
  2779. });
  2780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2781. auto se = detail::scope_exit([&] {
  2782. svr.stop();
  2783. thread.join();
  2784. ASSERT_FALSE(svr.is_running());
  2785. });
  2786. svr.wait_until_ready();
  2787. Client cli(HOST, PORT);
  2788. cli.set_payload_max_length(200 * 1024 * 1024);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return false; });
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST(CancelTest, NoCancelPatch) {
  2797. Server svr;
  2798. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2799. res.set_content("Hello World!", "text/plain");
  2800. });
  2801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2802. auto se = detail::scope_exit([&] {
  2803. svr.stop();
  2804. thread.join();
  2805. ASSERT_FALSE(svr.is_running());
  2806. });
  2807. svr.wait_until_ready();
  2808. Client cli(HOST, PORT);
  2809. cli.set_connection_timeout(std::chrono::seconds(5));
  2810. auto res =
  2811. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2812. "application/json", [](uint64_t, uint64_t) { return true; });
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. EXPECT_EQ(StatusCode::OK_200, res->status);
  2816. }
  2817. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2818. Server svr;
  2819. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2820. res.set_content("Hello World!", "text/plain");
  2821. });
  2822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2823. auto se = detail::scope_exit([&] {
  2824. svr.stop();
  2825. thread.join();
  2826. ASSERT_FALSE(svr.is_running());
  2827. });
  2828. svr.wait_until_ready();
  2829. Client cli(HOST, PORT);
  2830. cli.set_connection_timeout(std::chrono::seconds(5));
  2831. auto res =
  2832. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2833. "application/json", [](uint64_t, uint64_t) { return false; });
  2834. ASSERT_TRUE(!res);
  2835. EXPECT_EQ(Error::Canceled, res.error());
  2836. }
  2837. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2838. Server svr;
  2839. svr.set_payload_max_length(200 * 1024 * 1024);
  2840. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2841. res.set_content(LARGE_DATA, "text/plain");
  2842. });
  2843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2844. auto se = detail::scope_exit([&] {
  2845. svr.stop();
  2846. thread.join();
  2847. ASSERT_FALSE(svr.is_running());
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, PORT);
  2851. cli.set_payload_max_length(200 * 1024 * 1024);
  2852. cli.set_connection_timeout(std::chrono::seconds(5));
  2853. auto res =
  2854. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2855. "application/json", [](uint64_t, uint64_t) { return false; });
  2856. ASSERT_TRUE(!res);
  2857. EXPECT_EQ(Error::Canceled, res.error());
  2858. }
  2859. TEST(CancelTest, NoCancelDelete) {
  2860. Server svr;
  2861. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2862. res.set_content("Hello World!", "text/plain");
  2863. });
  2864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2865. auto se = detail::scope_exit([&] {
  2866. svr.stop();
  2867. thread.join();
  2868. ASSERT_FALSE(svr.is_running());
  2869. });
  2870. svr.wait_until_ready();
  2871. Client cli(HOST, PORT);
  2872. cli.set_connection_timeout(std::chrono::seconds(5));
  2873. auto res =
  2874. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2875. "application/json", [](uint64_t, uint64_t) { return true; });
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ("Hello World!", res->body);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2881. Server svr;
  2882. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2883. res.set_content("Hello World!", "text/plain");
  2884. });
  2885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2886. auto se = detail::scope_exit([&] {
  2887. svr.stop();
  2888. thread.join();
  2889. ASSERT_FALSE(svr.is_running());
  2890. });
  2891. svr.wait_until_ready();
  2892. Client cli(HOST, PORT);
  2893. cli.set_connection_timeout(std::chrono::seconds(5));
  2894. auto res =
  2895. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2896. "application/json", [](uint64_t, uint64_t) { return false; });
  2897. ASSERT_TRUE(!res);
  2898. EXPECT_EQ(Error::Canceled, res.error());
  2899. }
  2900. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2901. Server svr;
  2902. svr.set_payload_max_length(200 * 1024 * 1024);
  2903. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2904. res.set_content(LARGE_DATA, "text/plain");
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. Client cli(HOST, PORT);
  2914. cli.set_payload_max_length(200 * 1024 * 1024);
  2915. cli.set_connection_timeout(std::chrono::seconds(5));
  2916. auto res =
  2917. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2918. "application/json", [](uint64_t, uint64_t) { return false; });
  2919. ASSERT_TRUE(!res);
  2920. EXPECT_EQ(Error::Canceled, res.error());
  2921. }
  2922. // One stop() from another thread ends a request that waits for the response
  2923. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2924. Server svr;
  2925. std::atomic<bool> received{false};
  2926. std::atomic<bool> done{false};
  2927. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2928. received.store(true);
  2929. while (!done.load()) {
  2930. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2931. }
  2932. res.set_content("Hello World!", "text/plain");
  2933. });
  2934. auto port = svr.bind_to_any_port(HOST);
  2935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2936. Client cli(HOST, port);
  2937. cli.set_read_timeout(std::chrono::seconds(30));
  2938. std::future<Result> request;
  2939. auto se = detail::scope_exit([&] {
  2940. done.store(true);
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  2947. for (int i = 0; i < 500 && !received.load(); ++i) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2949. }
  2950. ASSERT_TRUE(received.load());
  2951. // Let the client block in the wait for the response
  2952. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2953. auto start = std::chrono::steady_clock::now();
  2954. cli.stop();
  2955. ASSERT_EQ(std::future_status::ready,
  2956. request.wait_for(std::chrono::seconds(5)));
  2957. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  2958. auto res = request.get();
  2959. ASSERT_TRUE(!res);
  2960. EXPECT_EQ(Error::Read, res.error());
  2961. }
  2962. static std::string remove_whitespace(const std::string &input) {
  2963. std::string output;
  2964. output.reserve(input.size());
  2965. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2966. [](unsigned char c) { return !std::isspace(c); });
  2967. return output;
  2968. }
  2969. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2970. auto host = "httpbingo.org";
  2971. auto path = std::string{"/basic-auth/hello/world"};
  2972. #ifdef CPPHTTPLIB_SSL_ENABLED
  2973. auto port = 443;
  2974. SSLClient cli(host, port);
  2975. #else
  2976. auto port = 80;
  2977. Client cli(host, port);
  2978. #endif
  2979. {
  2980. auto res = cli.Get(path);
  2981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2982. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2983. }
  2984. {
  2985. auto res = cli.Get(
  2986. path, Headers{make_basic_authentication_header("hello", "world")});
  2987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2988. auto body = remove_whitespace(res->body);
  2989. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2990. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2991. EXPECT_EQ(StatusCode::OK_200, res->status);
  2992. }
  2993. {
  2994. cli.set_basic_auth("hello", "world");
  2995. auto res = cli.Get(path);
  2996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2997. auto body = remove_whitespace(res->body);
  2998. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2999. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3000. EXPECT_EQ(StatusCode::OK_200, res->status);
  3001. }
  3002. {
  3003. cli.set_basic_auth("hello", "bad");
  3004. auto res = cli.Get(path);
  3005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3006. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3007. }
  3008. {
  3009. cli.set_basic_auth("bad", "world");
  3010. auto res = cli.Get(path);
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3013. }
  3014. }
  3015. #ifdef CPPHTTPLIB_SSL_ENABLED
  3016. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3017. auto host = "httpbingo.org";
  3018. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3019. auto paths = std::vector<std::string>{
  3020. "/digest-auth/auth/hello/world/MD5",
  3021. "/digest-auth/auth/hello/world/SHA-256",
  3022. };
  3023. auto port = 443;
  3024. SSLClient cli(host, port);
  3025. {
  3026. auto res = cli.Get(unauth_path);
  3027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3028. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3029. }
  3030. {
  3031. cli.set_digest_auth("hello", "world");
  3032. for (const auto &path : paths) {
  3033. auto res = cli.Get(path.c_str());
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. auto body = remove_whitespace(res->body);
  3036. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3037. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3038. EXPECT_EQ(StatusCode::OK_200, res->status);
  3039. }
  3040. cli.set_digest_auth("hello", "bad");
  3041. for (const auto &path : paths) {
  3042. auto res = cli.Get(path.c_str());
  3043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3044. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3045. }
  3046. }
  3047. }
  3048. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3049. // comma-separated list of challenges, and each challenge may itself carry a
  3050. // comma-separated auth-param list, so a server can legally offer Basic
  3051. // before Digest, either as two field lines or packed into one. Runs one 401
  3052. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3053. // value() joins them in receipt order) and checks that the retry carries a
  3054. // well-formed Digest Authorization header naming expected_realm.
  3055. static void
  3056. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3057. const std::string &expected_realm) {
  3058. std::atomic<int> hits{0};
  3059. Server svr;
  3060. svr.Get("/x", [&](const Request &req, Response &res) {
  3061. if (++hits == 1) {
  3062. res.status = StatusCode::Unauthorized_401;
  3063. for (const auto &challenge : challenges) {
  3064. res.set_header("WWW-Authenticate", challenge);
  3065. }
  3066. } else {
  3067. auto authorization = req.get_header_value("Authorization");
  3068. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3069. EXPECT_NE(std::string::npos,
  3070. authorization.find("realm=\"" + expected_realm + "\""));
  3071. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. }
  3088. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3089. static const char *kDigestChallenge =
  3090. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3091. "algorithm=MD5";
  3092. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3093. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3094. "testrealm");
  3095. }
  3096. // Same challenge list with the schemes in the opposite order, to make sure
  3097. // the fix above didn't just special-case "Basic first".
  3098. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3099. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3100. "testrealm");
  3101. }
  3102. // A comma inside a quoted auth-param value must not be mistaken for the
  3103. // separator between two challenges (or two auth-params).
  3104. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3105. run_digest_challenge_list_test(
  3106. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3107. "algorithm=MD5"},
  3108. "test,realm");
  3109. }
  3110. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3111. // the params and leaves out the fragment.
  3112. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3113. Server svr;
  3114. std::string uri, target;
  3115. svr.Get("/a b", [&](const Request &req, Response &res) {
  3116. auto auth = req.get_header_value("Authorization");
  3117. if (auth.empty()) {
  3118. res.status = StatusCode::Unauthorized_401;
  3119. res.set_header("WWW-Authenticate",
  3120. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3121. return;
  3122. }
  3123. auto b = auth.find("uri=\"") + 5;
  3124. uri = auth.substr(b, auth.find('"', b) - b);
  3125. target = req.target;
  3126. });
  3127. auto port = svr.bind_to_any_port(HOST);
  3128. std::thread t([&]() { svr.listen_after_bind(); });
  3129. auto se = detail::scope_exit([&] {
  3130. svr.stop();
  3131. t.join();
  3132. });
  3133. svr.wait_until_ready();
  3134. Client cli(HOST, port);
  3135. cli.set_digest_auth("hello", "world");
  3136. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ("/a%20b?x=1", target);
  3139. EXPECT_EQ(target, uri);
  3140. }
  3141. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3142. // make_digest_authentication_header() dereferences both unconditionally, so
  3143. // a server sending a challenge missing either one must not be treated as
  3144. // usable -- doing so used to crash the client with std::out_of_range.
  3145. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3146. Server svr;
  3147. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3148. res.status = StatusCode::Unauthorized_401;
  3149. res.set_header("WWW-Authenticate", challenge);
  3150. });
  3151. auto port = svr.bind_to_any_port(HOST);
  3152. std::thread t([&]() { svr.listen_after_bind(); });
  3153. auto se = detail::scope_exit([&] {
  3154. svr.stop();
  3155. t.join();
  3156. });
  3157. svr.wait_until_ready();
  3158. Client cli(HOST, port);
  3159. cli.set_digest_auth("hello", "world");
  3160. auto res = cli.Get("/x");
  3161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3162. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3163. }
  3164. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3165. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3166. }
  3167. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3168. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3169. }
  3170. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3171. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3172. }
  3173. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3174. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3175. // when storing the values, so the header builder has to re-escape them (and
  3176. // keep algorithm a bare token); otherwise the value breaks out of its
  3177. // quoted-string and injects extra auth-params into the client's Authorization.
  3178. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3179. std::atomic<int> hits{0};
  3180. std::string authorization;
  3181. Server svr;
  3182. svr.Get("/x", [&](const Request &req, Response &res) {
  3183. if (++hits == 1) {
  3184. res.status = StatusCode::Unauthorized_401;
  3185. // On the wire the quotes embedded in the values are backslash-escaped.
  3186. res.set_header("WWW-Authenticate",
  3187. "Digest realm=\"testrealm\", "
  3188. "nonce=\"n\\\"; injected=\\\"x\", "
  3189. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3190. } else {
  3191. authorization = req.get_header_value("Authorization");
  3192. res.set_content("ok", "text/plain");
  3193. }
  3194. });
  3195. auto port = svr.bind_to_any_port(HOST);
  3196. std::thread t([&]() { svr.listen_after_bind(); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. t.join();
  3200. });
  3201. svr.wait_until_ready();
  3202. Client cli(HOST, port);
  3203. cli.set_digest_auth("hello", "world");
  3204. auto res = cli.Get("/x");
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(2, hits.load());
  3207. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3208. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3209. // inside its quoted-string rather than starting an "injected" auth-param.
  3210. EXPECT_NE(std::string::npos,
  3211. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3212. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3213. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3214. }
  3215. #endif
  3216. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3217. auto host = "google.com";
  3218. auto another_host = "example.com";
  3219. auto wrong_ip = "0.0.0.0";
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3226. auto res = cli.Get("/");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3229. }
  3230. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3231. auto host = "google.com";
  3232. auto wrong_ip = "0.0.0.0";
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3239. auto res = cli.Get("/");
  3240. ASSERT_TRUE(!res);
  3241. EXPECT_EQ(Error::Connection, res.error());
  3242. }
  3243. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3244. // A mapped value that is not an IP literal must be resolved. "localhost"
  3245. // resolves from the hosts file, so this test needs no external DNS.
  3246. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3247. auto host = "target.invalid";
  3248. Server svr;
  3249. std::string received_host;
  3250. svr.Get("/hi", [&](const Request &req, Response &res) {
  3251. received_host = req.get_header_value("Host");
  3252. res.set_content("Hello World!", "text/plain");
  3253. });
  3254. auto port = svr.bind_to_any_port(HOST);
  3255. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3256. auto se = detail::scope_exit([&] {
  3257. svr.stop();
  3258. thread.join();
  3259. ASSERT_FALSE(svr.is_running());
  3260. });
  3261. svr.wait_until_ready();
  3262. Client cli(host, port);
  3263. cli.set_direct_hostname_addr_map({{host, HOST}});
  3264. auto res = cli.Get("/hi");
  3265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3266. EXPECT_EQ(StatusCode::OK_200, res->status);
  3267. // The mapping only redirects the connection; the identity stays host_.
  3268. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3269. }
  3270. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3271. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3272. auto host = "target.invalid";
  3273. Server svr;
  3274. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3275. res.set_content("Hello World!", "text/plain");
  3276. });
  3277. auto port = svr.bind_to_any_port("127.0.0.1");
  3278. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3279. auto se = detail::scope_exit([&] {
  3280. svr.stop();
  3281. thread.join();
  3282. ASSERT_FALSE(svr.is_running());
  3283. });
  3284. svr.wait_until_ready();
  3285. Client cli(host, port);
  3286. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3287. auto res = cli.Get("/hi");
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3292. // An empty mapped value must leave host_ as the connection target. Without
  3293. // that guard the empty value would become the host argument, getaddrinfo
  3294. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3295. // loopback - silently connecting somewhere the caller never asked for.
  3296. // The server listens on loopback, so such a fallback would succeed and is
  3297. // therefore observable as a failure of this test.
  3298. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3299. Server svr;
  3300. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3301. res.set_content("Hello World!", "text/plain");
  3302. });
  3303. auto port = svr.bind_to_any_port(HOST);
  3304. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. Client cli(blackhole, port);
  3312. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3313. cli.set_connection_timeout(1);
  3314. auto res = cli.Get("/hi");
  3315. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3316. }
  3317. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3318. auto host = "target.invalid";
  3319. Server svr;
  3320. std::string received_host;
  3321. svr.Get("/hi", [&](const Request &req, Response &res) {
  3322. received_host = req.get_header_value("Host");
  3323. res.set_content("Hello World!", "text/plain");
  3324. });
  3325. auto port = svr.bind_to_any_port("127.0.0.1");
  3326. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3327. auto se = detail::scope_exit([&] {
  3328. svr.stop();
  3329. thread.join();
  3330. ASSERT_FALSE(svr.is_running());
  3331. });
  3332. svr.wait_until_ready();
  3333. Client cli(host, port);
  3334. #pragma GCC diagnostic push
  3335. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3336. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3337. #pragma GCC diagnostic pop
  3338. auto res = cli.Get("/hi");
  3339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3340. EXPECT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3342. }
  3343. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3344. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3345. Server svr;
  3346. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3347. res.set_content("Hello World!", "text/plain");
  3348. });
  3349. auto port = svr.bind_to_any_port("127.0.0.1");
  3350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3351. auto se = detail::scope_exit([&] {
  3352. svr.stop();
  3353. thread.join();
  3354. ASSERT_FALSE(svr.is_running());
  3355. });
  3356. svr.wait_until_ready();
  3357. Client cli("127.0.0.1", port);
  3358. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3359. cli.set_connection_timeout(1);
  3360. auto res = cli.Get("/hi");
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. }
  3364. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3365. auto host = "httpbingo.org";
  3366. auto path = std::string{"/absolute-redirect/3"};
  3367. #ifdef CPPHTTPLIB_SSL_ENABLED
  3368. SSLClient cli(host);
  3369. #else
  3370. Client cli(host);
  3371. #endif
  3372. cli.set_follow_location(true);
  3373. auto res = cli.Get(path);
  3374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. }
  3377. TEST(RedirectTest, Redirect_Online) {
  3378. auto host = "httpbingo.org";
  3379. auto path = std::string{"/redirect/3"};
  3380. #ifdef CPPHTTPLIB_SSL_ENABLED
  3381. SSLClient cli(host);
  3382. #else
  3383. Client cli(host);
  3384. #endif
  3385. cli.set_follow_location(true);
  3386. auto res = cli.Get(path);
  3387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3388. EXPECT_EQ(StatusCode::OK_200, res->status);
  3389. }
  3390. TEST(RelativeRedirectTest, Redirect_Online) {
  3391. auto host = "httpbingo.org";
  3392. auto path = std::string{"/relative-redirect/3"};
  3393. #ifdef CPPHTTPLIB_SSL_ENABLED
  3394. SSLClient cli(host);
  3395. #else
  3396. Client cli(host);
  3397. #endif
  3398. cli.set_follow_location(true);
  3399. auto res = cli.Get(path);
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ(StatusCode::OK_200, res->status);
  3402. }
  3403. TEST(TooManyRedirectTest, Redirect_Online) {
  3404. auto host = "httpbingo.org";
  3405. auto path = std::string{"/redirect/21"};
  3406. #ifdef CPPHTTPLIB_SSL_ENABLED
  3407. SSLClient cli(host);
  3408. #else
  3409. Client cli(host);
  3410. #endif
  3411. cli.set_follow_location(true);
  3412. auto res = cli.Get(path);
  3413. ASSERT_TRUE(!res);
  3414. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3415. }
  3416. #ifdef CPPHTTPLIB_SSL_ENABLED
  3417. TEST(YahooRedirectTest, Redirect_Online) {
  3418. Client cli("yahoo.com");
  3419. auto res = cli.Get("/");
  3420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3421. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3422. cli.set_follow_location(true);
  3423. res = cli.Get("/");
  3424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3427. }
  3428. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3429. #define REDIR_HOST "httpbingo.org"
  3430. #define REDIR_PATH "/redirect-to"
  3431. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3432. SSLClient cli(REDIR_HOST);
  3433. cli.set_follow_location(true);
  3434. auto res =
  3435. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3437. EXPECT_EQ(StatusCode::OK_200, res->status);
  3438. }
  3439. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3440. SSLClient cli(REDIR_HOST);
  3441. cli.set_follow_location(true);
  3442. Params params;
  3443. params.emplace("url", "http://example.com");
  3444. params.emplace("status_code", "302");
  3445. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3447. EXPECT_EQ(StatusCode::OK_200, res->status);
  3448. }
  3449. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3450. SSLClient cli(REDIR_HOST);
  3451. cli.set_follow_location(true);
  3452. Params params;
  3453. params.emplace("url", "http://example.com");
  3454. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3456. EXPECT_EQ(StatusCode::OK_200, res->status);
  3457. }
  3458. TEST(UrlWithSpace, Redirect_Online) {
  3459. SSLClient cli("edge.forgecdn.net");
  3460. cli.set_follow_location(true);
  3461. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3465. }
  3466. #endif
  3467. #if !defined(_WIN32) && !defined(_WIN64)
  3468. TEST(ReceiveSignals, Signal) {
  3469. auto setupSignalHandlers = []() {
  3470. struct sigaction act;
  3471. sigemptyset(&act.sa_mask);
  3472. act.sa_flags = SA_SIGINFO;
  3473. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3474. switch (sig) {
  3475. case SIGINT:
  3476. default: break;
  3477. }
  3478. };
  3479. ::sigaction(SIGINT, &act, nullptr);
  3480. };
  3481. Server svr;
  3482. int port = 0;
  3483. auto thread = std::thread([&]() {
  3484. setupSignalHandlers();
  3485. port = svr.bind_to_any_port(HOST);
  3486. svr.listen_after_bind();
  3487. });
  3488. auto se = detail::scope_exit([&] {
  3489. svr.stop();
  3490. thread.join();
  3491. ASSERT_FALSE(svr.is_running());
  3492. });
  3493. svr.wait_until_ready();
  3494. ASSERT_TRUE(svr.is_running());
  3495. pthread_kill(thread.native_handle(), SIGINT);
  3496. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3497. ASSERT_TRUE(svr.is_running());
  3498. }
  3499. #endif
  3500. TEST(RedirectToDifferentPort, Redirect) {
  3501. Server svr1;
  3502. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3503. res.set_content("Hello World!", "text/plain");
  3504. });
  3505. int svr1_port = 0;
  3506. auto thread1 = std::thread([&]() {
  3507. svr1_port = svr1.bind_to_any_port(HOST);
  3508. svr1.listen_after_bind();
  3509. });
  3510. Server svr2;
  3511. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3512. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3513. });
  3514. int svr2_port = 0;
  3515. auto thread2 = std::thread([&]() {
  3516. svr2_port = svr2.bind_to_any_port(HOST);
  3517. svr2.listen_after_bind();
  3518. });
  3519. auto se = detail::scope_exit([&] {
  3520. svr2.stop();
  3521. thread2.join();
  3522. svr1.stop();
  3523. thread1.join();
  3524. ASSERT_FALSE(svr2.is_running());
  3525. ASSERT_FALSE(svr1.is_running());
  3526. });
  3527. svr1.wait_until_ready();
  3528. svr2.wait_until_ready();
  3529. Client cli("localhost", svr2_port);
  3530. cli.set_follow_location(true);
  3531. auto res = cli.Get("/2");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. EXPECT_EQ("Hello World!", res->body);
  3535. }
  3536. // GET /redir on one server redirects to /target on another port, so the
  3537. // client follows it with a new client.
  3538. static Result
  3539. GetThroughRedirectToDifferentPort(Server::Handler target,
  3540. const std::function<void(Client &)> &setup,
  3541. const Headers &headers = Headers()) {
  3542. Server target_svr;
  3543. target_svr.Get("/target", target);
  3544. int target_port = 0;
  3545. auto target_thread = std::thread([&]() {
  3546. target_port = target_svr.bind_to_any_port(HOST);
  3547. target_svr.listen_after_bind();
  3548. });
  3549. Server origin_svr;
  3550. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3551. res.set_redirect(
  3552. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3553. });
  3554. int origin_port = 0;
  3555. auto origin_thread = std::thread([&]() {
  3556. origin_port = origin_svr.bind_to_any_port(HOST);
  3557. origin_svr.listen_after_bind();
  3558. });
  3559. auto se = detail::scope_exit([&] {
  3560. origin_svr.stop();
  3561. origin_thread.join();
  3562. target_svr.stop();
  3563. target_thread.join();
  3564. });
  3565. target_svr.wait_until_ready();
  3566. origin_svr.wait_until_ready();
  3567. Client cli("localhost", origin_port);
  3568. cli.set_follow_location(true);
  3569. setup(cli);
  3570. return cli.Get("/redir", headers);
  3571. }
  3572. static void
  3573. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3574. std::string captured_authorization;
  3575. auto result = GetThroughRedirectToDifferentPort(
  3576. [&](const Request &req, Response &res) {
  3577. captured_authorization = req.get_header_value("Authorization");
  3578. res.set_content("OK", "text/plain");
  3579. },
  3580. set_auth);
  3581. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3582. EXPECT_EQ(StatusCode::OK_200, result->status);
  3583. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3584. EXPECT_TRUE(captured_authorization.empty());
  3585. }
  3586. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3587. TestDoNotForwardCredentialsOnRedirect(
  3588. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3589. }
  3590. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3591. TestDoNotForwardCredentialsOnRedirect(
  3592. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3593. }
  3594. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3595. std::string captured_cookie;
  3596. auto result = GetThroughRedirectToDifferentPort(
  3597. [&](const Request &req, Response &res) {
  3598. captured_cookie = req.get_header_value("Cookie");
  3599. res.set_content("OK", "text/plain");
  3600. },
  3601. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3602. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3603. EXPECT_EQ(StatusCode::OK_200, result->status);
  3604. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3605. EXPECT_TRUE(captured_cookie.empty());
  3606. }
  3607. TEST(RedirectToSamePort, ForwardCookie) {
  3608. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3609. // header so that ordinary session flows keep working.
  3610. Server svr;
  3611. std::string captured_cookie;
  3612. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3613. res.set_redirect("/target", 302);
  3614. });
  3615. svr.Get("/target", [&](const Request &req, Response &res) {
  3616. captured_cookie = req.get_header_value("Cookie");
  3617. res.set_content("OK", "text/plain");
  3618. });
  3619. auto port = svr.bind_to_any_port(HOST);
  3620. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. thread.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. Client cli(HOST, port);
  3628. cli.set_follow_location(true);
  3629. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3630. auto res = cli.Get("/redir", headers);
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3634. }
  3635. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3636. std::string authorization;
  3637. std::string trace_id;
  3638. auto result = GetThroughRedirectToDifferentPort(
  3639. [&](const Request &req, Response &res) {
  3640. authorization = req.get_header_value("Authorization");
  3641. trace_id = req.get_header_value("X-Trace-Id");
  3642. res.set_content("OK", "text/plain");
  3643. },
  3644. [](Client &cli) {
  3645. cli.set_default_headers(
  3646. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3647. });
  3648. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3649. EXPECT_EQ(StatusCode::OK_200, result->status);
  3650. // Like a header given with the request, a default one goes along unless it
  3651. // carries credentials (RFC 9110 15.4).
  3652. EXPECT_TRUE(authorization.empty());
  3653. EXPECT_EQ("42", trace_id);
  3654. }
  3655. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3656. auto result = GetThroughRedirectToDifferentPort(
  3657. [](const Request &, Response &res) {
  3658. res.set_content(std::string(2048, 'x'), "text/plain");
  3659. },
  3660. [](Client &cli) { cli.set_payload_max_length(1024); });
  3661. EXPECT_FALSE(result);
  3662. }
  3663. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3664. auto result = GetThroughRedirectToDifferentPort(
  3665. [](const Request &req, Response &res) {
  3666. // Answer after a second, or once the client gives up.
  3667. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3668. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3669. }
  3670. res.set_content("late", "text/plain");
  3671. },
  3672. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3673. ASSERT_FALSE(result);
  3674. EXPECT_EQ(Error::Read, result.error());
  3675. }
  3676. #ifdef CPPHTTPLIB_SSL_ENABLED
  3677. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3678. auto result = GetThroughRedirectToDifferentPort(
  3679. [](const Request &, Response &res) {
  3680. res.status = StatusCode::Unauthorized_401;
  3681. res.set_header("WWW-Authenticate",
  3682. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3683. },
  3684. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3685. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3686. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3687. }
  3688. #endif
  3689. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3690. Server svr;
  3691. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3692. // Port number that overflows int — should not crash
  3693. res.set_redirect("http://localhost:99999999999999999999/target");
  3694. });
  3695. auto port = svr.bind_to_any_port(HOST);
  3696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. Client cli(HOST, port);
  3704. cli.set_follow_location(true);
  3705. auto res = cli.Get("/redir");
  3706. // Should fail gracefully, not crash (no valid response due to bad port)
  3707. EXPECT_FALSE(res);
  3708. }
  3709. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3710. Server svr;
  3711. auto port = svr.bind_to_any_port(HOST);
  3712. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3713. // The server's own port followed by junk must not be followed
  3714. res.set_redirect("http://" + std::string(HOST) + ":" +
  3715. std::to_string(port) + "junk/target");
  3716. });
  3717. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3718. res.set_content("target", "text/plain");
  3719. });
  3720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3721. auto se = detail::scope_exit([&] {
  3722. svr.stop();
  3723. thread.join();
  3724. ASSERT_FALSE(svr.is_running());
  3725. });
  3726. svr.wait_until_ready();
  3727. Client cli(HOST, port);
  3728. cli.set_follow_location(true);
  3729. auto res = cli.Get("/redir");
  3730. EXPECT_FALSE(res);
  3731. }
  3732. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3733. Server svr;
  3734. std::atomic<bool> followed{false};
  3735. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3736. res.status = StatusCode::NotModified_304;
  3737. res.set_header("Location", "/target");
  3738. });
  3739. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3740. res.status = StatusCode::UseProxy_305;
  3741. res.set_header("Location", "/target");
  3742. });
  3743. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3744. followed = true;
  3745. res.set_content("target", "text/plain");
  3746. });
  3747. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. th.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. Client cli("localhost", PORT);
  3755. cli.set_follow_location(true);
  3756. auto res = cli.Get("/304");
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3759. res = cli.Get("/305");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3762. EXPECT_FALSE(followed);
  3763. }
  3764. TEST(RedirectFromPageWithContent, Redirect) {
  3765. Server svr;
  3766. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3767. res.set_content("___", "text/plain");
  3768. res.set_redirect("/2");
  3769. });
  3770. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3771. res.set_content("Hello World!", "text/plain");
  3772. });
  3773. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3774. auto se = detail::scope_exit([&] {
  3775. svr.stop();
  3776. th.join();
  3777. ASSERT_FALSE(svr.is_running());
  3778. });
  3779. svr.wait_until_ready();
  3780. {
  3781. Client cli("localhost", PORT);
  3782. cli.set_follow_location(true);
  3783. std::string body;
  3784. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3785. body.append(data, data_length);
  3786. return true;
  3787. });
  3788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3789. EXPECT_EQ(StatusCode::OK_200, res->status);
  3790. EXPECT_EQ("Hello World!", body);
  3791. }
  3792. {
  3793. Client cli("localhost", PORT);
  3794. std::string body;
  3795. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3796. body.append(data, data_length);
  3797. return true;
  3798. });
  3799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3800. EXPECT_EQ(StatusCode::Found_302, res->status);
  3801. EXPECT_EQ("___", body);
  3802. }
  3803. }
  3804. // A server can close the connection after a request with "Connection: close"
  3805. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3806. // redirected request must go out on a new connection.
  3807. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3808. #ifndef _WIN32
  3809. signal(SIGPIPE, SIG_IGN);
  3810. #endif
  3811. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3812. default_socket_options(srv);
  3813. sockaddr_in addr{};
  3814. addr.sin_family = AF_INET;
  3815. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3816. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3817. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3818. ASSERT_EQ(0, ::listen(srv, 2));
  3819. auto send_text = [](socket_t sock, const std::string &text) {
  3820. ::send(sock,
  3821. #ifdef _WIN32
  3822. static_cast<const char *>(text.c_str()),
  3823. static_cast<int>(text.size()),
  3824. #else
  3825. text.c_str(), text.size(),
  3826. #endif
  3827. 0);
  3828. };
  3829. auto reused = false;
  3830. auto server_thread = std::thread([&] {
  3831. char buf[4096];
  3832. auto first = ::accept(srv, nullptr, nullptr);
  3833. if (first == INVALID_SOCKET) { return; }
  3834. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3835. ::recv(first, buf, sizeof(buf), 0);
  3836. send_text(
  3837. first,
  3838. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3839. auto next = first;
  3840. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3841. reused = true;
  3842. } else {
  3843. detail::close_socket(first);
  3844. next = ::accept(srv, nullptr, nullptr);
  3845. if (next == INVALID_SOCKET) { return; }
  3846. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3847. ::recv(next, buf, sizeof(buf), 0);
  3848. }
  3849. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3850. "Connection: close\r\n\r\nok");
  3851. detail::close_socket(next);
  3852. });
  3853. Client cli("127.0.0.1", PORT + 2);
  3854. cli.set_follow_location(true);
  3855. cli.set_read_timeout(5, 0);
  3856. auto res = cli.Get("/1");
  3857. server_thread.join();
  3858. detail::close_socket(srv);
  3859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3860. EXPECT_EQ(StatusCode::OK_200, res->status);
  3861. EXPECT_EQ("ok", res->body);
  3862. EXPECT_FALSE(reused);
  3863. }
  3864. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3865. Server svr;
  3866. auto port_str = std::to_string(PORT);
  3867. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3868. auto expected_host = "[::1]:" + port_str;
  3869. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3870. res.set_content("___", "text/plain");
  3871. // res.set_redirect("/2");
  3872. res.set_redirect(redirect_url);
  3873. });
  3874. svr.Get("/2", [&](const Request &req, Response &res) {
  3875. auto host_header = req.headers.find("Host");
  3876. ASSERT_TRUE(host_header != req.headers.end());
  3877. EXPECT_EQ(expected_host, host_header->second);
  3878. res.set_content("Hello World!", "text/plain");
  3879. });
  3880. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3881. auto se = detail::scope_exit([&] {
  3882. svr.stop();
  3883. th.join();
  3884. ASSERT_FALSE(svr.is_running());
  3885. });
  3886. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3887. // actually starts anything, so the condition !svr.is_running() will
  3888. // always remain true, and the loop never stops.
  3889. // This basically counts how many milliseconds have passed since the
  3890. // call to svr.listen(), and if after 5 seconds nothing started yet
  3891. // aborts the test.
  3892. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3893. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3894. ASSERT_LT(milliseconds, 5000U);
  3895. }
  3896. {
  3897. Client cli("::1", PORT);
  3898. cli.set_follow_location(true);
  3899. std::string body;
  3900. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3901. body.append(data, data_length);
  3902. return true;
  3903. });
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("Hello World!", body);
  3907. }
  3908. {
  3909. Client cli("::1", PORT);
  3910. std::string body;
  3911. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3912. body.append(data, data_length);
  3913. return true;
  3914. });
  3915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3916. EXPECT_EQ(StatusCode::Found_302, res->status);
  3917. EXPECT_EQ("___", body);
  3918. }
  3919. }
  3920. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3921. Server svr;
  3922. svr.Get("/foo", [](const Request &req, Response &res) {
  3923. auto a = req.params.find("a");
  3924. if (a != req.params.end()) {
  3925. res.set_content((*a).second, "text/plain");
  3926. res.status = StatusCode::OK_200;
  3927. } else {
  3928. res.status = StatusCode::BadRequest_400;
  3929. }
  3930. });
  3931. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3932. auto se = detail::scope_exit([&] {
  3933. svr.stop();
  3934. thread.join();
  3935. ASSERT_FALSE(svr.is_running());
  3936. });
  3937. svr.wait_until_ready();
  3938. {
  3939. Client cli(HOST, PORT);
  3940. cli.set_path_encode(false);
  3941. auto res = cli.Get("/foo?a=explicitly+encoded");
  3942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3943. EXPECT_EQ(StatusCode::OK_200, res->status);
  3944. // This expects it back with a space, as the `+` won't have been
  3945. // url-encoded, and server-side the params get decoded turning `+`
  3946. // into spaces.
  3947. EXPECT_EQ("explicitly encoded", res->body);
  3948. }
  3949. }
  3950. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3951. // When path encoding is disabled the client must transmit the supplied
  3952. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3953. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3954. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3955. // than a space (0x20). Assert on the raw wire target to catch this.
  3956. Server svr;
  3957. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3958. svr.Get("/foo", [&](const Request &req, Response &res) {
  3959. EXPECT_EQ(expected_target, req.target);
  3960. res.status = StatusCode::OK_200;
  3961. });
  3962. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3963. auto se = detail::scope_exit([&] {
  3964. svr.stop();
  3965. thread.join();
  3966. ASSERT_FALSE(svr.is_running());
  3967. });
  3968. svr.wait_until_ready();
  3969. {
  3970. Client cli(HOST, PORT);
  3971. cli.set_path_encode(false);
  3972. auto res = cli.Get(expected_target.c_str());
  3973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3974. EXPECT_EQ(StatusCode::OK_200, res->status);
  3975. }
  3976. }
  3977. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3978. // `open_stream()` used to skip the path encoding that the buffered send
  3979. // path applies, so the same `path` produced different bytes in the request
  3980. // line depending on which API was used. Assert the two agree.
  3981. Server svr;
  3982. std::string target;
  3983. svr.Get(".*", [&](const Request &req, Response &res) {
  3984. target = req.target;
  3985. res.status = StatusCode::OK_200;
  3986. });
  3987. auto port = svr.bind_to_any_port(HOST);
  3988. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3989. auto se = detail::scope_exit([&] {
  3990. svr.stop();
  3991. thread.join();
  3992. ASSERT_FALSE(svr.is_running());
  3993. });
  3994. svr.wait_until_ready();
  3995. struct {
  3996. const char *path;
  3997. const char *expected;
  3998. } cases[] = {
  3999. {"/a b?x=1", "/a%20b?x=1"},
  4000. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4001. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4002. };
  4003. for (const auto &c : cases) {
  4004. Client cli(HOST, port);
  4005. target.clear();
  4006. auto res = cli.Get(c.path);
  4007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4008. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4009. auto buffered_target = target;
  4010. target.clear();
  4011. auto handle = cli.open_stream("GET", c.path);
  4012. EXPECT_TRUE(handle.is_valid())
  4013. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4014. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4015. }
  4016. }
  4017. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4018. // The `set_path_encode(false)` contract — transmit the supplied target
  4019. // verbatim — must hold for the streaming API too.
  4020. Server svr;
  4021. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4022. std::string target;
  4023. svr.Get("/foo", [&](const Request &req, Response &res) {
  4024. target = req.target;
  4025. res.status = StatusCode::OK_200;
  4026. });
  4027. auto port = svr.bind_to_any_port(HOST);
  4028. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4029. auto se = detail::scope_exit([&] {
  4030. svr.stop();
  4031. thread.join();
  4032. ASSERT_FALSE(svr.is_running());
  4033. });
  4034. svr.wait_until_ready();
  4035. {
  4036. Client cli(HOST, port);
  4037. cli.set_path_encode(false);
  4038. auto handle = cli.open_stream("GET", expected_target);
  4039. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4040. EXPECT_EQ(expected_target, target);
  4041. }
  4042. }
  4043. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4044. // With path encoding enabled a CR/LF in the target is percent-encoded
  4045. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4046. // write_request_line still backstops `set_path_encode(false)`, which is
  4047. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4048. Server svr;
  4049. // Captured before routing: the decoded path contains a newline, which a
  4050. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4051. std::string target;
  4052. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4053. target = req.target;
  4054. res.status = StatusCode::OK_200;
  4055. return Server::HandlerResponse::Handled;
  4056. });
  4057. auto port = svr.bind_to_any_port(HOST);
  4058. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4059. auto se = detail::scope_exit([&] {
  4060. svr.stop();
  4061. thread.join();
  4062. ASSERT_FALSE(svr.is_running());
  4063. });
  4064. svr.wait_until_ready();
  4065. {
  4066. Client cli(HOST, port);
  4067. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4068. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4069. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4070. }
  4071. }
  4072. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4073. // Every control character is percent-encoded, not just CR/LF, so the target
  4074. // passes the request-target check in write_request_line.
  4075. Server svr;
  4076. std::string target;
  4077. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4078. target = req.target;
  4079. res.status = StatusCode::OK_200;
  4080. return Server::HandlerResponse::Handled;
  4081. });
  4082. auto port = svr.bind_to_any_port(HOST);
  4083. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4084. auto se = detail::scope_exit([&] {
  4085. svr.stop();
  4086. thread.join();
  4087. ASSERT_FALSE(svr.is_running());
  4088. });
  4089. svr.wait_until_ready();
  4090. {
  4091. Client cli(HOST, port);
  4092. auto res = cli.Get("/a\tb\x1b\x7f");
  4093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4094. EXPECT_EQ("/a%09b%1B%7F", target);
  4095. }
  4096. }
  4097. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4098. // Nothing may reach the wire: a raw CR/LF target would split the request
  4099. // line and inject headers.
  4100. Server svr;
  4101. // Pre-routing so that "not called" means nothing reached the server at all,
  4102. // rather than merely failing to match a handler pattern.
  4103. auto handler_called = false;
  4104. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4105. handler_called = true;
  4106. res.status = StatusCode::OK_200;
  4107. return Server::HandlerResponse::Handled;
  4108. });
  4109. auto port = svr.bind_to_any_port(HOST);
  4110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. {
  4118. Client cli(HOST, port);
  4119. cli.set_path_encode(false);
  4120. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4121. EXPECT_FALSE(handle.is_valid());
  4122. EXPECT_EQ(Error::Write, handle.error);
  4123. EXPECT_FALSE(handler_called);
  4124. }
  4125. }
  4126. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4127. // Which of the two branches runs is decided by whether the query component
  4128. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4129. // an empty query and must still fall back to building one from
  4130. // `req.params`, while a non-empty query must win over `req.params`.
  4131. Server svr;
  4132. std::string target;
  4133. svr.Get("/foo", [&](const Request &req, Response &res) {
  4134. target = req.target;
  4135. res.status = StatusCode::OK_200;
  4136. });
  4137. auto port = svr.bind_to_any_port(HOST);
  4138. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4139. auto se = detail::scope_exit([&] {
  4140. svr.stop();
  4141. thread.join();
  4142. ASSERT_FALSE(svr.is_running());
  4143. });
  4144. svr.wait_until_ready();
  4145. {
  4146. // Trailing `?` -> empty query component -> `req.params` is used.
  4147. Client cli(HOST, port);
  4148. Request req;
  4149. req.method = "GET";
  4150. req.path = "/foo?";
  4151. req.params.emplace("a", "1");
  4152. target.clear();
  4153. auto res = cli.send(req);
  4154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4155. EXPECT_EQ("/foo?a=1", target);
  4156. }
  4157. {
  4158. // Non-empty query in `req.path` -> `req.params` is not appended.
  4159. Client cli(HOST, port);
  4160. Request req;
  4161. req.method = "GET";
  4162. req.path = "/foo?b=2";
  4163. req.params.emplace("a", "1");
  4164. target.clear();
  4165. auto res = cli.send(req);
  4166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4167. EXPECT_EQ("/foo?b=2", target);
  4168. }
  4169. }
  4170. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4171. Server svr;
  4172. svr.Get("/", [](const Request &req, Response &) {
  4173. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4174. });
  4175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4176. auto se = detail::scope_exit([&] {
  4177. svr.stop();
  4178. thread.join();
  4179. ASSERT_FALSE(svr.is_running());
  4180. });
  4181. svr.wait_until_ready();
  4182. {
  4183. Client cli(HOST, PORT);
  4184. cli.set_path_encode(false);
  4185. auto res = cli.Get("/?something=%0A");
  4186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4187. EXPECT_EQ(StatusCode::OK_200, res->status);
  4188. }
  4189. }
  4190. TEST(BindServerTest, BindDualStack) {
  4191. Server svr;
  4192. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4193. res.set_content("Hello World!", "text/plain");
  4194. });
  4195. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. Client cli("127.0.0.1", PORT);
  4204. auto res = cli.Get("/1");
  4205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. EXPECT_EQ("Hello World!", res->body);
  4208. }
  4209. {
  4210. Client cli("::1", PORT);
  4211. auto res = cli.Get("/1");
  4212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. EXPECT_EQ("Hello World!", res->body);
  4215. }
  4216. }
  4217. TEST(BindServerTest, BindAndListenSeparately) {
  4218. Server svr;
  4219. int port = svr.bind_to_any_port("0.0.0.0");
  4220. ASSERT_TRUE(svr.is_valid());
  4221. ASSERT_TRUE(port > 0);
  4222. svr.stop();
  4223. }
  4224. // Reports whether anything is still listening on a loopback port. A plain
  4225. // connect() is used instead of a Client request because a socket left bound by
  4226. // mistake accepts the connection into its backlog and never answers, which
  4227. // would hang the test instead of failing it.
  4228. static bool is_loopback_port_accepting(int port) {
  4229. sockaddr_in addr{};
  4230. addr.sin_family = AF_INET;
  4231. addr.sin_port = htons(static_cast<uint16_t>(port));
  4232. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4233. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4234. EXPECT_NE(sock, INVALID_SOCKET);
  4235. if (sock == INVALID_SOCKET) { return false; }
  4236. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4237. static_cast<socklen_t>(sizeof(addr)));
  4238. detail::close_socket(sock);
  4239. return ret == 0;
  4240. }
  4241. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4242. Server svr;
  4243. auto port = svr.bind_to_any_port("127.0.0.1");
  4244. ASSERT_TRUE(port > 0);
  4245. svr.stop();
  4246. // bind_to_any_port() already called listen(2), so until stop() closed the
  4247. // descriptor the port kept accepting connections into the backlog. ASSERT
  4248. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4249. // below blocks forever in the accept loop.
  4250. ASSERT_FALSE(is_loopback_port_accepting(port));
  4251. // Nothing is left to accept on, so listen_after_bind() must report failure
  4252. // instead of returning success without ever serving.
  4253. EXPECT_FALSE(svr.listen_after_bind());
  4254. // The failed listen marks the server decommissioned, so a waiter returns
  4255. // instead of spinning forever.
  4256. svr.wait_until_ready();
  4257. }
  4258. #ifdef CPPHTTPLIB_SSL_ENABLED
  4259. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4261. CLIENT_CA_CERT_DIR);
  4262. int port = svr.bind_to_any_port("0.0.0.0");
  4263. ASSERT_TRUE(svr.is_valid());
  4264. ASSERT_TRUE(port > 0);
  4265. svr.stop();
  4266. }
  4267. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4268. // or a rejected CustomRoute() registration would not stop the server binding.
  4269. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4271. CLIENT_CA_CERT_DIR);
  4272. ASSERT_TRUE(svr.is_valid());
  4273. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4274. EXPECT_FALSE(svr.is_valid());
  4275. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4276. }
  4277. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4278. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4279. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4280. int port = svr.bind_to_any_port("0.0.0.0");
  4281. ASSERT_TRUE(svr.is_valid());
  4282. ASSERT_TRUE(port > 0);
  4283. svr.stop();
  4284. }
  4285. TEST(BindServerTest, UpdateCertsPem) {
  4286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4287. int port = svr.bind_to_any_port("0.0.0.0");
  4288. ASSERT_TRUE(svr.is_valid());
  4289. ASSERT_TRUE(port > 0);
  4290. // Read PEM files
  4291. std::string cert_pem, key_pem, ca_pem;
  4292. read_file(SERVER_CERT_FILE, cert_pem);
  4293. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4294. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4295. // Update server certificates using PEM API
  4296. ASSERT_TRUE(
  4297. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4298. ASSERT_TRUE(svr.is_valid());
  4299. svr.stop();
  4300. }
  4301. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4302. // Start server with client CA (enables client auth)
  4303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4304. ASSERT_TRUE(svr.is_valid());
  4305. bool handler_called = false;
  4306. svr.Get("/test", [&](const Request &req, Response &res) {
  4307. handler_called = true;
  4308. // Verify client certificate is present
  4309. auto cert = req.peer_cert();
  4310. EXPECT_TRUE(static_cast<bool>(cert));
  4311. res.set_content("ok", "text/plain");
  4312. });
  4313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4314. auto se = detail::scope_exit([&] {
  4315. svr.stop();
  4316. t.join();
  4317. ASSERT_FALSE(svr.is_running());
  4318. });
  4319. svr.wait_until_ready();
  4320. // Read PEM files
  4321. std::string cert_pem, key_pem, ca_pem;
  4322. read_file(SERVER_CERT_FILE, cert_pem);
  4323. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4324. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4325. // Update server certificates and client CA using PEM API while server running
  4326. ASSERT_TRUE(
  4327. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4328. // Connect with client certificate
  4329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4330. cli.enable_server_certificate_verification(false);
  4331. cli.set_connection_timeout(30);
  4332. auto res = cli.Get("/test");
  4333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4334. ASSERT_EQ(StatusCode::OK_200, res->status);
  4335. ASSERT_TRUE(handler_called);
  4336. EXPECT_EQ("ok", res->body);
  4337. }
  4338. // Puts a CA that did not sign the client's certificate in the old one's place.
  4339. static bool replace_client_ca(SSLServer &svr) {
  4340. std::string cert_pem, key_pem, ca_pem;
  4341. read_file(SERVER_CERT_FILE, cert_pem);
  4342. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4343. read_file(SERVER_CERT2_FILE, ca_pem);
  4344. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4345. ca_pem.c_str());
  4346. }
  4347. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4349. ASSERT_TRUE(svr.is_valid());
  4350. svr.Get("/test", [](const Request &, Response &res) {
  4351. res.set_content("ok", "text/plain");
  4352. });
  4353. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. t.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. auto get = [] {
  4361. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4362. cli.enable_server_certificate_verification(false);
  4363. return cli.Get("/test");
  4364. };
  4365. ASSERT_TRUE(get());
  4366. ASSERT_TRUE(replace_client_ca(svr));
  4367. EXPECT_FALSE(get());
  4368. }
  4369. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4370. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4372. ASSERT_TRUE(svr.is_valid());
  4373. tls::set_verify_callback(svr.tls_context(),
  4374. [](const tls::VerifyContext &) -> bool {
  4375. throw std::runtime_error("verify");
  4376. });
  4377. svr.Get("/test", [](const Request &, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4381. auto se = detail::scope_exit([&] {
  4382. svr.stop();
  4383. t.join();
  4384. ASSERT_FALSE(svr.is_running());
  4385. });
  4386. svr.wait_until_ready();
  4387. auto get = [] {
  4388. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4389. cli.enable_server_certificate_verification(false);
  4390. return cli.Get("/test");
  4391. };
  4392. EXPECT_FALSE(get());
  4393. // The handshake is over, so an update does not wait for it.
  4394. std::string cert_pem, key_pem;
  4395. read_file(SERVER_CERT_FILE, cert_pem);
  4396. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4397. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4398. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4399. return v.preverify_ok;
  4400. });
  4401. auto res = get();
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ("ok", res->body);
  4404. }
  4405. #endif
  4406. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4407. // Sends each request over a new connection with a client certificate,
  4408. // resuming the session of the one before when there is one.
  4409. class ResumingClient {
  4410. public:
  4411. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4412. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4413. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4414. SSL_FILETYPE_PEM);
  4415. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4416. // callback, not through SSL_get1_session().
  4417. SSL_CTX_set_app_data(ctx_, this);
  4418. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4419. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4420. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4421. auto self = static_cast<ResumingClient *>(
  4422. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4423. SSL_SESSION_free(self->session_);
  4424. self->session_ = session;
  4425. return 1; // Keeps the reference
  4426. });
  4427. }
  4428. ~ResumingClient() {
  4429. SSL_SESSION_free(session_);
  4430. SSL_CTX_free(ctx_);
  4431. }
  4432. // Tells whether the request was answered.
  4433. bool get() {
  4434. auto error = Error::Success;
  4435. auto sock = detail::create_client_socket(
  4436. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4437. /*connection_timeout_sec=*/5, 0,
  4438. /*read_timeout_sec=*/5, 0,
  4439. /*write_timeout_sec=*/5, 0, std::string(), error);
  4440. if (sock == INVALID_SOCKET) { return false; }
  4441. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4442. auto ssl = SSL_new(ctx_);
  4443. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4444. SSL_set_fd(ssl, static_cast<int>(sock));
  4445. if (session_) { SSL_set_session(ssl, session_); }
  4446. if (SSL_connect(ssl) != 1) { return false; }
  4447. reused_ = SSL_session_reused(ssl) == 1;
  4448. // Reading the response also takes in a TLS 1.3 session ticket.
  4449. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4450. "Connection: close\r\n\r\n";
  4451. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4452. std::string res;
  4453. char buf[256];
  4454. int n;
  4455. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4456. res.append(buf, static_cast<size_t>(n));
  4457. }
  4458. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4459. SSL_shutdown(ssl);
  4460. return res.find("200 OK") != std::string::npos;
  4461. }
  4462. // Whether the last connection resumed a session
  4463. bool reused() const { return reused_; }
  4464. private:
  4465. SSL_CTX *ctx_;
  4466. SSL_SESSION *session_ = nullptr;
  4467. bool reused_ = false;
  4468. };
  4469. // A client that resumes its session gets through, but not once the client CA
  4470. // has changed, as a resumed session does not show the certificate again.
  4471. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4473. ASSERT_TRUE(svr.is_valid());
  4474. svr.Get("/test", [](const Request &, Response &res) {
  4475. res.set_content("ok", "text/plain");
  4476. });
  4477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4478. auto se = detail::scope_exit([&] {
  4479. svr.stop();
  4480. t.join();
  4481. ASSERT_FALSE(svr.is_running());
  4482. });
  4483. svr.wait_until_ready();
  4484. ResumingClient cli;
  4485. ASSERT_TRUE(cli.get());
  4486. ASSERT_TRUE(cli.get());
  4487. EXPECT_TRUE(cli.reused());
  4488. ASSERT_TRUE(replace_client_ca(svr));
  4489. EXPECT_FALSE(cli.get());
  4490. }
  4491. // A resumed session does not show the certificate again, so the server does
  4492. // not resume one with a verify callback to run on it.
  4493. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4495. ASSERT_TRUE(svr.is_valid());
  4496. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4497. return v.preverify_ok;
  4498. });
  4499. svr.Get("/test", [](const Request &, Response &res) {
  4500. res.set_content("ok", "text/plain");
  4501. });
  4502. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4503. auto se = detail::scope_exit([&] {
  4504. svr.stop();
  4505. t.join();
  4506. ASSERT_FALSE(svr.is_running());
  4507. });
  4508. svr.wait_until_ready();
  4509. ResumingClient cli;
  4510. ASSERT_TRUE(cli.get());
  4511. ASSERT_TRUE(cli.get());
  4512. EXPECT_FALSE(cli.reused());
  4513. }
  4514. #endif
  4515. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4516. // wolfSSL shares its session cache between contexts, so a resumed session
  4517. // could carry a client certificate checked against another server's CA, or
  4518. // against a client CA since replaced.
  4519. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4521. ASSERT_TRUE(svr.is_valid());
  4522. // Trusts a CA that did not sign the client's certificate.
  4523. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4524. ASSERT_TRUE(other.is_valid());
  4525. for (auto s : {&svr, &other}) {
  4526. s->Get("/test", [](const Request &, Response &res) {
  4527. res.set_content("ok", "text/plain");
  4528. });
  4529. }
  4530. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4531. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4532. auto se = detail::scope_exit([&] {
  4533. other.stop();
  4534. svr.stop();
  4535. t2.join();
  4536. t.join();
  4537. });
  4538. svr.wait_until_ready();
  4539. other.wait_until_ready();
  4540. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4541. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4542. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4543. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4544. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4545. ASSERT_EQ(WOLFSSL_SUCCESS,
  4546. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4547. WOLFSSL_FILETYPE_PEM));
  4548. WOLFSSL_SESSION *session = nullptr;
  4549. auto session_se = detail::scope_exit([&] {
  4550. if (session) { wolfSSL_SESSION_free(session); }
  4551. });
  4552. // A request over a new connection, resuming `session` when there is one and
  4553. // keeping the connection's own in its place. Tells whether it was answered.
  4554. auto get = [&](int port) {
  4555. auto error = Error::Success;
  4556. auto sock = detail::create_client_socket(
  4557. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4558. /*connection_timeout_sec=*/5, 0,
  4559. /*read_timeout_sec=*/5, 0,
  4560. /*write_timeout_sec=*/5, 0, std::string(), error);
  4561. if (sock == INVALID_SOCKET) { return false; }
  4562. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4563. auto ssl = wolfSSL_new(ctx);
  4564. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4565. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4566. if (session) { wolfSSL_set_session(ssl, session); }
  4567. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4568. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4569. "Connection: close\r\n\r\n";
  4570. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4571. std::string res;
  4572. char buf[256];
  4573. int n;
  4574. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4575. res.append(buf, static_cast<size_t>(n));
  4576. }
  4577. wolfSSL_shutdown(ssl);
  4578. if (session) { wolfSSL_SESSION_free(session); }
  4579. session = wolfSSL_get1_session(ssl);
  4580. return res.find("200 OK") != std::string::npos;
  4581. };
  4582. ASSERT_TRUE(get(PORT));
  4583. EXPECT_FALSE(get(PORT + 1));
  4584. ASSERT_TRUE(get(PORT));
  4585. ASSERT_TRUE(replace_client_ca(svr));
  4586. EXPECT_FALSE(get(PORT));
  4587. }
  4588. #endif
  4589. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4591. ASSERT_TRUE(svr.is_valid());
  4592. svr.Get("/test", [](const Request &, Response &res) {
  4593. res.set_content("ok", "text/plain");
  4594. });
  4595. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. t.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. // A connection that sends no ClientHello keeps its handshake in progress,
  4603. // once the server has had a moment to start it.
  4604. auto error = Error::Success;
  4605. auto sock = detail::create_client_socket(
  4606. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4607. /*connection_timeout_sec=*/5, 0,
  4608. /*read_timeout_sec=*/5, 0,
  4609. /*write_timeout_sec=*/5, 0, std::string(), error);
  4610. ASSERT_NE(INVALID_SOCKET, sock);
  4611. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4612. std::string cert_pem, key_pem;
  4613. read_file(SERVER_CERT_FILE, cert_pem);
  4614. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4615. auto update = std::async(std::launch::async, [&]() {
  4616. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4617. });
  4618. EXPECT_EQ(std::future_status::timeout,
  4619. update.wait_for(std::chrono::milliseconds(200)));
  4620. detail::close_socket(sock);
  4621. EXPECT_TRUE(update.get());
  4622. SSLClient cli(HOST, PORT);
  4623. cli.enable_server_certificate_verification(false);
  4624. auto res = cli.Get("/test");
  4625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4626. EXPECT_EQ(StatusCode::OK_200, res->status);
  4627. }
  4628. #endif
  4629. TEST(ErrorHandlerTest, ContentLength) {
  4630. Server svr;
  4631. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4632. res.status = StatusCode::OK_200;
  4633. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4634. "text/html"); // <= Content-Length still 13
  4635. });
  4636. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4637. res.set_content("Hello World!\n", "text/plain");
  4638. res.status = 524;
  4639. });
  4640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4641. auto se = detail::scope_exit([&] {
  4642. svr.stop();
  4643. thread.join();
  4644. ASSERT_FALSE(svr.is_running());
  4645. });
  4646. svr.wait_until_ready();
  4647. {
  4648. Client cli(HOST, PORT);
  4649. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4653. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4654. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4655. }
  4656. }
  4657. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4658. TEST(ExceptionTest, WithoutExceptionHandler) {
  4659. Server svr;
  4660. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4661. throw std::runtime_error("exception...");
  4662. });
  4663. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4664. throw std::runtime_error("exception\r\n...");
  4665. });
  4666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4667. auto se = detail::scope_exit([&] {
  4668. svr.stop();
  4669. listen_thread.join();
  4670. ASSERT_FALSE(svr.is_running());
  4671. });
  4672. svr.wait_until_ready();
  4673. Client cli("localhost", PORT);
  4674. {
  4675. auto res = cli.Get("/exception");
  4676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4677. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4678. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4679. }
  4680. {
  4681. auto res = cli.Get("/unknown");
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4684. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4685. }
  4686. }
  4687. TEST(ExceptionTest, WithExceptionHandler) {
  4688. Server svr;
  4689. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4690. std::exception_ptr ep) {
  4691. EXPECT_FALSE(ep == nullptr);
  4692. try {
  4693. std::rethrow_exception(ep);
  4694. } catch (std::exception &e) {
  4695. EXPECT_EQ("abc", std::string(e.what()));
  4696. } catch (...) {}
  4697. res.status = StatusCode::InternalServerError_500;
  4698. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4699. "text/html"); // <= Content-Length still 13 at this point
  4700. });
  4701. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4702. res.set_content("Hello World!\n", "text/plain");
  4703. throw std::runtime_error("abc");
  4704. });
  4705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4706. auto se = detail::scope_exit([&] {
  4707. svr.stop();
  4708. thread.join();
  4709. ASSERT_FALSE(svr.is_running());
  4710. });
  4711. svr.wait_until_ready();
  4712. for (size_t i = 0; i < 10; i++) {
  4713. Client cli(HOST, PORT);
  4714. for (size_t j = 0; j < 100; j++) {
  4715. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4718. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4719. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4720. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4721. }
  4722. cli.set_keep_alive(true);
  4723. for (size_t j = 0; j < 100; j++) {
  4724. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4727. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4728. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4729. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4730. }
  4731. }
  4732. }
  4733. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4734. Server svr;
  4735. svr.set_exception_handler(
  4736. [](const Request &, Response &res, std::exception_ptr) {
  4737. res.set_content("oops", "text/plain");
  4738. });
  4739. svr.Get("/throw", [](const Request &, Response &) {
  4740. throw std::runtime_error("throw");
  4741. });
  4742. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4743. res.status = StatusCode::Created_201;
  4744. throw std::runtime_error("created-then-throw");
  4745. });
  4746. auto port = svr.bind_to_any_port(HOST);
  4747. ASSERT_GT(port, 0);
  4748. thread t = thread([&] { svr.listen_after_bind(); });
  4749. auto se = detail::scope_exit([&] {
  4750. svr.stop();
  4751. t.join();
  4752. ASSERT_FALSE(svr.is_running());
  4753. });
  4754. svr.wait_until_ready();
  4755. Client cli(HOST, port);
  4756. for (auto path : {"/throw", "/created-then-throw"}) {
  4757. auto res = cli.Get(path);
  4758. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4759. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4760. }
  4761. }
  4762. TEST(ExceptionTest, AndErrorHandler) {
  4763. Server svr;
  4764. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4765. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4766. });
  4767. svr.set_exception_handler(
  4768. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4769. EXPECT_FALSE(ep == nullptr);
  4770. try {
  4771. std::rethrow_exception(ep);
  4772. } catch (std::exception &e) {
  4773. res.set_content(e.what(), "text/html");
  4774. } catch (...) {}
  4775. res.status = StatusCode::InternalServerError_500;
  4776. });
  4777. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4778. throw std::runtime_error("EXCEPTION");
  4779. });
  4780. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4781. res.set_content("ERROR", "text/html");
  4782. res.status = StatusCode::InternalServerError_500;
  4783. });
  4784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4785. auto se = detail::scope_exit([&] {
  4786. svr.stop();
  4787. thread.join();
  4788. ASSERT_FALSE(svr.is_running());
  4789. });
  4790. svr.wait_until_ready();
  4791. Client cli(HOST, PORT);
  4792. {
  4793. auto res = cli.Get("/exception");
  4794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4795. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4796. EXPECT_EQ("EXCEPTION", res->body);
  4797. }
  4798. {
  4799. auto res = cli.Get("/error");
  4800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4801. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4802. EXPECT_EQ("ERROR", res->body);
  4803. }
  4804. {
  4805. auto res = cli.Get("/invalid");
  4806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4807. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4808. EXPECT_EQ("NOT_FOUND", res->body);
  4809. }
  4810. }
  4811. #endif
  4812. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4813. // An exception from a user callback outside process_request()'s try/catch
  4814. // used to unwind into the task queue - which does not catch - and terminate
  4815. // the process. Each test below runs the server on a single worker thread: a
  4816. // guard that catches the exception but still loses the thread would otherwise
  4817. // be hidden by a spare worker serving the follow-up request. Note that a
  4818. // regression here aborts the whole test binary rather than failing one test.
  4819. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4820. Server svr;
  4821. svr.new_task_queue = [] { return new ThreadPool(1); };
  4822. std::atomic<int> reported{0};
  4823. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4824. if (err == Error::UserCallbackException) { reported++; }
  4825. });
  4826. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4827. res.set_content_provider(
  4828. 1024, "text/plain",
  4829. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4830. sink.write("hello", 5);
  4831. throw std::runtime_error("from the content provider");
  4832. });
  4833. });
  4834. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4835. res.set_content("ok", "text/plain");
  4836. });
  4837. auto port = svr.bind_to_any_port(HOST);
  4838. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4839. auto se = detail::scope_exit([&] {
  4840. svr.stop();
  4841. listen_thread.join();
  4842. ASSERT_FALSE(svr.is_running());
  4843. });
  4844. svr.wait_until_ready();
  4845. {
  4846. Client cli(HOST, port);
  4847. cli.set_read_timeout(5, 0);
  4848. EXPECT_FALSE(cli.Get("/throw"));
  4849. }
  4850. EXPECT_TRUE(svr.is_running());
  4851. EXPECT_EQ(1, reported.load());
  4852. // A request on a fresh connection is still served.
  4853. {
  4854. Client cli(HOST, port);
  4855. auto res = cli.Get("/ok");
  4856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4857. EXPECT_EQ(StatusCode::OK_200, res->status);
  4858. EXPECT_EQ("ok", res->body);
  4859. }
  4860. }
  4861. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4862. Server svr;
  4863. svr.new_task_queue = [] { return new ThreadPool(1); };
  4864. std::atomic<bool> should_throw{true};
  4865. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4866. res.set_content("hi", "text/plain");
  4867. });
  4868. svr.set_post_routing_handler(
  4869. [&](const Request & /*req*/, Response & /*res*/) {
  4870. if (should_throw) {
  4871. throw std::runtime_error("from the post-routing handler");
  4872. }
  4873. });
  4874. auto port = svr.bind_to_any_port(HOST);
  4875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4876. auto se = detail::scope_exit([&] {
  4877. svr.stop();
  4878. listen_thread.join();
  4879. ASSERT_FALSE(svr.is_running());
  4880. });
  4881. svr.wait_until_ready();
  4882. {
  4883. Client cli(HOST, port);
  4884. cli.set_read_timeout(5, 0);
  4885. EXPECT_FALSE(cli.Get("/hi"));
  4886. }
  4887. EXPECT_TRUE(svr.is_running());
  4888. should_throw = false;
  4889. {
  4890. Client cli(HOST, port);
  4891. auto res = cli.Get("/hi");
  4892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. EXPECT_EQ("hi", res->body);
  4895. }
  4896. }
  4897. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4898. // The guard reports the caught exception through the error logger, which is
  4899. // a user callback too. A logger that throws has to be contained as well, or
  4900. // the process would terminate from inside the catch.
  4901. Server svr;
  4902. svr.new_task_queue = [] { return new ThreadPool(1); };
  4903. std::atomic<int> reported{0};
  4904. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4905. if (err == Error::UserCallbackException) {
  4906. reported++;
  4907. throw std::runtime_error("from the error logger");
  4908. }
  4909. });
  4910. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4911. res.set_content_provider(
  4912. 1024, "text/plain",
  4913. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4914. sink.write("hello", 5);
  4915. throw std::runtime_error("from the content provider");
  4916. });
  4917. });
  4918. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4919. res.set_content("ok", "text/plain");
  4920. });
  4921. auto port = svr.bind_to_any_port(HOST);
  4922. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4923. auto se = detail::scope_exit([&] {
  4924. svr.stop();
  4925. listen_thread.join();
  4926. ASSERT_FALSE(svr.is_running());
  4927. });
  4928. svr.wait_until_ready();
  4929. {
  4930. Client cli(HOST, port);
  4931. cli.set_read_timeout(5, 0);
  4932. EXPECT_FALSE(cli.Get("/throw"));
  4933. }
  4934. EXPECT_TRUE(svr.is_running());
  4935. EXPECT_EQ(1, reported.load());
  4936. {
  4937. Client cli(HOST, port);
  4938. auto res = cli.Get("/ok");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("ok", res->body);
  4942. }
  4943. }
  4944. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4945. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4946. // so the exception unwinds through the ws::WebSocket object on its way to
  4947. // the guard. None of the HTTP cases above cross that.
  4948. Server svr;
  4949. svr.new_task_queue = [] { return new ThreadPool(1); };
  4950. std::atomic<int> reported{0};
  4951. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4952. if (err == Error::UserCallbackException) { reported++; }
  4953. });
  4954. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4955. throw std::runtime_error("from the WebSocket handler");
  4956. });
  4957. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4958. res.set_content("ok", "text/plain");
  4959. });
  4960. auto port = svr.bind_to_any_port(HOST);
  4961. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4962. auto se = detail::scope_exit([&] {
  4963. svr.stop();
  4964. listen_thread.join();
  4965. ASSERT_FALSE(svr.is_running());
  4966. });
  4967. svr.wait_until_ready();
  4968. {
  4969. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4970. "/ws");
  4971. auto res = client.connect();
  4972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4973. // The server dropped the connection instead of dying.
  4974. std::string msg;
  4975. EXPECT_FALSE(client.read(msg));
  4976. client.close();
  4977. }
  4978. EXPECT_TRUE(svr.is_running());
  4979. EXPECT_EQ(1, reported.load());
  4980. {
  4981. Client cli(HOST, port);
  4982. auto res = cli.Get("/ok");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("ok", res->body);
  4986. }
  4987. }
  4988. #ifdef CPPHTTPLIB_SSL_ENABLED
  4989. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4990. // SSLServer::process_and_close_socket() is a separate overload with its own
  4991. // guard, so it is exercised on its own.
  4992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4993. ASSERT_TRUE(svr.is_valid());
  4994. svr.new_task_queue = [] { return new ThreadPool(1); };
  4995. std::atomic<int> reported{0};
  4996. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4997. if (err == Error::UserCallbackException) { reported++; }
  4998. });
  4999. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5000. res.set_content_provider(
  5001. 1024, "text/plain",
  5002. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5003. sink.write("hello", 5);
  5004. throw std::runtime_error("from the content provider");
  5005. });
  5006. });
  5007. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5008. res.set_content("ok", "text/plain");
  5009. });
  5010. auto port = svr.bind_to_any_port(HOST);
  5011. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5012. auto se = detail::scope_exit([&] {
  5013. svr.stop();
  5014. listen_thread.join();
  5015. ASSERT_FALSE(svr.is_running());
  5016. });
  5017. svr.wait_until_ready();
  5018. {
  5019. SSLClient cli(HOST, port);
  5020. cli.enable_server_certificate_verification(false);
  5021. cli.set_read_timeout(5, 0);
  5022. EXPECT_FALSE(cli.Get("/throw"));
  5023. }
  5024. EXPECT_TRUE(svr.is_running());
  5025. EXPECT_EQ(1, reported.load());
  5026. {
  5027. SSLClient cli(HOST, port);
  5028. cli.enable_server_certificate_verification(false);
  5029. auto res = cli.Get("/ok");
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ("ok", res->body);
  5033. }
  5034. }
  5035. #endif
  5036. #endif
  5037. TEST(NoContentTest, ContentLength) {
  5038. Server svr;
  5039. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5040. res.status = StatusCode::NoContent_204;
  5041. });
  5042. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5043. auto se = detail::scope_exit([&] {
  5044. svr.stop();
  5045. thread.join();
  5046. ASSERT_FALSE(svr.is_running());
  5047. });
  5048. svr.wait_until_ready();
  5049. {
  5050. Client cli(HOST, PORT);
  5051. auto res = cli.Get("/hi");
  5052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5053. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5054. // RFC 9110 8.6: none in a 204 response
  5055. EXPECT_FALSE(res->has_header("Content-Length"));
  5056. }
  5057. }
  5058. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5059. Server svr;
  5060. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5061. res.set_header("Content-Length", "5");
  5062. res.set_content("hello world", "text/plain");
  5063. });
  5064. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5065. // A body that reads as the last chunk, were it taken as chunked
  5066. res.set_header("Transfer-Encoding", "chunked");
  5067. res.set_content("0\r\n\r\n", "text/plain");
  5068. });
  5069. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5070. res.set_header("Content-Length", "2");
  5071. res.set_content_provider(5, "text/plain",
  5072. [](size_t offset, size_t length, DataSink &sink) {
  5073. sink.write(&"hello"[offset], length);
  5074. return true;
  5075. });
  5076. });
  5077. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5078. res.set_header("Content-Length", "1234");
  5079. });
  5080. thread t = thread([&] { svr.listen(HOST, PORT); });
  5081. auto se = detail::scope_exit([&] {
  5082. svr.stop();
  5083. t.join();
  5084. ASSERT_FALSE(svr.is_running());
  5085. });
  5086. svr.wait_until_ready();
  5087. Client cli(HOST, PORT);
  5088. cli.set_read_timeout(1, 0);
  5089. auto expect_body = [&](const Result &res, const std::string &body) {
  5090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5091. EXPECT_EQ(body, res->body);
  5092. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5093. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5094. };
  5095. Headers identity{{"Accept-Encoding", ""}};
  5096. expect_body(cli.Get("/body", identity), "hello world");
  5097. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5098. expect_body(cli.Get("/body",
  5099. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5100. "he");
  5101. expect_body(cli.Get("/provider", identity), "hello");
  5102. expect_body(cli.Get("/empty", identity), "");
  5103. // A HEAD response may give the length of the body a GET would get.
  5104. auto res = cli.Head("/empty");
  5105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5106. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5107. }
  5108. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5109. Server svr;
  5110. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5111. res.set_content("short", "text/plain");
  5112. });
  5113. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5114. res.body += " with a footer";
  5115. res.set_header("Transfer-Encoding", "chunked");
  5116. });
  5117. thread t = thread([&] { svr.listen(HOST, PORT); });
  5118. auto se = detail::scope_exit([&] {
  5119. svr.stop();
  5120. t.join();
  5121. ASSERT_FALSE(svr.is_running());
  5122. });
  5123. svr.wait_until_ready();
  5124. Client cli(HOST, PORT);
  5125. cli.set_read_timeout(1, 0);
  5126. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. EXPECT_EQ("short with a footer", res->body);
  5129. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5130. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5131. }
  5132. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5133. Server svr;
  5134. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5135. res.set_header("Content-Length", "3");
  5136. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5137. sink.write("abc", 3);
  5138. sink.done();
  5139. return true;
  5140. });
  5141. });
  5142. thread t = thread([&] { svr.listen(HOST, PORT); });
  5143. auto se = detail::scope_exit([&] {
  5144. svr.stop();
  5145. t.join();
  5146. ASSERT_FALSE(svr.is_running());
  5147. });
  5148. svr.wait_until_ready();
  5149. Client cli(HOST, PORT);
  5150. cli.set_keep_alive(true);
  5151. auto res = cli.Get("/");
  5152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5153. EXPECT_EQ("abc", res->body);
  5154. EXPECT_FALSE(res->has_header("Content-Length"));
  5155. EXPECT_EQ("close", res->get_header_value("Connection"));
  5156. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5157. // No body to delimit
  5158. auto head = cli.Head("/");
  5159. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5160. EXPECT_FALSE(head->has_header("Connection"));
  5161. }
  5162. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5163. #ifdef CPPHTTPLIB_SSL_ENABLED
  5164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5165. ASSERT_TRUE(svr.is_valid());
  5166. #else
  5167. Server svr;
  5168. #endif
  5169. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5170. if (req.path == "/routing_handler") {
  5171. res.set_header("PRE_ROUTING", "on");
  5172. res.set_content("Routing Handler", "text/plain");
  5173. return httplib::Server::HandlerResponse::Handled;
  5174. }
  5175. return httplib::Server::HandlerResponse::Unhandled;
  5176. });
  5177. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5178. res.set_content("Error", "text/html");
  5179. });
  5180. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5181. if (req.path == "/routing_handler") {
  5182. res.set_header("POST_ROUTING", "on");
  5183. }
  5184. });
  5185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5186. res.set_content("Hello World!\n", "text/plain");
  5187. });
  5188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5189. auto se = detail::scope_exit([&] {
  5190. svr.stop();
  5191. thread.join();
  5192. ASSERT_FALSE(svr.is_running());
  5193. });
  5194. svr.wait_until_ready();
  5195. {
  5196. #ifdef CPPHTTPLIB_SSL_ENABLED
  5197. SSLClient cli(HOST, PORT);
  5198. cli.enable_server_certificate_verification(false);
  5199. #else
  5200. Client cli(HOST, PORT);
  5201. #endif
  5202. auto res = cli.Get("/routing_handler");
  5203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("Routing Handler", res->body);
  5206. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5207. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5208. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5209. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5210. }
  5211. {
  5212. #ifdef CPPHTTPLIB_SSL_ENABLED
  5213. SSLClient cli(HOST, PORT);
  5214. cli.enable_server_certificate_verification(false);
  5215. #else
  5216. Client cli(HOST, PORT);
  5217. #endif
  5218. auto res = cli.Get("/hi");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ("Hello World!\n", res->body);
  5222. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5223. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5224. }
  5225. {
  5226. #ifdef CPPHTTPLIB_SSL_ENABLED
  5227. SSLClient cli(HOST, PORT);
  5228. cli.enable_server_certificate_verification(false);
  5229. #else
  5230. Client cli(HOST, PORT);
  5231. #endif
  5232. auto res = cli.Get("/aaa");
  5233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5235. EXPECT_EQ("Error", res->body);
  5236. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5237. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5238. }
  5239. }
  5240. TEST(RequestHandlerTest, PreRequestHandler) {
  5241. auto route_path = "/user/:user";
  5242. Server svr;
  5243. svr.Get("/hi", [](const Request &, Response &res) {
  5244. res.set_content("hi", "text/plain");
  5245. });
  5246. svr.Get(route_path, [](const Request &req, Response &res) {
  5247. res.set_content(req.path_params.at("user"), "text/plain");
  5248. });
  5249. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5250. if (req.matched_route == route_path) {
  5251. auto user = req.path_params.at("user");
  5252. if (user != "john") {
  5253. res.status = StatusCode::Forbidden_403;
  5254. res.set_content("error", "text/html");
  5255. return Server::HandlerResponse::Handled;
  5256. }
  5257. }
  5258. return Server::HandlerResponse::Unhandled;
  5259. });
  5260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5261. auto se = detail::scope_exit([&] {
  5262. svr.stop();
  5263. thread.join();
  5264. ASSERT_FALSE(svr.is_running());
  5265. });
  5266. svr.wait_until_ready();
  5267. Client cli(HOST, PORT);
  5268. {
  5269. auto res = cli.Get("/hi");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("hi", res->body);
  5273. }
  5274. {
  5275. auto res = cli.Get("/user/john");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ("john", res->body);
  5279. }
  5280. {
  5281. auto res = cli.Get("/user/invalid-user");
  5282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5283. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5284. EXPECT_EQ("error", res->body);
  5285. }
  5286. }
  5287. // The pre-request handler must run before the request body is read, so a
  5288. // rejected request never forces the server to buffer a (potentially large)
  5289. // body. Here the posted body is larger than the payload limit: if the body
  5290. // were read first the server would answer 413, but because the pre-request
  5291. // handler runs first it answers 403 and the body is never read.
  5292. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5293. Server svr;
  5294. svr.set_payload_max_length(8);
  5295. auto handler_ran = false;
  5296. svr.Post("/reject", [&](const Request &req, Response &res) {
  5297. handler_ran = true;
  5298. res.set_content(req.body, "text/plain");
  5299. });
  5300. svr.Post("/accept", [](const Request &req, Response &res) {
  5301. res.set_content(req.body, "text/plain");
  5302. });
  5303. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5304. if (req.matched_route == "/reject") {
  5305. res.status = StatusCode::Forbidden_403;
  5306. res.set_content("denied", "text/plain");
  5307. return Server::HandlerResponse::Handled;
  5308. }
  5309. return Server::HandlerResponse::Unhandled;
  5310. });
  5311. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5312. auto se = detail::scope_exit([&] {
  5313. svr.stop();
  5314. thread.join();
  5315. ASSERT_FALSE(svr.is_running());
  5316. });
  5317. svr.wait_until_ready();
  5318. Client cli(HOST, PORT);
  5319. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5320. // rejects with 403 before the body is read, so 413 is never reached.
  5321. {
  5322. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5325. EXPECT_EQ("denied", res->body);
  5326. EXPECT_FALSE(handler_ran);
  5327. }
  5328. // An approved route still reads the body and enforces the payload limit.
  5329. {
  5330. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5333. }
  5334. }
  5335. TEST(UserDataTest, BasicOperations) {
  5336. httplib::UserData ud;
  5337. // Initially empty
  5338. EXPECT_FALSE(ud.has("key"));
  5339. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5340. // set and get
  5341. ud.set("key", 42);
  5342. EXPECT_TRUE(ud.has("key"));
  5343. auto *p = ud.get<int>("key");
  5344. ASSERT_NE(nullptr, p);
  5345. EXPECT_EQ(42, *p);
  5346. // Type mismatch → nullptr
  5347. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5348. // Overwrite with different type
  5349. ud.set("key", std::string("hello"));
  5350. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5351. auto *s = ud.get<std::string>("key");
  5352. ASSERT_NE(nullptr, s);
  5353. EXPECT_EQ("hello", *s);
  5354. // erase
  5355. ud.erase("key");
  5356. EXPECT_FALSE(ud.has("key"));
  5357. // clear
  5358. ud.set("a", 1);
  5359. ud.set("b", 2);
  5360. ud.clear();
  5361. EXPECT_FALSE(ud.has("a"));
  5362. EXPECT_FALSE(ud.has("b"));
  5363. }
  5364. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5365. struct AuthCtx {
  5366. std::string user_id;
  5367. };
  5368. Server svr;
  5369. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5370. res.user_data.set("auth", AuthCtx{"alice"});
  5371. return Server::HandlerResponse::Unhandled;
  5372. });
  5373. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5374. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5375. ASSERT_NE(nullptr, ctx);
  5376. res.set_content("Hello " + ctx->user_id, "text/plain");
  5377. });
  5378. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5379. auto se = detail::scope_exit([&] {
  5380. svr.stop();
  5381. thread.join();
  5382. ASSERT_FALSE(svr.is_running());
  5383. });
  5384. svr.wait_until_ready();
  5385. Client cli(HOST, PORT);
  5386. auto res = cli.Get("/me");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. EXPECT_EQ("Hello alice", res->body);
  5390. }
  5391. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5392. struct RoleCtx {
  5393. std::string role;
  5394. };
  5395. Server svr;
  5396. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5397. res.user_data.set("role", RoleCtx{"admin"});
  5398. return Server::HandlerResponse::Unhandled;
  5399. });
  5400. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5401. auto *ctx = res.user_data.get<RoleCtx>("role");
  5402. ASSERT_NE(nullptr, ctx);
  5403. res.set_content(ctx->role, "text/plain");
  5404. });
  5405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5406. auto se = detail::scope_exit([&] {
  5407. svr.stop();
  5408. thread.join();
  5409. ASSERT_FALSE(svr.is_running());
  5410. });
  5411. svr.wait_until_ready();
  5412. Client cli(HOST, PORT);
  5413. auto res = cli.Get("/role");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ("admin", res->body);
  5417. }
  5418. TEST(InvalidFormatTest, StatusCode) {
  5419. Server svr;
  5420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5421. res.set_content("Hello World!\n", "text/plain");
  5422. res.status = 9999; // Status should be a three-digit code...
  5423. });
  5424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5425. auto se = detail::scope_exit([&] {
  5426. svr.stop();
  5427. thread.join();
  5428. ASSERT_FALSE(svr.is_running());
  5429. });
  5430. svr.wait_until_ready();
  5431. {
  5432. Client cli(HOST, PORT);
  5433. auto res = cli.Get("/hi");
  5434. ASSERT_FALSE(res);
  5435. }
  5436. }
  5437. TEST(URLFragmentTest, WithFragment) {
  5438. Server svr;
  5439. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5440. EXPECT_TRUE(req.target == "/hi");
  5441. });
  5442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5443. auto se = detail::scope_exit([&] {
  5444. svr.stop();
  5445. thread.join();
  5446. ASSERT_FALSE(svr.is_running());
  5447. });
  5448. svr.wait_until_ready();
  5449. {
  5450. Client cli(HOST, PORT);
  5451. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5452. EXPECT_TRUE(res);
  5453. EXPECT_EQ(StatusCode::OK_200, res->status);
  5454. res = cli.Get("/hi%23key1=val1=key2=val2");
  5455. EXPECT_TRUE(res);
  5456. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5457. }
  5458. }
  5459. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5460. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5461. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5462. Server svr;
  5463. std::vector<std::string> targets;
  5464. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5465. targets.push_back(req.target);
  5466. });
  5467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5468. auto se = detail::scope_exit([&] {
  5469. svr.stop();
  5470. thread.join();
  5471. ASSERT_FALSE(svr.is_running());
  5472. });
  5473. svr.wait_until_ready();
  5474. Client cli(HOST, PORT);
  5475. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5476. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5477. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5478. // A '?' after the '#' belongs to the fragment, not to the query.
  5479. Request req;
  5480. req.method = "GET";
  5481. req.path = "/hi#f?x=1";
  5482. req.params.emplace("a", "1");
  5483. Response res;
  5484. auto error = Error::Success;
  5485. EXPECT_TRUE(cli.send(req, res, error));
  5486. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5487. "/hi?a=1"}),
  5488. targets);
  5489. }
  5490. TEST(HeaderWriter, SetHeaderWriter) {
  5491. Server svr;
  5492. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5493. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5494. return detail::write_headers(strm, hdrs);
  5495. });
  5496. svr.Get("/hi", [](const Request &req, Response &res) {
  5497. auto it = req.headers.find("CustomClientHeader");
  5498. EXPECT_TRUE(it != req.headers.end());
  5499. EXPECT_EQ(it->second, "CustomClientValue");
  5500. res.set_content("Hello World!\n", "text/plain");
  5501. });
  5502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5503. auto se = detail::scope_exit([&] {
  5504. svr.stop();
  5505. thread.join();
  5506. ASSERT_FALSE(svr.is_running());
  5507. });
  5508. svr.wait_until_ready();
  5509. {
  5510. Client cli(HOST, PORT);
  5511. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5512. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5513. return detail::write_headers(strm, hdrs);
  5514. });
  5515. auto res = cli.Get("/hi");
  5516. EXPECT_TRUE(res);
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. auto it = res->headers.find("CustomServerHeader");
  5519. EXPECT_TRUE(it != res->headers.end());
  5520. EXPECT_EQ(it->second, "CustomServerValue");
  5521. }
  5522. }
  5523. class ServerTest : public ::testing::Test {
  5524. protected:
  5525. ServerTest()
  5526. : cli_(HOST, PORT)
  5527. #ifdef CPPHTTPLIB_SSL_ENABLED
  5528. ,
  5529. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5530. #endif
  5531. {
  5532. #ifdef CPPHTTPLIB_SSL_ENABLED
  5533. cli_.enable_server_certificate_verification(false);
  5534. #endif
  5535. // Allow LARGE_DATA (100MB) responses
  5536. cli_.set_payload_max_length(200 * 1024 * 1024);
  5537. }
  5538. virtual void SetUp() {
  5539. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5540. svr_.set_payload_max_length(200 * 1024 * 1024);
  5541. svr_.set_mount_point("/", "./www");
  5542. svr_.set_mount_point("/mount", "./www2");
  5543. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5544. svr_.Get("/hi",
  5545. [&](const Request & /*req*/, Response &res) {
  5546. res.set_content("Hello World!", "text/plain");
  5547. })
  5548. .Get("/file_content",
  5549. [&](const Request & /*req*/, Response &res) {
  5550. res.set_file_content("./www/dir/test.html");
  5551. })
  5552. .Get("/file_content_with_content_type",
  5553. [&](const Request & /*req*/, Response &res) {
  5554. res.set_file_content("./www/file", "text/plain");
  5555. })
  5556. .Get("/invalid_file_content",
  5557. [&](const Request & /*req*/, Response &res) {
  5558. res.set_file_content("./www/dir/invalid_file_path");
  5559. })
  5560. .Get("/http_response_splitting",
  5561. [&](const Request & /*req*/, Response &res) {
  5562. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5563. EXPECT_EQ(0U, res.headers.size());
  5564. EXPECT_FALSE(res.has_header("a"));
  5565. res.set_header("a", "1\nSet-Cookie: a=1");
  5566. EXPECT_EQ(0U, res.headers.size());
  5567. EXPECT_FALSE(res.has_header("a"));
  5568. res.set_header("a", "1\rSet-Cookie: a=1");
  5569. EXPECT_EQ(0U, res.headers.size());
  5570. EXPECT_FALSE(res.has_header("a"));
  5571. res.set_header("a\r\nb", "0");
  5572. EXPECT_EQ(0U, res.headers.size());
  5573. EXPECT_FALSE(res.has_header("a"));
  5574. res.set_header("a\rb", "0");
  5575. EXPECT_EQ(0U, res.headers.size());
  5576. EXPECT_FALSE(res.has_header("a"));
  5577. res.set_header("a\nb", "0");
  5578. EXPECT_EQ(0U, res.headers.size());
  5579. EXPECT_FALSE(res.has_header("a"));
  5580. res.set_redirect("1\r\nSet-Cookie: a=1");
  5581. EXPECT_EQ(0U, res.headers.size());
  5582. EXPECT_FALSE(res.has_header("Location"));
  5583. })
  5584. .Get("/slow",
  5585. [&](const Request & /*req*/, Response &res) {
  5586. std::this_thread::sleep_for(std::chrono::seconds(4));
  5587. res.set_content("slow", "text/plain");
  5588. })
  5589. #if 0
  5590. .Post("/slowpost",
  5591. [&](const Request & /*req*/, Response &res) {
  5592. std::this_thread::sleep_for(std::chrono::seconds(2));
  5593. res.set_content("slow", "text/plain");
  5594. })
  5595. #endif
  5596. .Get("/remote_addr",
  5597. [&](const Request &req, Response &res) {
  5598. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5599. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5600. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5601. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5602. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5603. #endif
  5604. res.set_content(req.remote_addr, "text/plain");
  5605. })
  5606. .Get("/local_addr",
  5607. [&](const Request &req, Response &res) {
  5608. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5609. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5610. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5611. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5612. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5613. #endif
  5614. auto local_addr = req.local_addr;
  5615. auto local_port = std::to_string(req.local_port);
  5616. res.set_content(local_addr.append(":").append(local_port),
  5617. "text/plain");
  5618. })
  5619. .Get("/endwith%",
  5620. [&](const Request & /*req*/, Response &res) {
  5621. res.set_content("Hello World!", "text/plain");
  5622. })
  5623. .Get("/a\\+\\+b",
  5624. [&](const Request &req, Response &res) {
  5625. ASSERT_TRUE(req.has_param("a +b"));
  5626. auto val = req.get_param_value("a +b");
  5627. res.set_content(val, "text/plain");
  5628. })
  5629. .Get("/", [&](const Request & /*req*/,
  5630. Response &res) { res.set_redirect("/hi"); })
  5631. .Post("/1",
  5632. [](const Request & /*req*/, Response &res) {
  5633. res.set_redirect("/2", StatusCode::SeeOther_303);
  5634. })
  5635. .Get("/2",
  5636. [](const Request & /*req*/, Response &res) {
  5637. res.set_content("redirected.", "text/plain");
  5638. res.status = StatusCode::OK_200;
  5639. })
  5640. .Post("/person",
  5641. [&](const Request &req, Response &res) {
  5642. if (req.has_param("name") && req.has_param("note")) {
  5643. persons_[req.get_param_value("name")] =
  5644. req.get_param_value("note");
  5645. } else {
  5646. res.status = StatusCode::BadRequest_400;
  5647. }
  5648. })
  5649. .Put("/person",
  5650. [&](const Request &req, Response &res) {
  5651. if (req.has_param("name") && req.has_param("note")) {
  5652. persons_[req.get_param_value("name")] =
  5653. req.get_param_value("note");
  5654. } else {
  5655. res.status = StatusCode::BadRequest_400;
  5656. }
  5657. })
  5658. .Get("/person/(.*)",
  5659. [&](const Request &req, Response &res) {
  5660. string name = req.matches[1];
  5661. if (persons_.find(name) != persons_.end()) {
  5662. auto note = persons_[name];
  5663. res.set_content(note, "text/plain");
  5664. } else {
  5665. res.status = StatusCode::NotFound_404;
  5666. }
  5667. })
  5668. .Delete("/person",
  5669. [&](const Request &req, Response &res) {
  5670. if (req.has_param("name")) {
  5671. string name = req.get_param_value("name");
  5672. if (persons_.find(name) != persons_.end()) {
  5673. persons_.erase(name);
  5674. res.set_content("DELETED", "text/plain");
  5675. } else {
  5676. res.status = StatusCode::NotFound_404;
  5677. }
  5678. } else {
  5679. res.status = StatusCode::BadRequest_400;
  5680. }
  5681. })
  5682. .Post("/x-www-form-urlencoded-json",
  5683. [&](const Request &req, Response &res) {
  5684. auto json = req.get_param_value("json");
  5685. ASSERT_EQ(JSON_DATA, json);
  5686. res.set_content(json, "appliation/json");
  5687. res.status = StatusCode::OK_200;
  5688. })
  5689. .Get("/streamed-chunked",
  5690. [&](const Request & /*req*/, Response &res) {
  5691. res.set_chunked_content_provider(
  5692. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5693. sink.os << "123";
  5694. sink.os << "456";
  5695. sink.os << "789";
  5696. sink.done();
  5697. return true;
  5698. });
  5699. })
  5700. .Get("/streamed-chunked-with-prohibited-trailer",
  5701. [&](const Request & /*req*/, Response &res) {
  5702. auto i = new int(0);
  5703. // Declare both a prohibited trailer (Content-Length) and an
  5704. // allowed one
  5705. res.set_header("Trailer", "Content-Length, X-Allowed");
  5706. res.set_chunked_content_provider(
  5707. "text/plain",
  5708. [i](size_t /*offset*/, DataSink &sink) {
  5709. switch (*i) {
  5710. case 0: sink.os << "123"; break;
  5711. case 1: sink.os << "456"; break;
  5712. case 2: sink.os << "789"; break;
  5713. case 3: {
  5714. sink.done_with_trailer(
  5715. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5716. } break;
  5717. }
  5718. (*i)++;
  5719. return true;
  5720. },
  5721. [i](bool success) {
  5722. EXPECT_TRUE(success);
  5723. delete i;
  5724. });
  5725. })
  5726. .Get("/streamed-chunked2",
  5727. [&](const Request & /*req*/, Response &res) {
  5728. auto i = new int(0);
  5729. res.set_chunked_content_provider(
  5730. "text/plain",
  5731. [i](size_t /*offset*/, DataSink &sink) {
  5732. switch (*i) {
  5733. case 0: sink.os << "123"; break;
  5734. case 1: sink.os << "456"; break;
  5735. case 2: sink.os << "789"; break;
  5736. case 3: sink.done(); break;
  5737. }
  5738. (*i)++;
  5739. return true;
  5740. },
  5741. [i](bool success) {
  5742. EXPECT_TRUE(success);
  5743. delete i;
  5744. });
  5745. })
  5746. .Get("/streamed-chunked-with-trailer",
  5747. [&](const Request & /*req*/, Response &res) {
  5748. auto i = new int(0);
  5749. res.set_header("Trailer", "Dummy1, Dummy2");
  5750. res.set_chunked_content_provider(
  5751. "text/plain",
  5752. [i](size_t /*offset*/, DataSink &sink) {
  5753. switch (*i) {
  5754. case 0: sink.os << "123"; break;
  5755. case 1: sink.os << "456"; break;
  5756. case 2: sink.os << "789"; break;
  5757. case 3: {
  5758. sink.done_with_trailer(
  5759. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5760. } break;
  5761. }
  5762. (*i)++;
  5763. return true;
  5764. },
  5765. [i](bool success) {
  5766. EXPECT_TRUE(success);
  5767. delete i;
  5768. });
  5769. })
  5770. .Get("/streamed",
  5771. [&](const Request & /*req*/, Response &res) {
  5772. res.set_content_provider(
  5773. 6, "text/plain",
  5774. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5775. sink.os << (offset < 3 ? "a" : "b");
  5776. return true;
  5777. });
  5778. })
  5779. .Get("/streamed-without-length",
  5780. [&](const Request & /*req*/, Response &res) {
  5781. auto data = new std::string("abcdefg");
  5782. res.set_content_provider(
  5783. "text/plain",
  5784. [data](size_t offset, DataSink &sink) {
  5785. if (offset < data->size()) {
  5786. sink.os << data->substr(offset);
  5787. }
  5788. sink.done();
  5789. return true;
  5790. },
  5791. [data](bool success) {
  5792. EXPECT_TRUE(success);
  5793. delete data;
  5794. });
  5795. })
  5796. .Get("/streamed-with-range",
  5797. [&](const Request &req, Response &res) {
  5798. auto data = new std::string("abcdefg");
  5799. // An explicit status keeps the server from picking the 206 it
  5800. // would otherwise choose for a ranged request, so the response
  5801. // is not a partial representation.
  5802. auto status = req.get_param_value("status");
  5803. if (status == "200") {
  5804. res.status = StatusCode::OK_200;
  5805. } else if (status == "403") {
  5806. res.status = StatusCode::Forbidden_403;
  5807. }
  5808. res.set_content_provider(
  5809. data->size(), "text/plain",
  5810. [data](size_t offset, size_t length, DataSink &sink) {
  5811. size_t DATA_CHUNK_SIZE = 4;
  5812. const auto &d = *data;
  5813. auto out_len =
  5814. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5815. auto ret =
  5816. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5817. EXPECT_TRUE(ret);
  5818. return true;
  5819. },
  5820. [data, &req](bool success) {
  5821. EXPECT_EQ(success, !req.has_param("error"));
  5822. delete data;
  5823. });
  5824. })
  5825. .Get("/streamed-cancel",
  5826. [&](const Request & /*req*/, Response &res) {
  5827. res.set_content_provider(
  5828. size_t(-1), "text/plain",
  5829. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5830. sink.os << "data_chunk";
  5831. return true;
  5832. });
  5833. })
  5834. .Get("/regex-with-delimiter",
  5835. [&](const Request &req, Response & /*res*/) {
  5836. ASSERT_TRUE(req.has_param("key"));
  5837. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5838. })
  5839. .Get("/with-range",
  5840. [&](const Request & /*req*/, Response &res) {
  5841. res.set_content("abcdefg", "text/plain");
  5842. })
  5843. .Get("/test-start-time",
  5844. [&](const Request &req, Response & /*res*/) {
  5845. EXPECT_NE(req.start_time_,
  5846. std::chrono::steady_clock::time_point::min());
  5847. })
  5848. .Get("/with-range-customized-response",
  5849. [&](const Request & /*req*/, Response &res) {
  5850. res.status = StatusCode::BadRequest_400;
  5851. res.set_content(JSON_DATA, "application/json");
  5852. })
  5853. .Post("/chunked",
  5854. [&](const Request &req, Response & /*res*/) {
  5855. EXPECT_EQ(req.body, "dechunked post body");
  5856. })
  5857. .Post("/large-chunked",
  5858. [&](const Request &req, Response & /*res*/) {
  5859. std::string expected(6 * 30 * 1024u, 'a');
  5860. EXPECT_EQ(req.body, expected);
  5861. })
  5862. .Post("/multipart",
  5863. [&](const Request &req, Response & /*res*/) {
  5864. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5865. req.form.get_field_count("text2") +
  5866. req.form.get_field_count("file3") +
  5867. req.form.get_field_count("file4"));
  5868. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5869. req.form.get_file_count("file2"));
  5870. ASSERT_TRUE(!req.form.has_file("???"));
  5871. ASSERT_TRUE(!req.form.has_field("???"));
  5872. ASSERT_TRUE(req.body.empty());
  5873. {
  5874. const auto &text = req.form.get_field("text1");
  5875. EXPECT_EQ("text default", text);
  5876. }
  5877. {
  5878. const auto &text = req.form.get_field("text2");
  5879. EXPECT_EQ("aωb", text);
  5880. }
  5881. {
  5882. const auto &file = req.form.get_file("file1");
  5883. EXPECT_EQ("hello.txt", file.filename);
  5884. EXPECT_EQ("text/plain", file.content_type);
  5885. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5886. }
  5887. {
  5888. const auto &file = req.form.get_file("file2");
  5889. EXPECT_EQ("world.json", file.filename);
  5890. EXPECT_EQ("application/json", file.content_type);
  5891. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5892. }
  5893. {
  5894. const auto &text = req.form.get_field("file3");
  5895. EXPECT_EQ(0u, text.size());
  5896. }
  5897. {
  5898. const auto &text = req.form.get_field("file4");
  5899. EXPECT_EQ(0u, text.size());
  5900. }
  5901. })
  5902. .Post("/multipart/multi_file_values",
  5903. [&](const Request &req, Response & /*res*/) {
  5904. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5905. req.form.get_field_count("multi_text1"));
  5906. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5907. ASSERT_TRUE(!req.form.has_file("???"));
  5908. ASSERT_TRUE(!req.form.has_field("???"));
  5909. ASSERT_TRUE(req.body.empty());
  5910. {
  5911. const auto &text = req.form.get_field("text");
  5912. EXPECT_EQ("default text", text);
  5913. }
  5914. {
  5915. const auto &text1_values = req.form.get_fields("multi_text1");
  5916. EXPECT_EQ(2u, text1_values.size());
  5917. EXPECT_EQ("aaaaa", text1_values[0]);
  5918. EXPECT_EQ("bbbbb", text1_values[1]);
  5919. }
  5920. {
  5921. const auto &file1_values = req.form.get_files("multi_file1");
  5922. EXPECT_EQ(2u, file1_values.size());
  5923. auto file1 = file1_values[0];
  5924. EXPECT_EQ(file1.filename, "hello.txt");
  5925. EXPECT_EQ(file1.content_type, "text/plain");
  5926. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5927. auto file2 = file1_values[1];
  5928. EXPECT_EQ(file2.filename, "world.json");
  5929. EXPECT_EQ(file2.content_type, "application/json");
  5930. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5931. }
  5932. })
  5933. .Post("/empty",
  5934. [&](const Request &req, Response &res) {
  5935. EXPECT_EQ(req.body, "");
  5936. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5937. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5938. res.set_content("empty", "text/plain");
  5939. })
  5940. .Post("/empty-no-content-type",
  5941. [&](const Request &req, Response &res) {
  5942. EXPECT_EQ(req.body, "");
  5943. EXPECT_FALSE(req.has_header("Content-Type"));
  5944. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5945. res.set_content("empty-no-content-type", "text/plain");
  5946. })
  5947. .Post("/path-only",
  5948. [&](const Request &req, Response &res) {
  5949. EXPECT_EQ(req.body, "");
  5950. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5951. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5952. res.set_content("path-only", "text/plain");
  5953. })
  5954. .Post("/path-headers-only",
  5955. [&](const Request &req, Response &res) {
  5956. EXPECT_EQ(req.body, "");
  5957. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5958. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5959. EXPECT_EQ("world", req.get_header_value("hello"));
  5960. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5961. res.set_content("path-headers-only", "text/plain");
  5962. })
  5963. .Post("/post-large",
  5964. [&](const Request &req, Response &res) {
  5965. EXPECT_EQ(req.body, LARGE_DATA);
  5966. res.set_content(req.body, "text/plain");
  5967. })
  5968. .Post("/post-loopback",
  5969. [&](const Request &, Response &res,
  5970. ContentReader const &content_reader) {
  5971. std::string body;
  5972. content_reader([&](const char *data, size_t data_length) {
  5973. body.append(data, data_length);
  5974. return true;
  5975. });
  5976. res.set_content(body, "text/plain");
  5977. })
  5978. .Put("/put-loopback",
  5979. [&](const Request &, Response &res,
  5980. ContentReader const &content_reader) {
  5981. std::string body;
  5982. content_reader([&](const char *data, size_t data_length) {
  5983. body.append(data, data_length);
  5984. return true;
  5985. });
  5986. res.set_content(body, "text/plain");
  5987. })
  5988. .Patch("/patch-loopback",
  5989. [&](const Request &, Response &res,
  5990. ContentReader const &content_reader) {
  5991. std::string body;
  5992. content_reader([&](const char *data, size_t data_length) {
  5993. body.append(data, data_length);
  5994. return true;
  5995. });
  5996. res.set_content(body, "text/plain");
  5997. })
  5998. .Put("/empty-no-content-type",
  5999. [&](const Request &req, Response &res) {
  6000. EXPECT_EQ(req.body, "");
  6001. EXPECT_FALSE(req.has_header("Content-Type"));
  6002. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6003. res.set_content("empty-no-content-type", "text/plain");
  6004. })
  6005. .Put("/put",
  6006. [&](const Request &req, Response &res) {
  6007. EXPECT_EQ(req.body, "PUT");
  6008. res.set_content(req.body, "text/plain");
  6009. })
  6010. .Put("/put-large",
  6011. [&](const Request &req, Response &res) {
  6012. EXPECT_EQ(req.body, LARGE_DATA);
  6013. res.set_content(req.body, "text/plain");
  6014. })
  6015. .Patch("/patch",
  6016. [&](const Request &req, Response &res) {
  6017. EXPECT_EQ(req.body, "PATCH");
  6018. res.set_content(req.body, "text/plain");
  6019. })
  6020. .Delete("/delete",
  6021. [&](const Request & /*req*/, Response &res) {
  6022. res.set_content("DELETE", "text/plain");
  6023. })
  6024. .Delete("/delete-body",
  6025. [&](const Request &req, Response &res) {
  6026. EXPECT_EQ(req.body, "content");
  6027. res.set_content(req.body, "text/plain");
  6028. })
  6029. .Options(R"(\*)",
  6030. [&](const Request & /*req*/, Response &res) {
  6031. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6032. })
  6033. .CustomRoute("PROPFIND", "/dav/:id",
  6034. [&](const Request &req, Response &res) {
  6035. res.set_header("x-body-size",
  6036. std::to_string(req.body.size()));
  6037. res.set_header("x-matched-route", req.matched_route);
  6038. res.set_header("x-dav-id", req.path_params.at("id"));
  6039. res.status = StatusCode::MultiStatus_207;
  6040. res.set_content(req.body, "application/xml");
  6041. })
  6042. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6043. [&](const Request &req, Response &res) {
  6044. res.set_header("x-dav-match", req.matches[1]);
  6045. res.status = StatusCode::MultiStatus_207;
  6046. })
  6047. .CustomRoute("MKCOL", "/dav-mkcol",
  6048. [&](const Request &req, Response &res) {
  6049. EXPECT_TRUE(req.body.empty());
  6050. res.status = StatusCode::Created_201;
  6051. })
  6052. .CustomRoute(
  6053. "REPORT", "/dav-report",
  6054. [&](const Request & /*req*/, Response &res,
  6055. const ContentReader &content_reader) {
  6056. std::string body;
  6057. content_reader([&](const char *data, size_t data_length) {
  6058. body.append(data, data_length);
  6059. return true;
  6060. });
  6061. res.set_header("x-body-size", std::to_string(body.size()));
  6062. res.status = StatusCode::MultiStatus_207;
  6063. res.set_content(body, "application/xml");
  6064. })
  6065. .Get("/request-target",
  6066. [&](const Request &req, Response & /*res*/) {
  6067. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6068. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6069. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6070. })
  6071. .Get("/long-query-value",
  6072. [&](const Request &req, Response & /*res*/) {
  6073. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6074. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6075. })
  6076. .Get("/too-long-query-value",
  6077. [&](const Request &req, Response & /*res*/) {
  6078. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6079. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6080. })
  6081. .Get("/array-param",
  6082. [&](const Request &req, Response & /*res*/) {
  6083. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6084. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6085. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6086. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6087. })
  6088. .Get("/array-param-values",
  6089. [&](const Request &req, Response & /*res*/) {
  6090. auto values = req.get_param_values("array");
  6091. EXPECT_EQ(3u, values.size());
  6092. EXPECT_EQ("value1", values[0]);
  6093. EXPECT_EQ("value2", values[1]);
  6094. EXPECT_EQ("value3", values[2]);
  6095. auto empty = req.get_param_values("nonexistent");
  6096. EXPECT_TRUE(empty.empty());
  6097. })
  6098. .Post("/validate-no-multiple-headers",
  6099. [&](const Request &req, Response & /*res*/) {
  6100. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6101. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6102. })
  6103. .Post("/content_receiver",
  6104. [&](const Request &req, Response &res,
  6105. const ContentReader &content_reader) {
  6106. if (req.is_multipart_form_data()) {
  6107. std::vector<FormData> items;
  6108. content_reader(
  6109. [&](const FormData &file) {
  6110. items.push_back(file);
  6111. return true;
  6112. },
  6113. [&](const char *data, size_t data_length) {
  6114. items.back().content.append(data, data_length);
  6115. return true;
  6116. });
  6117. EXPECT_EQ(5u, items.size());
  6118. {
  6119. const auto &file = get_file_value(items, "text1");
  6120. EXPECT_TRUE(file.filename.empty());
  6121. EXPECT_EQ("text default", file.content);
  6122. }
  6123. {
  6124. const auto &file = get_file_value(items, "text2");
  6125. EXPECT_TRUE(file.filename.empty());
  6126. EXPECT_EQ("aωb", file.content);
  6127. }
  6128. {
  6129. const auto &file = get_file_value(items, "file1");
  6130. EXPECT_EQ("hello.txt", file.filename);
  6131. EXPECT_EQ("text/plain", file.content_type);
  6132. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6133. }
  6134. {
  6135. const auto &file = get_file_value(items, "file2");
  6136. EXPECT_EQ("world.json", file.filename);
  6137. EXPECT_EQ("application/json", file.content_type);
  6138. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6139. }
  6140. {
  6141. const auto &file = get_file_value(items, "file3");
  6142. EXPECT_TRUE(file.filename.empty());
  6143. EXPECT_EQ("application/octet-stream", file.content_type);
  6144. EXPECT_EQ(0u, file.content.size());
  6145. }
  6146. } else {
  6147. std::string body;
  6148. content_reader([&](const char *data, size_t data_length) {
  6149. EXPECT_EQ(7U, data_length);
  6150. body.append(data, data_length);
  6151. return true;
  6152. });
  6153. EXPECT_EQ(body, "content");
  6154. res.set_content(body, "text/plain");
  6155. }
  6156. })
  6157. .Put("/content_receiver",
  6158. [&](const Request & /*req*/, Response &res,
  6159. const ContentReader &content_reader) {
  6160. std::string body;
  6161. content_reader([&](const char *data, size_t data_length) {
  6162. body.append(data, data_length);
  6163. return true;
  6164. });
  6165. EXPECT_EQ(body, "content");
  6166. res.set_content(body, "text/plain");
  6167. })
  6168. .Patch("/content_receiver",
  6169. [&](const Request & /*req*/, Response &res,
  6170. const ContentReader &content_reader) {
  6171. std::string body;
  6172. content_reader([&](const char *data, size_t data_length) {
  6173. body.append(data, data_length);
  6174. return true;
  6175. });
  6176. EXPECT_EQ(body, "content");
  6177. res.set_content(body, "text/plain");
  6178. })
  6179. .Post("/query-string-and-body",
  6180. [&](const Request &req, Response & /*res*/) {
  6181. ASSERT_TRUE(req.has_param("key"));
  6182. EXPECT_EQ(req.get_param_value("key"), "value");
  6183. EXPECT_EQ(req.body, "content");
  6184. })
  6185. .Get("/last-request",
  6186. [&](const Request &req, Response & /*res*/) {
  6187. EXPECT_EQ("close", req.get_header_value("Connection"));
  6188. })
  6189. .Get(R"(/redirect/(\d+))",
  6190. [&](const Request &req, Response &res) {
  6191. auto num = std::stoi(req.matches[1]) + 1;
  6192. std::string url = "/redirect/" + std::to_string(num);
  6193. res.set_redirect(url);
  6194. })
  6195. .Post("/binary",
  6196. [&](const Request &req, Response &res) {
  6197. EXPECT_EQ(4U, req.body.size());
  6198. EXPECT_EQ("application/octet-stream",
  6199. req.get_header_value("Content-Type"));
  6200. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6201. res.set_content(req.body, "application/octet-stream");
  6202. })
  6203. .Put("/binary",
  6204. [&](const Request &req, Response &res) {
  6205. EXPECT_EQ(4U, req.body.size());
  6206. EXPECT_EQ("application/octet-stream",
  6207. req.get_header_value("Content-Type"));
  6208. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6209. res.set_content(req.body, "application/octet-stream");
  6210. })
  6211. .Patch("/binary",
  6212. [&](const Request &req, Response &res) {
  6213. EXPECT_EQ(4U, req.body.size());
  6214. EXPECT_EQ("application/octet-stream",
  6215. req.get_header_value("Content-Type"));
  6216. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6217. res.set_content(req.body, "application/octet-stream");
  6218. })
  6219. .Delete("/binary",
  6220. [&](const Request &req, Response &res) {
  6221. EXPECT_EQ(4U, req.body.size());
  6222. EXPECT_EQ("application/octet-stream",
  6223. req.get_header_value("Content-Type"));
  6224. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6225. res.set_content(req.body, "application/octet-stream");
  6226. })
  6227. .Get("/issue1772",
  6228. [&](const Request & /*req*/, Response &res) {
  6229. res.status = 401;
  6230. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6231. })
  6232. .Delete("/issue609",
  6233. [](const httplib::Request &, httplib::Response &res,
  6234. const httplib::ContentReader &) {
  6235. res.set_content("ok", "text/plain");
  6236. })
  6237. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6238. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6239. .Get("/compress",
  6240. [&](const Request & /*req*/, Response &res) {
  6241. res.set_content(
  6242. "12345678901234567890123456789012345678901234567890123456789"
  6243. "01234567890123456789012345678901234567890",
  6244. "text/plain");
  6245. })
  6246. .Get("/compress-with-charset",
  6247. [&](const Request & /*req*/, Response &res) {
  6248. res.set_content(
  6249. "12345678901234567890123456789012345678901234567890123456789"
  6250. "01234567890123456789012345678901234567890",
  6251. "application/json; charset=utf-8");
  6252. })
  6253. .Get("/nocompress",
  6254. [&](const Request & /*req*/, Response &res) {
  6255. res.set_content(
  6256. "12345678901234567890123456789012345678901234567890123456789"
  6257. "01234567890123456789012345678901234567890",
  6258. "application/octet-stream");
  6259. })
  6260. .Post("/compress-multipart",
  6261. [&](const Request &req, Response & /*res*/) {
  6262. EXPECT_EQ(2u, req.form.fields.size());
  6263. ASSERT_TRUE(!req.form.has_field("???"));
  6264. {
  6265. const auto &text = req.form.get_field("key1");
  6266. EXPECT_EQ("test", text);
  6267. }
  6268. {
  6269. const auto &text = req.form.get_field("key2");
  6270. EXPECT_EQ("--abcdefg123", text);
  6271. }
  6272. })
  6273. #endif
  6274. ;
  6275. persons_["john"] = "programmer";
  6276. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6277. svr_.wait_until_ready();
  6278. }
  6279. virtual void TearDown() {
  6280. svr_.stop();
  6281. if (!request_threads_.empty()) {
  6282. std::this_thread::sleep_for(std::chrono::seconds(1));
  6283. for (auto &t : request_threads_) {
  6284. t.join();
  6285. }
  6286. }
  6287. t_.join();
  6288. }
  6289. map<string, string> persons_;
  6290. #ifdef CPPHTTPLIB_SSL_ENABLED
  6291. SSLClient cli_;
  6292. SSLServer svr_;
  6293. #else
  6294. Client cli_;
  6295. Server svr_;
  6296. #endif
  6297. thread t_;
  6298. std::vector<thread> request_threads_;
  6299. };
  6300. TEST_F(ServerTest, GetMethod200) {
  6301. auto res = cli_.Get("/hi");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ("HTTP/1.1", res->version);
  6304. EXPECT_EQ(StatusCode::OK_200, res->status);
  6305. EXPECT_EQ("OK", res->reason);
  6306. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6307. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6308. EXPECT_EQ("Hello World!", res->body);
  6309. }
  6310. TEST_F(ServerTest, GetEmptyFile) {
  6311. auto res = cli_.Get("/empty_file");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6316. EXPECT_EQ("", res->body);
  6317. }
  6318. TEST_F(ServerTest, GetFileContent) {
  6319. auto res = cli_.Get("/file_content");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6323. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6324. EXPECT_EQ("test.html", res->body);
  6325. }
  6326. TEST_F(ServerTest, GetFileContentWithRange) {
  6327. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6330. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6331. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6332. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6333. EXPECT_EQ("est", res->body);
  6334. }
  6335. TEST_F(ServerTest, GetFileContentWithContentType) {
  6336. auto res = cli_.Get("/file_content_with_content_type");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6340. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6341. EXPECT_EQ("file\n", res->body);
  6342. }
  6343. TEST_F(ServerTest, GetInvalidFileContent) {
  6344. auto res = cli_.Get("/invalid_file_content");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6347. }
  6348. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6349. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ("HTTP/1.1", res->version);
  6352. EXPECT_EQ(StatusCode::OK_200, res->status);
  6353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6354. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6355. EXPECT_EQ("Hello World!", res->body);
  6356. }
  6357. TEST_F(ServerTest, GetMethod302) {
  6358. auto res = cli_.Get("/");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. EXPECT_EQ(StatusCode::Found_302, res->status);
  6361. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6362. }
  6363. TEST_F(ServerTest, GetMethod302Redirect) {
  6364. cli_.set_follow_location(true);
  6365. auto res = cli_.Get("/");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::OK_200, res->status);
  6368. EXPECT_EQ("Hello World!", res->body);
  6369. EXPECT_EQ("/hi", res->location);
  6370. }
  6371. TEST_F(ServerTest, GetMethod404) {
  6372. auto res = cli_.Get("/invalid");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6375. }
  6376. TEST_F(ServerTest, HeadMethod200) {
  6377. auto res = cli_.Head("/hi");
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6381. EXPECT_TRUE(res->body.empty());
  6382. }
  6383. TEST_F(ServerTest, HeadMethod200Static) {
  6384. auto res = cli_.Head("/mount/dir/index.html");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6388. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6389. EXPECT_TRUE(res->body.empty());
  6390. }
  6391. TEST_F(ServerTest, HeadMethod404) {
  6392. auto res = cli_.Head("/invalid");
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6395. EXPECT_TRUE(res->body.empty());
  6396. }
  6397. TEST_F(ServerTest, GetMethodPersonJohn) {
  6398. auto res = cli_.Get("/person/john");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6402. EXPECT_EQ("programmer", res->body);
  6403. }
  6404. TEST_F(ServerTest, PostMethod1) {
  6405. auto res = cli_.Get("/person/john1");
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6408. res = cli_.Post("/person", "name=john1&note=coder",
  6409. "application/x-www-form-urlencoded");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. res = cli_.Get("/person/john1");
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. ASSERT_EQ(StatusCode::OK_200, res->status);
  6415. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6416. ASSERT_EQ("coder", res->body);
  6417. }
  6418. TEST_F(ServerTest, PostMethod2) {
  6419. auto res = cli_.Get("/person/john2");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6422. Params params;
  6423. params.emplace("name", "john2");
  6424. params.emplace("note", "coder");
  6425. res = cli_.Post("/person", params);
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. ASSERT_EQ(StatusCode::OK_200, res->status);
  6428. res = cli_.Get("/person/john2");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. ASSERT_EQ(StatusCode::OK_200, res->status);
  6431. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6432. ASSERT_EQ("coder", res->body);
  6433. }
  6434. TEST_F(ServerTest, PutMethod3) {
  6435. auto res = cli_.Get("/person/john3");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6438. Params params;
  6439. params.emplace("name", "john3");
  6440. params.emplace("note", "coder");
  6441. res = cli_.Put("/person", params);
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. ASSERT_EQ(StatusCode::OK_200, res->status);
  6444. res = cli_.Get("/person/john3");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. ASSERT_EQ(StatusCode::OK_200, res->status);
  6447. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6448. ASSERT_EQ("coder", res->body);
  6449. }
  6450. TEST_F(ServerTest, DeleteMethod1) {
  6451. auto res = cli_.Get("/person/john4");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6454. Params params;
  6455. params.emplace("name", "john4");
  6456. params.emplace("note", "coder");
  6457. res = cli_.Post("/person", params);
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. ASSERT_EQ(StatusCode::OK_200, res->status);
  6460. res = cli_.Get("/person/john4");
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. ASSERT_EQ(StatusCode::OK_200, res->status);
  6463. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6464. ASSERT_EQ("coder", res->body);
  6465. Params delete_params;
  6466. delete_params.emplace("name", "john4");
  6467. res = cli_.Delete("/person", delete_params);
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. ASSERT_EQ(StatusCode::OK_200, res->status);
  6470. ASSERT_EQ("DELETED", res->body);
  6471. res = cli_.Get("/person/john4");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6474. }
  6475. TEST_F(ServerTest, DeleteMethod2) {
  6476. auto res = cli_.Get("/person/john5");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6479. Params params;
  6480. params.emplace("name", "john5");
  6481. params.emplace("note", "developer");
  6482. res = cli_.Post("/person", params);
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. ASSERT_EQ(StatusCode::OK_200, res->status);
  6485. res = cli_.Get("/person/john5");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6489. ASSERT_EQ("developer", res->body);
  6490. Params delete_params;
  6491. delete_params.emplace("name", "john5");
  6492. Headers headers;
  6493. headers.emplace("Custom-Header", "test-value");
  6494. res = cli_.Delete("/person", headers, delete_params);
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. ASSERT_EQ(StatusCode::OK_200, res->status);
  6497. ASSERT_EQ("DELETED", res->body);
  6498. res = cli_.Get("/person/john5");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6501. }
  6502. TEST_F(ServerTest, DeleteMethod3) {
  6503. auto res = cli_.Get("/person/john6");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6506. Params params;
  6507. params.emplace("name", "john6");
  6508. params.emplace("note", "tester");
  6509. res = cli_.Post("/person", params);
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. ASSERT_EQ(StatusCode::OK_200, res->status);
  6512. res = cli_.Get("/person/john6");
  6513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6514. ASSERT_EQ(StatusCode::OK_200, res->status);
  6515. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6516. ASSERT_EQ("tester", res->body);
  6517. Params delete_params;
  6518. delete_params.emplace("name", "john6");
  6519. Headers headers;
  6520. headers.emplace("Custom-Header", "test-value");
  6521. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. ASSERT_EQ(StatusCode::OK_200, res->status);
  6524. ASSERT_EQ("DELETED", res->body);
  6525. res = cli_.Get("/person/john6");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6528. }
  6529. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6530. Params params;
  6531. params.emplace("json", JSON_DATA);
  6532. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::OK_200, res->status);
  6535. ASSERT_EQ(JSON_DATA, res->body);
  6536. }
  6537. TEST_F(ServerTest, PostEmptyContent) {
  6538. auto res = cli_.Post("/empty", "", "text/plain");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. ASSERT_EQ(StatusCode::OK_200, res->status);
  6541. ASSERT_EQ("empty", res->body);
  6542. }
  6543. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6544. auto res = cli_.Post("/empty-no-content-type");
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. ASSERT_EQ(StatusCode::OK_200, res->status);
  6547. ASSERT_EQ("empty-no-content-type", res->body);
  6548. }
  6549. TEST_F(ServerTest, PostPathOnly) {
  6550. auto res = cli_.Post("/path-only");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. ASSERT_EQ(StatusCode::OK_200, res->status);
  6553. ASSERT_EQ("path-only", res->body);
  6554. }
  6555. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6556. auto res = cli_.Post("/path-headers-only",
  6557. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. ASSERT_EQ(StatusCode::OK_200, res->status);
  6560. ASSERT_EQ("path-headers-only", res->body);
  6561. }
  6562. TEST_F(ServerTest, PostLarge) {
  6563. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6565. ASSERT_EQ(StatusCode::OK_200, res->status);
  6566. EXPECT_EQ(LARGE_DATA, res->body);
  6567. }
  6568. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6569. auto res = cli_.Put("/empty-no-content-type");
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. ASSERT_EQ(StatusCode::OK_200, res->status);
  6572. ASSERT_EQ("empty-no-content-type", res->body);
  6573. }
  6574. TEST_F(ServerTest, GetMethodDir) {
  6575. auto res = cli_.Get("/dir/");
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6579. auto body = R"(<html>
  6580. <head>
  6581. </head>
  6582. <body>
  6583. <a href="/dir/test.html">Test</a>
  6584. <a href="/hi">hi</a>
  6585. </body>
  6586. </html>
  6587. )";
  6588. EXPECT_EQ(body, res->body);
  6589. }
  6590. TEST_F(ServerTest, GetMethodDirTest) {
  6591. auto res = cli_.Get("/dir/test.html");
  6592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6593. EXPECT_EQ(StatusCode::OK_200, res->status);
  6594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6595. EXPECT_EQ("test.html", res->body);
  6596. }
  6597. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6598. auto res = cli_.Get("/dir/../dir/test.html");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6601. }
  6602. TEST_F(ServerTest, GetMethodInvalidPath) {
  6603. auto res = cli_.Get("/dir/../test.html");
  6604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6606. }
  6607. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6608. auto res = cli_.Get("/../www/dir/test.html");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6611. }
  6612. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6613. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6616. }
  6617. TEST_F(ServerTest, GetMethodDirMountTest) {
  6618. auto res = cli_.Get("/mount/dir/test.html");
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6622. EXPECT_EQ("test.html", res->body);
  6623. }
  6624. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6625. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6628. }
  6629. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6630. auto res = cli_.Get("/mount/dir/../test.html");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6633. }
  6634. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6635. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6638. }
  6639. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6640. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6643. }
  6644. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6645. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6648. }
  6649. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6650. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6653. }
  6654. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6655. auto res = cli_.Get("/mount/dir");
  6656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6657. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6658. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6659. }
  6660. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6661. auto res = cli_.Get("//dir");
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6664. EXPECT_FALSE(res->has_header("Location"));
  6665. }
  6666. TEST_F(ServerTest, PostMethod303) {
  6667. auto res = cli_.Post("/1", "body", "text/plain");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6670. EXPECT_EQ("/2", res->get_header_value("Location"));
  6671. }
  6672. TEST_F(ServerTest, PostMethod303Redirect) {
  6673. cli_.set_follow_location(true);
  6674. auto res = cli_.Post("/1", "body", "text/plain");
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. EXPECT_EQ("redirected.", res->body);
  6678. EXPECT_EQ("/2", res->location);
  6679. }
  6680. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6681. auto res = cli_.Get("/dir/test.abcde");
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6685. EXPECT_EQ("abcde", res->body);
  6686. }
  6687. TEST_F(ServerTest, StaticFileRange) {
  6688. auto res =
  6689. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6692. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6693. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6694. EXPECT_EQ(true, res->has_header("Content-Range"));
  6695. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6696. EXPECT_EQ(std::string("cd"), res->body);
  6697. }
  6698. TEST_F(ServerTest, StaticFileRanges) {
  6699. auto res = cli_.Get("/dir/test.abcde",
  6700. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6703. EXPECT_TRUE(
  6704. res->get_header_value("Content-Type")
  6705. .find(
  6706. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6707. 0);
  6708. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6709. }
  6710. TEST_F(ServerTest, StaticFileRangeHead) {
  6711. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6714. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6715. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6716. EXPECT_EQ(true, res->has_header("Content-Range"));
  6717. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6718. }
  6719. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6720. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6724. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6725. EXPECT_EQ(true, res->has_header("Content-Range"));
  6726. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6727. res->get_header_value("Content-Range"));
  6728. EXPECT_EQ("LAST\n", res->body);
  6729. }
  6730. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6731. auto res =
  6732. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6736. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6737. EXPECT_EQ(true, res->has_header("Content-Range"));
  6738. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6739. }
  6740. TEST_F(ServerTest, StaticFileBigFile) {
  6741. auto res = cli_.Get("/dir/1MB.txt");
  6742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6743. EXPECT_EQ(StatusCode::OK_200, res->status);
  6744. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6745. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6746. }
  6747. TEST_F(ServerTest, InvalidBaseDirMount) {
  6748. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6749. }
  6750. TEST_F(ServerTest, Binary) {
  6751. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6752. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6753. "application/octet-stream");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. ASSERT_EQ(StatusCode::OK_200, res->status);
  6756. ASSERT_EQ(4U, res->body.size());
  6757. res = cli_.Put("/binary", binary.data(), binary.size(),
  6758. "application/octet-stream");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. ASSERT_EQ(StatusCode::OK_200, res->status);
  6761. ASSERT_EQ(4U, res->body.size());
  6762. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6763. "application/octet-stream");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. ASSERT_EQ(StatusCode::OK_200, res->status);
  6766. ASSERT_EQ(4U, res->body.size());
  6767. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6768. "application/octet-stream");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. ASSERT_EQ(StatusCode::OK_200, res->status);
  6771. ASSERT_EQ(4U, res->body.size());
  6772. }
  6773. TEST_F(ServerTest, BinaryString) {
  6774. auto binary = std::string("\x00\x01\x02\x03", 4);
  6775. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. ASSERT_EQ(StatusCode::OK_200, res->status);
  6778. ASSERT_EQ(4U, res->body.size());
  6779. res = cli_.Put("/binary", binary, "application/octet-stream");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. ASSERT_EQ(StatusCode::OK_200, res->status);
  6782. ASSERT_EQ(4U, res->body.size());
  6783. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. ASSERT_EQ(StatusCode::OK_200, res->status);
  6786. ASSERT_EQ(4U, res->body.size());
  6787. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. ASSERT_EQ(StatusCode::OK_200, res->status);
  6790. ASSERT_EQ(4U, res->body.size());
  6791. }
  6792. TEST_F(ServerTest, EmptyRequest) {
  6793. auto res = cli_.Get("");
  6794. ASSERT_TRUE(!res);
  6795. EXPECT_EQ(Error::Connection, res.error());
  6796. }
  6797. TEST_F(ServerTest, LongRequest) {
  6798. std::string request;
  6799. for (size_t i = 0; i < 545; i++) {
  6800. request += "/TooLongRequest";
  6801. }
  6802. request += "OK";
  6803. auto res = cli_.Get(request.c_str());
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6806. }
  6807. TEST_F(ServerTest, TooLongRequest) {
  6808. std::string request;
  6809. for (size_t i = 0; i < 546; i++) {
  6810. request += "/TooLongRequest";
  6811. }
  6812. request += "_NG";
  6813. auto start = std::chrono::high_resolution_clock::now();
  6814. cli_.set_keep_alive(true);
  6815. auto res = cli_.Get(request.c_str());
  6816. auto end = std::chrono::high_resolution_clock::now();
  6817. auto elapsed =
  6818. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6819. .count();
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6822. EXPECT_LE(elapsed, 1000);
  6823. EXPECT_EQ("close", res->get_header_value("Connection"));
  6824. EXPECT_FALSE(cli_.is_socket_open());
  6825. }
  6826. TEST_F(ServerTest, AlmostTooLongRequest) {
  6827. // test for #2046 - URI length check shouldn't include other content on req
  6828. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6829. // leading /, space, HTTP/1.1)
  6830. std::string request =
  6831. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6832. auto res = cli_.Get(request.c_str());
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6835. }
  6836. TEST_F(ServerTest, LongHeader) {
  6837. Request req;
  6838. req.method = "GET";
  6839. req.path = "/hi";
  6840. std::string host_and_port;
  6841. host_and_port += HOST;
  6842. host_and_port += ":";
  6843. host_and_port += std::to_string(PORT);
  6844. req.headers.emplace("Host", host_and_port.c_str());
  6845. req.headers.emplace("Accept", "*/*");
  6846. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6847. req.headers.emplace(
  6848. "Header-Name",
  6849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6877. "@@@@@@@@@@@@@@@@");
  6878. auto res = std::make_shared<Response>();
  6879. auto error = Error::Success;
  6880. auto ret = cli_.send(req, *res, error);
  6881. ASSERT_TRUE(ret);
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(ServerTest, LongQueryValue) {
  6885. auto start = std::chrono::high_resolution_clock::now();
  6886. cli_.set_keep_alive(true);
  6887. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6888. auto end = std::chrono::high_resolution_clock::now();
  6889. auto elapsed =
  6890. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6891. .count();
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6894. EXPECT_LE(elapsed, 1000);
  6895. EXPECT_EQ("close", res->get_header_value("Connection"));
  6896. EXPECT_FALSE(cli_.is_socket_open());
  6897. }
  6898. TEST_F(ServerTest, TooLongQueryValue) {
  6899. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6900. ASSERT_FALSE(res);
  6901. EXPECT_EQ(Error::Read, res.error());
  6902. }
  6903. TEST_F(ServerTest, TooLongHeader) {
  6904. Request req;
  6905. req.method = "GET";
  6906. req.path = "/hi";
  6907. std::string host_and_port;
  6908. host_and_port += HOST;
  6909. host_and_port += ":";
  6910. host_and_port += std::to_string(PORT);
  6911. req.headers.emplace("Host", host_and_port.c_str());
  6912. req.headers.emplace("Accept", "*/*");
  6913. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6914. req.headers.emplace(
  6915. "Header-Name",
  6916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6944. "@@@@@@@@@@@@@@@@@");
  6945. auto res = std::make_shared<Response>();
  6946. auto error = Error::Success;
  6947. auto ret = cli_.send(req, *res, error);
  6948. ASSERT_TRUE(ret);
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. TEST_F(ServerTest, HeaderCountAtLimit) {
  6952. // Test with headers just under the 100 limit
  6953. httplib::Headers headers;
  6954. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6955. // This should keep us just under the 100 header limit
  6956. for (int i = 0; i < 95; i++) {
  6957. std::string name = "X-Test-Header-" + std::to_string(i);
  6958. std::string value = "value" + std::to_string(i);
  6959. headers.emplace(name, value);
  6960. }
  6961. // This should work fine as we're under the limit
  6962. auto res = cli_.Get("/hi", headers);
  6963. EXPECT_TRUE(res);
  6964. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6965. }
  6966. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6967. // Test with many headers to exceed the 100 limit
  6968. httplib::Headers headers;
  6969. // Add 150 headers to definitely exceed the 100 limit
  6970. for (int i = 0; i < 150; i++) {
  6971. std::string name = "X-Test-Header-" + std::to_string(i);
  6972. std::string value = "value" + std::to_string(i);
  6973. headers.emplace(name, value);
  6974. }
  6975. // This should fail due to exceeding header count limit
  6976. cli_.set_keep_alive(true);
  6977. auto res = cli_.Get("/hi", headers);
  6978. // The server should respond with 400 Bad Request
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6981. EXPECT_EQ("close", res->get_header_value("Connection"));
  6982. EXPECT_FALSE(cli_.is_socket_open());
  6983. }
  6984. TEST_F(ServerTest, PercentEncoding) {
  6985. auto res = cli_.Get("/e%6edwith%");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::OK_200, res->status);
  6988. }
  6989. TEST_F(ServerTest, PercentEncodingUnicode) {
  6990. auto res = cli_.Get("/e%u006edwith%");
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. }
  6994. TEST_F(ServerTest, InvalidPercentEncoding) {
  6995. auto res = cli_.Get("/%endwith%");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6998. }
  6999. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7000. auto res = cli_.Get("/%uendwith%");
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7003. }
  7004. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7005. auto res = cli_.Get("/hello?aaa=bbb%");
  7006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7007. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7008. }
  7009. TEST_F(ServerTest, PlusSignEncoding) {
  7010. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ("a +b", res->body);
  7014. }
  7015. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7016. // This test simulates a potential DoS attack using many headers
  7017. // to verify our security fix prevents memory exhaustion
  7018. httplib::Headers attack_headers;
  7019. // Attempt to add many headers like an attacker would (200 headers to far
  7020. // exceed limit)
  7021. for (int i = 0; i < 200; i++) {
  7022. std::string name = "X-Attack-Header-" + std::to_string(i);
  7023. std::string value = "attack_payload_" + std::to_string(i);
  7024. attack_headers.emplace(name, value);
  7025. }
  7026. // Try to POST with excessive headers
  7027. cli_.set_keep_alive(true);
  7028. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7029. // Should either fail or return 400 Bad Request due to security limit
  7030. if (res) {
  7031. // If we get a response, it should be 400 Bad Request
  7032. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7033. EXPECT_EQ("close", res->get_header_value("Connection"));
  7034. }
  7035. EXPECT_FALSE(cli_.is_socket_open());
  7036. }
  7037. TEST_F(ServerTest, MultipartFormData) {
  7038. UploadFormDataItems items = {
  7039. {"text1", "text default", "", ""},
  7040. {"text2", "aωb", "", ""},
  7041. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7042. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7043. {"file3", "", "", "application/octet-stream"},
  7044. {"file4", "", "", " application/json tmp-string "}};
  7045. auto res = cli_.Post("/multipart", items);
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::OK_200, res->status);
  7048. }
  7049. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7050. UploadFormDataItems items = {
  7051. {"text", "default text", "", ""},
  7052. {"multi_text1", "aaaaa", "", ""},
  7053. {"multi_text1", "bbbbb", "", ""},
  7054. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7055. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7056. "application/json"},
  7057. };
  7058. auto res = cli_.Post("/multipart/multi_file_values", items);
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7063. auto res = cli_.Get("/hi");
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::OK_200, res->status);
  7066. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7067. EXPECT_EQ("Hello World!", res->body);
  7068. }
  7069. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7070. Request req;
  7071. req.method = "POST";
  7072. req.path = "/chunked";
  7073. std::string host_and_port;
  7074. host_and_port += HOST;
  7075. host_and_port += ":";
  7076. host_and_port += std::to_string(PORT);
  7077. req.headers.emplace("Host", host_and_port.c_str());
  7078. req.headers.emplace("Accept", "*/*");
  7079. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7080. req.headers.emplace("Content-Type", "text/plain");
  7081. req.headers.emplace("Content-Length", "0");
  7082. req.headers.emplace(
  7083. "Transfer-Encoding",
  7084. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7085. // Client does not chunk, so make a chunked body manually.
  7086. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7087. auto res = std::make_shared<Response>();
  7088. auto error = Error::Success;
  7089. auto ret = cli_.send(req, *res, error);
  7090. ASSERT_TRUE(ret);
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. }
  7093. template <typename ClientT>
  7094. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7095. int expected_status) {
  7096. Request req;
  7097. req.method = "POST";
  7098. req.path = "/chunked";
  7099. std::string host_and_port;
  7100. host_and_port += HOST;
  7101. host_and_port += ":";
  7102. host_and_port += std::to_string(PORT);
  7103. req.headers.emplace("Host", host_and_port.c_str());
  7104. req.headers.emplace("Content-Length", "0");
  7105. req.headers.emplace("Transfer-Encoding", "chunked");
  7106. req.body = body;
  7107. auto res = std::make_shared<Response>();
  7108. auto error = Error::Success;
  7109. ASSERT_TRUE(cli.send(req, *res, error));
  7110. EXPECT_EQ(expected_status, res->status);
  7111. }
  7112. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7113. // rather than treat them as valid lengths.
  7114. template <typename ClientT>
  7115. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7116. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7117. }
  7118. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7119. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7120. }
  7121. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7122. expect_chunked_body_rejected(
  7123. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7124. }
  7125. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7126. // chunk-size line carries no CR, LF or other control character ahead of its
  7127. // terminator. Such a line must be refused rather than read as extension text.
  7128. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7129. expect_chunked_body_rejected(
  7130. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7131. }
  7132. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7133. expect_chunked_body_rejected(
  7134. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7135. }
  7136. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7137. expect_chunked_body_rejected(
  7138. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7139. }
  7140. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7141. // The literal stays split: a hex escape consumes every hex digit that
  7142. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7143. expect_chunked_body_rejected(
  7144. cli_, "4;a\x01"
  7145. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7146. }
  7147. // The bytes around chunk data are no payload, so they cannot ride on the
  7148. // payload limit
  7149. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7150. // Small enough that the whole request is sent before the server turns it
  7151. // down, yet past the limit by the last chunks
  7152. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7153. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7154. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7155. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7156. SCOPED_TRACE(size_line.substr(0, 2));
  7157. std::string body;
  7158. for (auto c : std::string("dechunked post body")) {
  7159. body += size_line + "\r\n" + c + "\r\n";
  7160. }
  7161. body += "0\r\n\r\n";
  7162. expect_chunked_body_rejected(cli_, body.c_str());
  7163. }
  7164. }
  7165. TEST_F(ServerTest, AcceptsChunkExtension) {
  7166. expect_chunked_body_status(cli_,
  7167. "4;name=value\r\ndech\r\n"
  7168. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7169. "0;last\r\n\r\n",
  7170. StatusCode::OK_200);
  7171. }
  7172. TEST_F(ServerTest, GetStreamed2) {
  7173. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7176. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7177. EXPECT_EQ(true, res->has_header("Content-Range"));
  7178. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7179. EXPECT_EQ(std::string("ab"), res->body);
  7180. }
  7181. TEST_F(ServerTest, GetStreamed) {
  7182. auto res = cli_.Get("/streamed");
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7186. EXPECT_EQ(std::string("aaabbb"), res->body);
  7187. }
  7188. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7189. auto res = cli_.Get("/streamed-without-length",
  7190. Headers{make_range_header({{0, -1}})});
  7191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7192. EXPECT_EQ(StatusCode::OK_200, res->status);
  7193. EXPECT_EQ(false, res->has_header("Content-Length"));
  7194. EXPECT_EQ(false, res->has_header("Content-Range"));
  7195. EXPECT_EQ(std::string("abcdefg"), res->body);
  7196. }
  7197. TEST_F(ServerTest, GetStreamedWithRange1) {
  7198. auto res =
  7199. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7202. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7203. EXPECT_EQ(true, res->has_header("Content-Range"));
  7204. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7205. EXPECT_EQ(std::string("def"), res->body);
  7206. }
  7207. TEST_F(ServerTest, GetStreamedWithRange2) {
  7208. auto res =
  7209. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7212. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7213. EXPECT_EQ(true, res->has_header("Content-Range"));
  7214. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7215. EXPECT_EQ(std::string("bcdefg"), res->body);
  7216. }
  7217. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7218. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7221. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7222. EXPECT_EQ(true, res->has_header("Content-Range"));
  7223. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7224. EXPECT_EQ(std::string("efg"), res->body);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7227. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7228. // the entire representation.
  7229. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7230. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7233. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7234. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7235. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7236. }
  7237. }
  7238. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7239. auto res =
  7240. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7243. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7244. EXPECT_EQ(false, res->has_header("Content-Range"));
  7245. EXPECT_EQ(0U, res->body.size());
  7246. }
  7247. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7248. // Only a 206 is served as a partial representation. Under any other status
  7249. // `apply_ranges()` reported the full content length, so the body must match
  7250. // that header, and the content provider must never be asked for an offset
  7251. // outside the representation.
  7252. auto check = [&](int status, const char *range) {
  7253. auto path =
  7254. std::string("/streamed-with-range?status=") + std::to_string(status);
  7255. auto ctx = path + " Range: " + range;
  7256. auto res = cli_.Get(path, Headers{{"Range", range}});
  7257. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7258. EXPECT_EQ(status, res->status) << ctx;
  7259. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7261. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7262. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7263. };
  7264. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7265. check(403, "bytes=3-5");
  7266. // The offset is far past the representation.
  7267. check(403, "bytes=100000-100200");
  7268. // `first_pos` is still -1 here, and the bounds asserts in
  7269. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7270. check(403, "bytes=-3");
  7271. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7272. // multipart branch would have written one that is empty.
  7273. check(403, "bytes=1-2, 4-5");
  7274. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7275. // covers the whole representation.
  7276. check(200, "bytes=3-5");
  7277. check(200, "bytes=1-2, 4-5");
  7278. }
  7279. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7280. auto res =
  7281. cli_.Get("/streamed-with-range",
  7282. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7283. "92233720368547758079223372036854775807"}});
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7287. EXPECT_EQ(false, res->has_header("Content-Range"));
  7288. EXPECT_EQ(0U, res->body.size());
  7289. }
  7290. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7291. auto res = cli_.Get(
  7292. "/with-range",
  7293. Headers{{"Range",
  7294. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7295. {"Accept-Encoding", ""}});
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7298. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7299. EXPECT_EQ(true, res->has_header("Content-Range"));
  7300. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7301. EXPECT_EQ(std::string("abcdefg"), res->body);
  7302. }
  7303. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7304. auto res = cli_.Get("/with-range", Headers{
  7305. {"Range", "bytes=0-"},
  7306. {"Accept-Encoding", ""},
  7307. });
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7310. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7311. EXPECT_EQ(true, res->has_header("Content-Range"));
  7312. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7313. EXPECT_EQ(std::string("abcdefg"), res->body);
  7314. }
  7315. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7316. auto res = cli_.Get("/streamed-with-range",
  7317. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(false, res->has_header("Content-Range"));
  7322. EXPECT_EQ(267U, res->body.size());
  7323. // Check that both range contents are present
  7324. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7325. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7326. // Check that Content-Range headers are present for both ranges
  7327. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7328. std::string::npos);
  7329. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7330. std::string::npos);
  7331. }
  7332. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7333. Ranges ranges;
  7334. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7335. ranges.emplace_back(0, -1);
  7336. }
  7337. auto res = cli_.Get("/streamed-with-range?error",
  7338. Headers{{make_range_header(ranges)}});
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7341. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7342. EXPECT_EQ(false, res->has_header("Content-Range"));
  7343. EXPECT_EQ(0U, res->body.size());
  7344. }
  7345. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7346. auto res = cli_.Get("/streamed-with-range",
  7347. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7350. EXPECT_EQ(5U, res->body.size());
  7351. // Check that overlapping ranges are coalesced into a single range
  7352. EXPECT_EQ("bcdef", res->body);
  7353. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7354. // Should be single range, not multipart
  7355. EXPECT_TRUE(res->has_header("Content-Range"));
  7356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7357. }
  7358. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7359. auto res = cli_.Get("/streamed-with-range",
  7360. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7363. EXPECT_EQ(268U, res->body.size());
  7364. // Check that both range contents are present
  7365. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7366. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7367. // Check that Content-Range headers are present for both ranges
  7368. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7369. std::string::npos);
  7370. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7371. std::string::npos);
  7372. }
  7373. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7374. auto res = cli_.Get("/streamed-with-range",
  7375. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7378. EXPECT_EQ(269U, res->body.size());
  7379. // Check that both duplicate range contents are present
  7380. size_t first_abc = res->body.find("abc\r\n");
  7381. EXPECT_TRUE(first_abc != std::string::npos);
  7382. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7383. EXPECT_TRUE(second_abc != std::string::npos);
  7384. // Check that Content-Range headers are present for both ranges
  7385. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7386. EXPECT_TRUE(first_range != std::string::npos);
  7387. size_t second_range =
  7388. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7389. EXPECT_TRUE(second_range != std::string::npos);
  7390. }
  7391. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7392. auto res =
  7393. cli_.Get("/streamed-with-range?error",
  7394. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7397. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7398. EXPECT_EQ(false, res->has_header("Content-Range"));
  7399. EXPECT_EQ(0U, res->body.size());
  7400. }
  7401. TEST_F(ServerTest, GetStreamedEndless) {
  7402. uint64_t offset = 0;
  7403. auto res = cli_.Get("/streamed-cancel",
  7404. [&](const char * /*data*/, uint64_t data_length) {
  7405. if (offset < 100) {
  7406. offset += data_length;
  7407. return true;
  7408. }
  7409. return false;
  7410. });
  7411. ASSERT_TRUE(!res);
  7412. EXPECT_EQ(Error::Canceled, res.error());
  7413. }
  7414. TEST_F(ServerTest, ClientStop) {
  7415. std::atomic_size_t count{4};
  7416. std::vector<std::thread> threads;
  7417. for (auto i = count.load(); i != 0; --i) {
  7418. threads.emplace_back([&]() {
  7419. auto res = cli_.Get("/streamed-cancel",
  7420. [&](const char *, uint64_t) { return true; });
  7421. --count;
  7422. ASSERT_TRUE(!res);
  7423. EXPECT_TRUE(res.error() == Error::Canceled ||
  7424. res.error() == Error::Read || res.error() == Error::Write);
  7425. });
  7426. }
  7427. std::this_thread::sleep_for(std::chrono::seconds(2));
  7428. while (count != 0) {
  7429. cli_.stop();
  7430. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7431. }
  7432. for (auto &t : threads) {
  7433. t.join();
  7434. }
  7435. }
  7436. TEST_F(ServerTest, GetWithRange1) {
  7437. auto res = cli_.Get("/with-range", Headers{
  7438. make_range_header({{3, 5}}),
  7439. {"Accept-Encoding", ""},
  7440. });
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7443. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7444. EXPECT_EQ(true, res->has_header("Content-Range"));
  7445. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7446. EXPECT_EQ(std::string("def"), res->body);
  7447. }
  7448. TEST_F(ServerTest, GetWithRange2) {
  7449. auto res = cli_.Get("/with-range", Headers{
  7450. make_range_header({{1, -1}}),
  7451. {"Accept-Encoding", ""},
  7452. });
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7455. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7456. EXPECT_EQ(true, res->has_header("Content-Range"));
  7457. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7458. EXPECT_EQ(std::string("bcdefg"), res->body);
  7459. }
  7460. TEST_F(ServerTest, GetWithRange3) {
  7461. auto res = cli_.Get("/with-range", Headers{
  7462. make_range_header({{0, 0}}),
  7463. {"Accept-Encoding", ""},
  7464. });
  7465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7467. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7468. EXPECT_EQ(true, res->has_header("Content-Range"));
  7469. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7470. EXPECT_EQ(std::string("a"), res->body);
  7471. }
  7472. TEST_F(ServerTest, GetWithRange4) {
  7473. auto res = cli_.Get("/with-range", Headers{
  7474. make_range_header({{-1, 2}}),
  7475. {"Accept-Encoding", ""},
  7476. });
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7479. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7480. EXPECT_EQ(true, res->has_header("Content-Range"));
  7481. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7482. EXPECT_EQ(std::string("fg"), res->body);
  7483. }
  7484. TEST_F(ServerTest, GetWithRange5) {
  7485. auto res = cli_.Get("/with-range", Headers{
  7486. make_range_header({{0, 5}}),
  7487. {"Accept-Encoding", ""},
  7488. });
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7491. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7492. EXPECT_EQ(true, res->has_header("Content-Range"));
  7493. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7494. EXPECT_EQ(std::string("abcdef"), res->body);
  7495. }
  7496. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7497. auto res =
  7498. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7500. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7501. }
  7502. TEST_F(ServerTest, GetWithRangeMultipart) {
  7503. auto res =
  7504. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7506. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7507. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7508. EXPECT_EQ(false, res->has_header("Content-Range"));
  7509. EXPECT_EQ(267U, res->body.size());
  7510. }
  7511. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7512. auto res = cli_.Get("/with-range",
  7513. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7516. }
  7517. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7518. auto res = cli_.Get("/with-range-customized-response",
  7519. Headers{{make_range_header({{1, 2}})}});
  7520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7521. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7522. EXPECT_EQ(true, res->has_header("Content-Length"));
  7523. EXPECT_EQ(false, res->has_header("Content-Range"));
  7524. EXPECT_EQ(JSON_DATA, res->body);
  7525. }
  7526. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7527. auto res = cli_.Get("/with-range-customized-response",
  7528. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7531. EXPECT_EQ(true, res->has_header("Content-Length"));
  7532. EXPECT_EQ(false, res->has_header("Content-Range"));
  7533. EXPECT_EQ(JSON_DATA, res->body);
  7534. }
  7535. TEST_F(ServerTest, Issue1772) {
  7536. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7539. }
  7540. TEST_F(ServerTest, Issue609) {
  7541. auto res = cli_.Delete("/issue609");
  7542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7543. EXPECT_EQ(StatusCode::OK_200, res->status);
  7544. EXPECT_EQ(std::string("ok"), res->body);
  7545. }
  7546. TEST_F(ServerTest, GetStreamedChunked) {
  7547. auto res = cli_.Get("/streamed-chunked");
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. EXPECT_EQ(std::string("123456789"), res->body);
  7551. }
  7552. TEST_F(ServerTest, GetStreamedChunked2) {
  7553. auto res = cli_.Get("/streamed-chunked2");
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(StatusCode::OK_200, res->status);
  7556. EXPECT_EQ(std::string("123456789"), res->body);
  7557. }
  7558. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7559. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. EXPECT_EQ(std::string("123456789"), res->body);
  7563. EXPECT_TRUE(res->has_header("Trailer"));
  7564. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7565. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7566. // Trailers are now stored separately from headers (security fix)
  7567. EXPECT_EQ(2U, res->trailers.size());
  7568. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7569. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7570. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7571. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7572. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7573. // Verify trailers are NOT in headers (security verification)
  7574. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7575. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7576. }
  7577. TEST_F(ServerTest, LargeChunkedPost) {
  7578. Request req;
  7579. req.method = "POST";
  7580. req.path = "/large-chunked";
  7581. std::string host_and_port;
  7582. host_and_port += HOST;
  7583. host_and_port += ":";
  7584. host_and_port += std::to_string(PORT);
  7585. req.headers.emplace("Host", host_and_port.c_str());
  7586. req.headers.emplace("Accept", "*/*");
  7587. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7588. req.headers.emplace("Content-Type", "text/plain");
  7589. req.headers.emplace("Content-Length", "0");
  7590. req.headers.emplace("Transfer-Encoding", "chunked");
  7591. std::string long_string(30 * 1024u, 'a');
  7592. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7593. // Attempt to make a large enough post to exceed OS buffers, to test that
  7594. // the server handles short reads if the full chunk data isn't available.
  7595. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7596. auto res = std::make_shared<Response>();
  7597. auto error = Error::Success;
  7598. auto ret = cli_.send(req, *res, error);
  7599. ASSERT_TRUE(ret);
  7600. EXPECT_EQ(StatusCode::OK_200, res->status);
  7601. }
  7602. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7603. auto res = cli_.Get("/remote_addr");
  7604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7607. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7608. }
  7609. TEST_F(ServerTest, GetMethodLocalAddr) {
  7610. auto res = cli_.Get("/local_addr");
  7611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7612. EXPECT_EQ(StatusCode::OK_200, res->status);
  7613. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7614. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7615. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7616. }
  7617. TEST_F(ServerTest, HTTPResponseSplitting) {
  7618. auto res = cli_.Get("/http_response_splitting");
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::OK_200, res->status);
  7621. }
  7622. TEST_F(ServerTest, SlowRequest) {
  7623. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7624. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7625. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7626. }
  7627. #if 0
  7628. TEST_F(ServerTest, SlowPost) {
  7629. char buffer[64 * 1024];
  7630. memset(buffer, 0x42, sizeof(buffer));
  7631. auto res = cli_.Post(
  7632. "/slowpost", 64 * 1024 * 1024,
  7633. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7634. auto ret = sink.write(buffer, sizeof(buffer));
  7635. EXPECT_TRUE(ret);
  7636. return true;
  7637. },
  7638. "text/plain");
  7639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7640. EXPECT_EQ(StatusCode::OK_200, res->status);
  7641. }
  7642. TEST_F(ServerTest, SlowPostFail) {
  7643. char buffer[64 * 1024];
  7644. memset(buffer, 0x42, sizeof(buffer));
  7645. cli_.set_write_timeout(std::chrono::seconds(0));
  7646. auto res = cli_.Post(
  7647. "/slowpost", 64 * 1024 * 1024,
  7648. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7649. sink.write(buffer, sizeof(buffer));
  7650. return true;
  7651. },
  7652. "text/plain");
  7653. ASSERT_TRUE(!res);
  7654. EXPECT_EQ(Error::Write, res.error());
  7655. }
  7656. #endif
  7657. TEST_F(ServerTest, Put) {
  7658. auto res = cli_.Put("/put", "PUT", "text/plain");
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::OK_200, res->status);
  7661. EXPECT_EQ("PUT", res->body);
  7662. }
  7663. TEST_F(ServerTest, PutWithContentProvider) {
  7664. auto res = cli_.Put(
  7665. "/put", 3,
  7666. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7667. sink.os << "PUT";
  7668. return true;
  7669. },
  7670. "text/plain");
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ(StatusCode::OK_200, res->status);
  7673. EXPECT_EQ("PUT", res->body);
  7674. }
  7675. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7676. auto res = cli_.Post(
  7677. "/post", 42,
  7678. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7679. return false;
  7680. },
  7681. "text/plain");
  7682. ASSERT_TRUE(!res);
  7683. EXPECT_EQ(Error::Canceled, res.error());
  7684. }
  7685. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7686. auto res = cli_.Put(
  7687. "/put",
  7688. [](size_t /*offset*/, DataSink &sink) {
  7689. sink.os << "PUT";
  7690. sink.done();
  7691. return true;
  7692. },
  7693. "text/plain");
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. EXPECT_EQ("PUT", res->body);
  7697. }
  7698. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7699. auto res = cli_.Post(
  7700. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7701. "text/plain");
  7702. ASSERT_TRUE(!res);
  7703. EXPECT_EQ(Error::Canceled, res.error());
  7704. }
  7705. TEST_F(ServerTest, PostLoopBack) {
  7706. std::string body;
  7707. auto res = cli_.Post(
  7708. "/post-loopback", 9,
  7709. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7710. EXPECT_EQ(9u, length);
  7711. sink.write("123", 3);
  7712. sink.write("456", 3);
  7713. sink.write("789", 3);
  7714. return true;
  7715. },
  7716. "text/plain",
  7717. [&body](const char *data, size_t data_length) {
  7718. body.append(data, data_length);
  7719. return true;
  7720. });
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ("123456789", body);
  7724. }
  7725. TEST_F(ServerTest, PutLoopBack) {
  7726. std::string body;
  7727. auto res = cli_.Put(
  7728. "/put-loopback", 9,
  7729. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7730. EXPECT_EQ(9u, length);
  7731. sink.write("123", 3);
  7732. sink.write("456", 3);
  7733. sink.write("789", 3);
  7734. return true;
  7735. },
  7736. "text/plain",
  7737. [&body](const char *data, size_t data_length) {
  7738. body.append(data, data_length);
  7739. return true;
  7740. });
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ("123456789", body);
  7744. }
  7745. TEST_F(ServerTest, PatchLoopBack) {
  7746. std::string body;
  7747. auto res = cli_.Patch(
  7748. "/patch-loopback", 9,
  7749. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7750. EXPECT_EQ(9u, length);
  7751. sink.write("123", 3);
  7752. sink.write("456", 3);
  7753. sink.write("789", 3);
  7754. return true;
  7755. },
  7756. "text/plain",
  7757. [&body](const char *data, size_t data_length) {
  7758. body.append(data, data_length);
  7759. return true;
  7760. });
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("123456789", body);
  7764. }
  7765. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7766. std::string body;
  7767. auto res = cli_.Post(
  7768. "/post-loopback",
  7769. [](size_t /*offset*/, DataSink &sink) {
  7770. sink.write("123", 3);
  7771. sink.write("456", 3);
  7772. sink.write("789", 3);
  7773. sink.done();
  7774. return true;
  7775. },
  7776. "text/plain",
  7777. [&body](const char *data, size_t data_length) {
  7778. body.append(data, data_length);
  7779. return true;
  7780. });
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. EXPECT_EQ("123456789", body);
  7784. }
  7785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7786. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7787. cli_.set_compress(true);
  7788. auto res = cli_.Put(
  7789. "/put", 3,
  7790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7791. sink.os << "PUT";
  7792. return true;
  7793. },
  7794. "text/plain");
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. EXPECT_EQ("PUT", res->body);
  7798. }
  7799. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7800. cli_.set_compress(true);
  7801. auto res = cli_.Post(
  7802. "/post", 42,
  7803. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7804. return false;
  7805. },
  7806. "text/plain");
  7807. ASSERT_TRUE(!res);
  7808. EXPECT_EQ(Error::Canceled, res.error());
  7809. }
  7810. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7811. cli_.set_compress(true);
  7812. auto res = cli_.Put(
  7813. "/put",
  7814. [](size_t /*offset*/, DataSink &sink) {
  7815. sink.os << "PUT";
  7816. sink.done();
  7817. return true;
  7818. },
  7819. "text/plain");
  7820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. EXPECT_EQ("PUT", res->body);
  7823. }
  7824. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7825. cli_.set_compress(true);
  7826. auto res = cli_.Post(
  7827. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7828. "text/plain");
  7829. ASSERT_TRUE(!res);
  7830. EXPECT_EQ(Error::Canceled, res.error());
  7831. }
  7832. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7833. cli_.set_compress(true);
  7834. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::OK_200, res->status);
  7837. EXPECT_EQ(LARGE_DATA, res->body);
  7838. }
  7839. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7840. #ifdef CPPHTTPLIB_SSL_ENABLED
  7841. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7842. Client cli(s.c_str());
  7843. cli.enable_server_certificate_verification(false);
  7844. #else
  7845. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7846. Client cli(s.c_str());
  7847. #endif
  7848. cli.set_compress(true);
  7849. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::OK_200, res->status);
  7852. EXPECT_EQ(LARGE_DATA, res->body);
  7853. // The compressed size should be less than a 10th of the original. May vary
  7854. // depending on the zlib library.
  7855. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7856. static_cast<uint64_t>(10 * 1024 * 1024));
  7857. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7858. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7859. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7860. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7861. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7862. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7863. #endif
  7864. }
  7865. TEST_F(ServerTest, PutContentWithDeflate) {
  7866. cli_.set_compress(false);
  7867. Headers headers;
  7868. headers.emplace("Content-Encoding", "deflate");
  7869. // PUT in deflate format:
  7870. auto res = cli_.Put("/put", headers,
  7871. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ("PUT", res->body);
  7875. }
  7876. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7877. Headers headers;
  7878. headers.emplace("Accept-Encoding", "gzip, deflate");
  7879. auto res = cli_.Get("/streamed-chunked", headers);
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ(std::string("123456789"), res->body);
  7883. }
  7884. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7885. Headers headers;
  7886. headers.emplace("Accept-Encoding", "gzip, deflate");
  7887. auto res = cli_.Get("/streamed-chunked2", headers);
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ(std::string("123456789"), res->body);
  7891. }
  7892. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7893. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. }
  7897. TEST(GzipDecompressor, ChunkedDecompression) {
  7898. std::string data;
  7899. for (size_t i = 0; i < 32 * 1024; ++i) {
  7900. data.push_back(static_cast<char>('a' + i % 26));
  7901. }
  7902. std::string compressed_data;
  7903. {
  7904. httplib::detail::gzip_compressor compressor;
  7905. bool result = compressor.compress(
  7906. data.data(), data.size(),
  7907. /*last=*/true,
  7908. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7909. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7910. compressed_data_size);
  7911. return true;
  7912. });
  7913. ASSERT_TRUE(result);
  7914. }
  7915. std::string decompressed_data;
  7916. {
  7917. httplib::detail::gzip_decompressor decompressor;
  7918. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7919. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7920. size_t chunk_size = 130;
  7921. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7922. chunk_begin += chunk_size) {
  7923. size_t current_chunk_size =
  7924. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7925. bool result = decompressor.decompress(
  7926. compressed_data.data() + chunk_begin, current_chunk_size,
  7927. [&](const char *decompressed_data_chunk,
  7928. size_t decompressed_data_chunk_size) {
  7929. decompressed_data.insert(decompressed_data.size(),
  7930. decompressed_data_chunk,
  7931. decompressed_data_chunk_size);
  7932. return true;
  7933. });
  7934. ASSERT_TRUE(result);
  7935. }
  7936. }
  7937. ASSERT_EQ(data, decompressed_data);
  7938. }
  7939. TEST(GzipDecompressor, DeflateDecompression) {
  7940. std::string original_text = "Raw deflate without gzip";
  7941. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7942. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7943. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7944. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7945. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7946. std::string decompressed_data;
  7947. {
  7948. httplib::detail::gzip_decompressor decompressor;
  7949. bool result = decompressor.decompress(
  7950. compressed_data.data(), compressed_data.size(),
  7951. [&](const char *decompressed_data_chunk,
  7952. size_t decompressed_data_chunk_size) {
  7953. decompressed_data.insert(decompressed_data.size(),
  7954. decompressed_data_chunk,
  7955. decompressed_data_chunk_size);
  7956. return true;
  7957. });
  7958. ASSERT_TRUE(result);
  7959. }
  7960. ASSERT_EQ(original_text, decompressed_data);
  7961. }
  7962. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7963. std::string original_text = "Raw deflate without gzip";
  7964. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7965. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7966. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7967. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7968. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7969. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7970. std::string decompressed_data;
  7971. {
  7972. httplib::detail::gzip_decompressor decompressor;
  7973. bool result = decompressor.decompress(
  7974. compressed_data.data(), compressed_data.size(),
  7975. [&](const char *decompressed_data_chunk,
  7976. size_t decompressed_data_chunk_size) {
  7977. decompressed_data.insert(decompressed_data.size(),
  7978. decompressed_data_chunk,
  7979. decompressed_data_chunk_size);
  7980. return true;
  7981. });
  7982. ASSERT_TRUE(result);
  7983. }
  7984. ASSERT_EQ(original_text, decompressed_data);
  7985. }
  7986. #endif
  7987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7988. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7989. Headers headers;
  7990. headers.emplace("Accept-Encoding", "br");
  7991. auto res = cli_.Get("/streamed-chunked", headers);
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ(std::string("123456789"), res->body);
  7995. }
  7996. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7997. Headers headers;
  7998. headers.emplace("Accept-Encoding", "br");
  7999. auto res = cli_.Get("/streamed-chunked2", headers);
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(StatusCode::OK_200, res->status);
  8002. EXPECT_EQ(std::string("123456789"), res->body);
  8003. }
  8004. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8005. cli_.set_compress(true);
  8006. auto res = cli_.Put(
  8007. "/put", 3,
  8008. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8009. sink.os << "PUT";
  8010. return true;
  8011. },
  8012. "text/plain");
  8013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. EXPECT_EQ("PUT", res->body);
  8016. }
  8017. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8018. cli_.set_compress(true);
  8019. auto res = cli_.Put(
  8020. "/put",
  8021. [](size_t /*offset*/, DataSink &sink) {
  8022. sink.os << "PUT";
  8023. sink.done();
  8024. return true;
  8025. },
  8026. "text/plain");
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. EXPECT_EQ("PUT", res->body);
  8030. }
  8031. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8032. cli_.set_compress(true);
  8033. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. EXPECT_EQ(LARGE_DATA, res->body);
  8037. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8038. }
  8039. #endif
  8040. TEST_F(ServerTest, Patch) {
  8041. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("PATCH", res->body);
  8045. }
  8046. TEST_F(ServerTest, Delete) {
  8047. auto res = cli_.Delete("/delete");
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. EXPECT_EQ("DELETE", res->body);
  8051. }
  8052. TEST_F(ServerTest, DeleteContentReceiver) {
  8053. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. EXPECT_EQ("content", res->body);
  8057. }
  8058. TEST_F(ServerTest, Options) {
  8059. auto res = cli_.Options("*");
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8063. EXPECT_TRUE(res->body.empty());
  8064. }
  8065. TEST_F(ServerTest, URL) {
  8066. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. }
  8070. TEST_F(ServerTest, ArrayParam) {
  8071. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8073. EXPECT_EQ(StatusCode::OK_200, res->status);
  8074. }
  8075. TEST_F(ServerTest, ArrayParamValues) {
  8076. auto res =
  8077. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8079. EXPECT_EQ(StatusCode::OK_200, res->status);
  8080. }
  8081. TEST_F(ServerTest, NoMultipleHeaders) {
  8082. Headers headers = {{"Content-Length", "5"}};
  8083. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8084. "text/plain");
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::OK_200, res->status);
  8087. }
  8088. TEST_F(ServerTest, PostContentReceiver) {
  8089. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8091. ASSERT_EQ(StatusCode::OK_200, res->status);
  8092. ASSERT_EQ("content", res->body);
  8093. }
  8094. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8095. UploadFormDataItems items = {
  8096. {"text1", "text default", "", ""},
  8097. {"text2", "aωb", "", ""},
  8098. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8099. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8100. {"file3", "", "", "application/octet-stream"},
  8101. };
  8102. auto res = cli_.Post("/content_receiver", items);
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. }
  8106. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8107. UploadFormDataItems items = {
  8108. {"text1", "text default", "", ""},
  8109. {"text2", "aωb", "", ""},
  8110. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8111. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8112. {"file3", "", "", "application/octet-stream"},
  8113. };
  8114. auto boundary = std::string("+++++");
  8115. std::string body;
  8116. for (const auto &item : items) {
  8117. body += "--" + boundary + "\r\n";
  8118. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8119. if (!item.filename.empty()) {
  8120. body += "; filename=\"" + item.filename + "\"";
  8121. }
  8122. body += "\r\n";
  8123. if (!item.content_type.empty()) {
  8124. body += "Content-Type: " + item.content_type + "\r\n";
  8125. }
  8126. body += "\r\n";
  8127. body += item.content + "\r\n";
  8128. }
  8129. body += "--" + boundary + "--\r\n";
  8130. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8131. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. }
  8135. TEST(MultipartFormDataTest, FieldEscaping) {
  8136. Server svr;
  8137. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8138. const ContentReader &content_reader) {
  8139. ASSERT_TRUE(req.is_multipart_form_data());
  8140. std::vector<FormData> received;
  8141. content_reader(
  8142. [&](const FormData &file) {
  8143. received.push_back(file);
  8144. return true;
  8145. },
  8146. [&](const char *data, size_t data_length) {
  8147. received.back().content.append(data, data_length);
  8148. return true;
  8149. });
  8150. // '"', CR and LF in names and filenames are escaped following the
  8151. // WHATWG HTML standard, so each part still parses as a single part
  8152. // with no injected headers. Content types get CR/LF escaped too,
  8153. // while '"' (legal there, e.g. quoted charset) is preserved.
  8154. ASSERT_EQ(4U, received.size());
  8155. EXPECT_EQ("na%22me", received[0].name);
  8156. EXPECT_EQ("quoted name", received[0].content);
  8157. EXPECT_EQ("file", received[1].name);
  8158. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8159. received[1].filename);
  8160. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8161. EXPECT_EQ("injected", received[1].content);
  8162. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8163. EXPECT_EQ("my%22file.txt", received[2].filename);
  8164. EXPECT_EQ("cr lf name", received[2].content);
  8165. EXPECT_EQ("typed", received[3].name);
  8166. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8167. received[3].content_type);
  8168. EXPECT_EQ("typed content", received[3].content);
  8169. });
  8170. auto port = svr.bind_to_any_port("localhost");
  8171. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8172. auto se = detail::scope_exit([&] {
  8173. svr.stop();
  8174. t.join();
  8175. ASSERT_FALSE(svr.is_running());
  8176. });
  8177. svr.wait_until_ready();
  8178. Client cli("localhost", port);
  8179. UploadFormDataItems items = {
  8180. {"na\"me", "quoted name", "", ""},
  8181. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8182. "application/octet-stream"},
  8183. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8184. {"typed", "typed content", "",
  8185. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8186. };
  8187. auto res = cli.Post("/post", items);
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::OK_200, res->status);
  8190. }
  8191. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8192. const UploadFormDataItems items = {
  8193. {"name1", "Content 1", "", ""},
  8194. {"name2", "Content 2", "file2.txt", "text/plain"},
  8195. };
  8196. Server svr;
  8197. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8198. const ContentReader &content_reader) {
  8199. ASSERT_TRUE(req.is_multipart_form_data());
  8200. std::vector<FormData> received;
  8201. content_reader(
  8202. [&](const FormData &file) {
  8203. received.push_back(file);
  8204. return true;
  8205. },
  8206. [&](const char *data, size_t data_length) {
  8207. received.back().content.append(data, data_length);
  8208. return true;
  8209. });
  8210. ASSERT_EQ(2U, received.size());
  8211. EXPECT_EQ("name1", received[0].name);
  8212. EXPECT_EQ("Content 1", received[0].content);
  8213. EXPECT_EQ("name2", received[1].name);
  8214. EXPECT_EQ("Content 2", received[1].content);
  8215. EXPECT_EQ("file2.txt", received[1].filename);
  8216. EXPECT_EQ("text/plain", received[1].content_type);
  8217. });
  8218. auto port = svr.bind_to_any_port("localhost");
  8219. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8220. auto se = detail::scope_exit([&] {
  8221. svr.stop();
  8222. t.join();
  8223. ASSERT_FALSE(svr.is_running());
  8224. });
  8225. svr.wait_until_ready();
  8226. Client cli("localhost", port);
  8227. // Whole-body serialization with a generated boundary
  8228. {
  8229. MultipartFormDataWriter writer;
  8230. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8231. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8232. writer.content_type());
  8233. auto body = writer.serialize(items);
  8234. EXPECT_EQ(body.size(), writer.content_length(items));
  8235. auto res = cli.Post("/post", body, writer.content_type());
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. }
  8239. // Per-part framing with a custom boundary via a content provider
  8240. {
  8241. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8242. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8243. MultipartFormDataWriter writer("custom-boundary_123");
  8244. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8245. std::string body;
  8246. for (const auto &item : items) {
  8247. body += writer.item_begin(item);
  8248. body += item.content;
  8249. body += MultipartFormDataWriter::item_end();
  8250. }
  8251. body += writer.finish();
  8252. EXPECT_EQ(body.size(), writer.content_length(items));
  8253. auto res = cli.Post(
  8254. "/post", body.size(),
  8255. [&](size_t offset, size_t length, DataSink &sink) {
  8256. sink.write(body.data() + offset, length);
  8257. return true;
  8258. },
  8259. writer.content_type());
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. }
  8263. }
  8264. TEST_F(ServerTest, PostContentReceiverGzip) {
  8265. cli_.set_compress(true);
  8266. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8268. ASSERT_EQ(StatusCode::OK_200, res->status);
  8269. ASSERT_EQ("content", res->body);
  8270. }
  8271. TEST_F(ServerTest, PutContentReceiver) {
  8272. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. ASSERT_EQ(StatusCode::OK_200, res->status);
  8275. ASSERT_EQ("content", res->body);
  8276. }
  8277. TEST_F(ServerTest, PatchContentReceiver) {
  8278. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8280. ASSERT_EQ(StatusCode::OK_200, res->status);
  8281. ASSERT_EQ("content", res->body);
  8282. }
  8283. template <typename ClientType>
  8284. void TestWithHeadersAndContentReceiver(
  8285. ClientType &cli,
  8286. std::function<Result(ClientType &, const std::string &, const Headers &,
  8287. const std::string &, const std::string &,
  8288. ContentReceiver, DownloadProgress)>
  8289. request_func) {
  8290. Headers headers;
  8291. headers.emplace("X-Custom-Header", "test-value");
  8292. std::string received_body;
  8293. auto res = request_func(
  8294. cli, "/content_receiver", headers, "content", "application/json",
  8295. [&](const char *data, size_t data_length) {
  8296. received_body.append(data, data_length);
  8297. return true;
  8298. },
  8299. nullptr);
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. EXPECT_EQ("content", received_body);
  8303. }
  8304. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8305. #ifdef CPPHTTPLIB_SSL_ENABLED
  8306. using ClientT = SSLClient;
  8307. #else
  8308. using ClientT = Client;
  8309. #endif
  8310. TestWithHeadersAndContentReceiver<ClientT>(
  8311. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8312. const std::string &body, const std::string &content_type,
  8313. ContentReceiver receiver, DownloadProgress progress) {
  8314. return cli.Post(path, headers, body, content_type, receiver, progress);
  8315. });
  8316. }
  8317. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8318. #ifdef CPPHTTPLIB_SSL_ENABLED
  8319. using ClientT = SSLClient;
  8320. #else
  8321. using ClientT = Client;
  8322. #endif
  8323. TestWithHeadersAndContentReceiver<ClientT>(
  8324. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8325. const std::string &body, const std::string &content_type,
  8326. ContentReceiver receiver, DownloadProgress progress) {
  8327. return cli.Put(path, headers, body, content_type, receiver, progress);
  8328. });
  8329. }
  8330. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8331. #ifdef CPPHTTPLIB_SSL_ENABLED
  8332. using ClientT = SSLClient;
  8333. #else
  8334. using ClientT = Client;
  8335. #endif
  8336. TestWithHeadersAndContentReceiver<ClientT>(
  8337. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8338. const std::string &body, const std::string &content_type,
  8339. ContentReceiver receiver, DownloadProgress progress) {
  8340. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8341. });
  8342. }
  8343. template <typename ClientType>
  8344. void TestWithHeadersAndContentReceiverWithProgress(
  8345. ClientType &cli,
  8346. std::function<Result(ClientType &, const std::string &, const Headers &,
  8347. const std::string &, const std::string &,
  8348. ContentReceiver, DownloadProgress)>
  8349. request_func) {
  8350. Headers headers;
  8351. headers.emplace("X-Test-Header", "progress-test");
  8352. std::string received_body;
  8353. auto progress_called = false;
  8354. auto res = request_func(
  8355. cli, "/content_receiver", headers, "content", "text/plain",
  8356. [&](const char *data, size_t data_length) {
  8357. received_body.append(data, data_length);
  8358. return true;
  8359. },
  8360. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8361. progress_called = true;
  8362. return true;
  8363. });
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::OK_200, res->status);
  8366. EXPECT_EQ("content", received_body);
  8367. EXPECT_TRUE(progress_called);
  8368. }
  8369. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8370. #ifdef CPPHTTPLIB_SSL_ENABLED
  8371. using ClientT = SSLClient;
  8372. #else
  8373. using ClientT = Client;
  8374. #endif
  8375. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8376. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8377. const std::string &body, const std::string &content_type,
  8378. ContentReceiver receiver, DownloadProgress progress) {
  8379. return cli.Post(path, headers, body, content_type, receiver, progress);
  8380. });
  8381. }
  8382. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8383. #ifdef CPPHTTPLIB_SSL_ENABLED
  8384. using ClientT = SSLClient;
  8385. #else
  8386. using ClientT = Client;
  8387. #endif
  8388. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8389. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8390. const std::string &body, const std::string &content_type,
  8391. ContentReceiver receiver, DownloadProgress progress) {
  8392. return cli.Put(path, headers, body, content_type, receiver, progress);
  8393. });
  8394. }
  8395. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8396. #ifdef CPPHTTPLIB_SSL_ENABLED
  8397. using ClientT = SSLClient;
  8398. #else
  8399. using ClientT = Client;
  8400. #endif
  8401. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8402. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8403. const std::string &body, const std::string &content_type,
  8404. ContentReceiver receiver, DownloadProgress progress) {
  8405. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8406. });
  8407. }
  8408. template <typename ClientType>
  8409. void TestWithHeadersAndContentReceiverError(
  8410. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8411. const Headers &, const std::string &,
  8412. const std::string &, ContentReceiver)>
  8413. request_func) {
  8414. Headers headers;
  8415. headers.emplace("X-Error-Test", "true");
  8416. std::string received_body;
  8417. auto receiver_failed = false;
  8418. auto res =
  8419. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8420. [&](const char *data, size_t data_length) {
  8421. received_body.append(data, data_length);
  8422. receiver_failed = true;
  8423. return false;
  8424. });
  8425. ASSERT_FALSE(res);
  8426. EXPECT_TRUE(receiver_failed);
  8427. }
  8428. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8429. #ifdef CPPHTTPLIB_SSL_ENABLED
  8430. using ClientT = SSLClient;
  8431. #else
  8432. using ClientT = Client;
  8433. #endif
  8434. TestWithHeadersAndContentReceiverError<ClientT>(
  8435. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8436. const std::string &body, const std::string &content_type,
  8437. ContentReceiver receiver) {
  8438. return cli.Post(path, headers, body, content_type, receiver);
  8439. });
  8440. }
  8441. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8442. #ifdef CPPHTTPLIB_SSL_ENABLED
  8443. using ClientT = SSLClient;
  8444. #else
  8445. using ClientT = Client;
  8446. #endif
  8447. TestWithHeadersAndContentReceiverError<ClientT>(
  8448. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8449. const std::string &body, const std::string &content_type,
  8450. ContentReceiver receiver) {
  8451. return cli.Put(path, headers, body, content_type, receiver);
  8452. });
  8453. }
  8454. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8455. #ifdef CPPHTTPLIB_SSL_ENABLED
  8456. using ClientT = SSLClient;
  8457. #else
  8458. using ClientT = Client;
  8459. #endif
  8460. TestWithHeadersAndContentReceiverError<ClientT>(
  8461. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8462. const std::string &body, const std::string &content_type,
  8463. ContentReceiver receiver) {
  8464. return cli.Patch(path, headers, body, content_type, receiver);
  8465. });
  8466. }
  8467. TEST_F(ServerTest, PostQueryStringAndBody) {
  8468. auto res =
  8469. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. ASSERT_EQ(StatusCode::OK_200, res->status);
  8472. }
  8473. TEST_F(ServerTest, HTTP2Magic) {
  8474. Request req;
  8475. req.method = "PRI";
  8476. req.path = "*";
  8477. req.body = "SM";
  8478. auto res = std::make_shared<Response>();
  8479. auto error = Error::Success;
  8480. auto ret = cli_.send(req, *res, error);
  8481. ASSERT_TRUE(ret);
  8482. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8483. }
  8484. TEST_F(ServerTest, KeepAlive) {
  8485. auto res = cli_.Get("/hi");
  8486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8489. EXPECT_EQ("Hello World!", res->body);
  8490. res = cli_.Get("/hi");
  8491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8492. EXPECT_EQ(StatusCode::OK_200, res->status);
  8493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8494. EXPECT_EQ("Hello World!", res->body);
  8495. res = cli_.Get("/hi");
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8499. EXPECT_EQ("Hello World!", res->body);
  8500. res = cli_.Get("/not-exist");
  8501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8503. res = cli_.Post("/empty", "", "text/plain");
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8507. EXPECT_EQ("empty", res->body);
  8508. EXPECT_EQ("close", res->get_header_value("Connection"));
  8509. res = cli_.Post(
  8510. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8511. "text/plain");
  8512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8513. EXPECT_EQ(StatusCode::OK_200, res->status);
  8514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8515. EXPECT_EQ("empty", res->body);
  8516. cli_.set_keep_alive(false);
  8517. res = cli_.Get("/last-request");
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. EXPECT_EQ("close", res->get_header_value("Connection"));
  8521. }
  8522. TEST_F(ServerTest, TooManyRedirect) {
  8523. cli_.set_follow_location(true);
  8524. auto res = cli_.Get("/redirect/0");
  8525. ASSERT_TRUE(!res);
  8526. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8527. }
  8528. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8529. Request req;
  8530. req.method = "FOOBAR";
  8531. req.path = "/hi";
  8532. cli_.set_keep_alive(true);
  8533. auto res = cli_.send(req);
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8536. EXPECT_EQ("close", res->get_header_value("Connection"));
  8537. EXPECT_FALSE(cli_.is_socket_open());
  8538. }
  8539. TEST_F(ServerTest, CustomRouteReadsBody) {
  8540. const std::string xml =
  8541. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8542. Request req;
  8543. req.method = "PROPFIND";
  8544. req.path = "/dav/dir";
  8545. req.set_header("Depth", "1");
  8546. req.body = xml;
  8547. auto res = cli_.send(req);
  8548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8549. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8550. EXPECT_EQ(xml, res->body);
  8551. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8552. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8553. }
  8554. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8555. Request req;
  8556. req.method = "PROPFIND";
  8557. req.path = "/dav/42";
  8558. auto res = cli_.send(req);
  8559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8560. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8561. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8562. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8563. }
  8564. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8565. Request req;
  8566. req.method = "PROPFIND";
  8567. req.path = "/dav-re/123";
  8568. auto res = cli_.send(req);
  8569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8570. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8571. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8572. }
  8573. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8574. Request req;
  8575. req.method = "MKCOL";
  8576. req.path = "/dav-mkcol";
  8577. auto res = cli_.send(req);
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ(StatusCode::Created_201, res->status);
  8580. }
  8581. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8582. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8583. Request req;
  8584. req.method = "REPORT";
  8585. req.path = "/dav-report";
  8586. req.body = xml;
  8587. auto res = cli_.send(req);
  8588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8589. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8590. EXPECT_EQ(xml, res->body);
  8591. }
  8592. // A content reader route must fire even when the request carries no body,
  8593. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8594. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8595. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8596. Request req;
  8597. req.method = "REPORT";
  8598. req.path = "/dav-report";
  8599. auto res = cli_.send(req);
  8600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8601. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8602. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8603. }
  8604. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8605. Request req;
  8606. req.method = "PROPFIND";
  8607. req.path = "/not-dav";
  8608. auto res = cli_.send(req);
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8611. }
  8612. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8613. Request req;
  8614. req.method = "UNLOCK";
  8615. req.path = "/dav/dir";
  8616. cli_.set_keep_alive(true);
  8617. auto res = cli_.send(req);
  8618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8619. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8620. EXPECT_EQ("close", res->get_header_value("Connection"));
  8621. EXPECT_FALSE(cli_.is_socket_open());
  8622. }
  8623. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8624. // The mount point serves this path, but only for GET and HEAD.
  8625. auto get_res = cli_.Get("/dir/index.html");
  8626. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8627. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8628. Request req;
  8629. req.method = "PROPFIND";
  8630. req.path = "/dir/index.html";
  8631. auto res = cli_.send(req);
  8632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8634. }
  8635. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8636. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8637. cli_.set_keep_alive(true);
  8638. for (auto i = 0; i < 2; i++) {
  8639. Request req;
  8640. req.method = "PROPFIND";
  8641. req.path = "/dav/dir";
  8642. req.body = xml;
  8643. auto res = cli_.send(req);
  8644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8645. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8646. EXPECT_EQ(xml, res->body);
  8647. EXPECT_TRUE(cli_.is_socket_open());
  8648. }
  8649. // A built-in method must still be served on the same connection.
  8650. cli_.set_keep_alive(false);
  8651. auto res = cli_.Get("/hi");
  8652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8653. EXPECT_EQ(StatusCode::OK_200, res->status);
  8654. EXPECT_EQ("close", res->get_header_value("Connection"));
  8655. }
  8656. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8657. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8658. Request req;
  8659. req.method = "PROPFIND";
  8660. req.path = "/dav/dir";
  8661. req.set_header("Expect", "100-continue");
  8662. req.body = xml;
  8663. auto res = cli_.send(req);
  8664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8665. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8666. EXPECT_EQ(xml, res->body);
  8667. }
  8668. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8669. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8670. TEST_F(ServerTest, Gzip) {
  8671. Headers headers;
  8672. headers.emplace("Accept-Encoding", "gzip, deflate");
  8673. auto res = cli_.Get("/compress", headers);
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8677. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8678. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8679. "7890123456789012345678901234567890",
  8680. res->body);
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. }
  8683. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8684. Headers headers;
  8685. headers.emplace("Accept-Encoding", "gzip, deflate");
  8686. auto res = cli_.Get("/compress-with-charset", headers);
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8689. EXPECT_EQ("application/json; charset=utf-8",
  8690. res->get_header_value("Content-Type"));
  8691. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8692. "7890123456789012345678901234567890",
  8693. res->body);
  8694. EXPECT_EQ(StatusCode::OK_200, res->status);
  8695. }
  8696. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8697. Headers headers;
  8698. headers.emplace("Accept-Encoding", "");
  8699. auto res = cli_.Get("/compress", headers);
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8702. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8703. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8704. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8705. "7890123456789012345678901234567890",
  8706. res->body);
  8707. EXPECT_EQ(StatusCode::OK_200, res->status);
  8708. }
  8709. TEST_F(ServerTest, GzipWithContentReceiver) {
  8710. Headers headers;
  8711. headers.emplace("Accept-Encoding", "gzip, deflate");
  8712. std::string body;
  8713. auto res =
  8714. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8715. EXPECT_EQ(100U, data_length);
  8716. body.append(data, data_length);
  8717. return true;
  8718. });
  8719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8720. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8722. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8723. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8724. "7890123456789012345678901234567890",
  8725. body);
  8726. EXPECT_EQ(StatusCode::OK_200, res->status);
  8727. }
  8728. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8729. Headers headers;
  8730. headers.emplace("Accept-Encoding", "gzip, deflate");
  8731. cli_.set_decompress(false);
  8732. auto res = cli_.Get("/compress", headers);
  8733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8736. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8737. EXPECT_EQ(33U, res->body.size());
  8738. EXPECT_EQ(StatusCode::OK_200, res->status);
  8739. }
  8740. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8741. Headers headers;
  8742. headers.emplace("Accept-Encoding", "");
  8743. std::string body;
  8744. auto res =
  8745. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8746. EXPECT_EQ(100U, data_length);
  8747. body.append(data, data_length);
  8748. return true;
  8749. });
  8750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8751. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8752. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8753. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8754. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8755. "7890123456789012345678901234567890",
  8756. body);
  8757. EXPECT_EQ(StatusCode::OK_200, res->status);
  8758. }
  8759. TEST_F(ServerTest, NoGzip) {
  8760. Headers headers;
  8761. headers.emplace("Accept-Encoding", "gzip, deflate");
  8762. auto res = cli_.Get("/nocompress", headers);
  8763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8764. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8765. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8766. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8767. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8768. "7890123456789012345678901234567890",
  8769. res->body);
  8770. EXPECT_EQ(StatusCode::OK_200, res->status);
  8771. }
  8772. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8773. Headers headers;
  8774. headers.emplace("Accept-Encoding", "gzip, deflate");
  8775. std::string body;
  8776. auto res = cli_.Get("/nocompress", headers,
  8777. [&](const char *data, size_t data_length) {
  8778. EXPECT_EQ(100U, data_length);
  8779. body.append(data, data_length);
  8780. return true;
  8781. });
  8782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8783. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8784. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8785. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8786. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8787. "7890123456789012345678901234567890",
  8788. body);
  8789. EXPECT_EQ(StatusCode::OK_200, res->status);
  8790. }
  8791. TEST_F(ServerTest, MultipartFormDataGzip) {
  8792. UploadFormDataItems items = {
  8793. {"key1", "test", "", ""},
  8794. {"key2", "--abcdefg123", "", ""},
  8795. };
  8796. cli_.set_compress(true);
  8797. auto res = cli_.Post("/compress-multipart", items);
  8798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8799. EXPECT_EQ(StatusCode::OK_200, res->status);
  8800. }
  8801. #endif
  8802. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8803. // Static file compression is opt-in, so these run their own server rather than
  8804. // flipping it on for the shared ServerTest fixture, which would silently
  8805. // rewrite what every other static file test is asserting.
  8806. class StaticFileCompressionTest : public ::testing::Test {
  8807. protected:
  8808. void TearDown() override {
  8809. if (t_.joinable()) {
  8810. svr_.stop();
  8811. t_.join();
  8812. }
  8813. }
  8814. int start(const std::function<void(Server &)> &configure = nullptr) {
  8815. // Serves the same tree as a directory of build-time compressed assets
  8816. // would be served: the mount point names the coding the files are already
  8817. // stored in. Registered before "/" so it is the one that matches.
  8818. svr_.set_mount_point("/pre-encoded", "./www",
  8819. {{"Content-Encoding", "gzip"}});
  8820. svr_.set_mount_point("/", "./www");
  8821. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8822. res.set_file_content("./www/dir/index.html", "text/html");
  8823. });
  8824. svr_.Get("/pre-encoded-file-content",
  8825. [](const Request & /*req*/, Response &res) {
  8826. res.set_header("Content-Encoding", "gzip");
  8827. res.set_file_content("./www/dir/index.html", "text/html");
  8828. });
  8829. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8830. res.set_content_provider(
  8831. 6, "text/plain",
  8832. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8833. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8834. return true;
  8835. });
  8836. });
  8837. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8838. res.set_content_provider(
  8839. 1000, "text/plain",
  8840. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8841. if (offset < 100) {
  8842. std::string data(100, 'A');
  8843. sink.write(data.data(), data.size());
  8844. return true;
  8845. }
  8846. std::this_thread::sleep_for(std::chrono::seconds(2));
  8847. std::string data(900, 'B');
  8848. sink.write(data.data(), data.size());
  8849. return true;
  8850. });
  8851. });
  8852. if (configure) { configure(svr_); }
  8853. auto port = svr_.bind_to_any_port(HOST);
  8854. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8855. svr_.wait_until_ready();
  8856. return port;
  8857. }
  8858. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8859. // Every file under ./www except 1MB.txt is smaller than the default
  8860. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8861. // it out of the way.
  8862. static void enable_without_floor(Server &svr) {
  8863. svr.set_static_file_compression(true);
  8864. svr.set_static_file_compression_min_length(0);
  8865. }
  8866. Server svr_;
  8867. std::thread t_;
  8868. };
  8869. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8870. auto port = start();
  8871. Client cli(HOST, port);
  8872. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8874. EXPECT_EQ(StatusCode::OK_200, res->status);
  8875. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8876. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8877. EXPECT_EQ(1048576U, res->body.size());
  8878. }
  8879. TEST_F(StaticFileCompressionTest, MountPoint) {
  8880. auto port = start(enable);
  8881. Client cli(HOST, port);
  8882. cli.set_decompress(false);
  8883. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8885. EXPECT_EQ(StatusCode::OK_200, res->status);
  8886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8887. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8888. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8889. // The response stays self-delimiting: a length, not a chunked body.
  8890. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8891. EXPECT_EQ(std::to_string(res->body.size()),
  8892. res->get_header_value("Content-Length"));
  8893. EXPECT_LT(res->body.size(), 1048576U);
  8894. EXPECT_FALSE(res->body.empty());
  8895. }
  8896. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8897. auto port = start(enable);
  8898. Client cli(HOST, port);
  8899. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8903. EXPECT_EQ(1048576U, res->body.size());
  8904. }
  8905. TEST_F(StaticFileCompressionTest, FileContent) {
  8906. auto port = start(enable_without_floor);
  8907. Client cli(HOST, port);
  8908. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8910. EXPECT_EQ(StatusCode::OK_200, res->status);
  8911. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8912. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8913. EXPECT_EQ(104U, res->body.size());
  8914. }
  8915. // A handler that serves an already-encoded file names the coding itself. The
  8916. // file-backed path decided its coding from Accept-Encoding and the content
  8917. // type alone, so it compressed the stored bytes a second time and appended a
  8918. // second Content-Encoding field line.
  8919. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8920. auto port = start(enable_without_floor);
  8921. Client cli(HOST, port);
  8922. cli.set_decompress(false);
  8923. auto res = cli.Get("/pre-encoded-file-content",
  8924. Headers{{"Accept-Encoding", "gzip"}});
  8925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8926. EXPECT_EQ(StatusCode::OK_200, res->status);
  8927. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8928. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8929. // Vary belongs to a coding the server chose, and it chose none here.
  8930. EXPECT_FALSE(res->has_header("Vary"));
  8931. // The file travels exactly as it is stored on disk.
  8932. EXPECT_EQ(104U, res->body.size());
  8933. }
  8934. // The 1MB file clears the default floor, so this one runs the configuration a
  8935. // deployment would actually have.
  8936. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8937. auto port = start(enable);
  8938. Client cli(HOST, port);
  8939. cli.set_decompress(false);
  8940. auto res =
  8941. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8943. EXPECT_EQ(StatusCode::OK_200, res->status);
  8944. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8945. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8946. EXPECT_FALSE(res->has_header("Vary"));
  8947. EXPECT_EQ(1048576U, res->body.size());
  8948. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8949. }
  8950. TEST_F(StaticFileCompressionTest, Head) {
  8951. auto port = start(enable);
  8952. Client cli(HOST, port);
  8953. cli.set_decompress(false);
  8954. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8955. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8956. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8960. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8961. // HEAD still reports the size a GET would return.
  8962. EXPECT_EQ(get->get_header_value("Content-Length"),
  8963. res->get_header_value("Content-Length"));
  8964. EXPECT_TRUE(res->body.empty());
  8965. }
  8966. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8967. auto port = start(enable);
  8968. Client cli(HOST, port);
  8969. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8970. {"Accept-Encoding", "gzip"}});
  8971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8972. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8973. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8974. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8975. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8976. EXPECT_EQ("cd", res->body);
  8977. }
  8978. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8979. auto port = start(enable);
  8980. Client cli(HOST, port);
  8981. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8983. EXPECT_EQ(StatusCode::OK_200, res->status);
  8984. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8985. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8986. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8987. }
  8988. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8989. auto port = start(enable);
  8990. Client cli(HOST, port);
  8991. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8995. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8996. EXPECT_TRUE(res->body.empty());
  8997. }
  8998. TEST_F(StaticFileCompressionTest, MinLength) {
  8999. auto port = start(enable);
  9000. Client cli(HOST, port);
  9001. // 104 bytes, well under the default floor. Compressing it would add the
  9002. // gzip header and trailer to a body that already fits in one packet.
  9003. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ(StatusCode::OK_200, res->status);
  9006. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9007. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9008. }
  9009. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9010. auto port = start([](Server &svr) {
  9011. svr.set_static_file_compression(true);
  9012. svr.set_static_file_compression_min_length(1);
  9013. });
  9014. Client cli(HOST, port);
  9015. cli.set_decompress(false);
  9016. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9019. // A 9-byte file comes back larger than it went in, because gzip's header and
  9020. // trailer outweigh anything deflate can save. That is the end of the range
  9021. // the floor exists to keep out.
  9022. EXPECT_GT(res->body.size(), 9U);
  9023. }
  9024. TEST_F(StaticFileCompressionTest, MaxLength) {
  9025. auto port = start([](Server &svr) {
  9026. svr.set_static_file_compression(true);
  9027. svr.set_static_file_compression_min_length(0);
  9028. svr.set_static_file_compression_max_length(1024);
  9029. });
  9030. Client cli(HOST, port);
  9031. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9032. // defines `small` as a macro on Windows.
  9033. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9034. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9035. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9036. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9037. // Under it: compressed.
  9038. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9039. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9040. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9041. }
  9042. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9043. auto port = start(enable_without_floor);
  9044. Client cli(HOST, port);
  9045. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9046. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9047. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9048. auto identity_etag = identity->get_header_value("ETag");
  9049. ASSERT_FALSE(identity_etag.empty());
  9050. auto gzipped =
  9051. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9052. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9053. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9054. auto gzip_etag = gzipped->get_header_value("ETag");
  9055. ASSERT_FALSE(gzip_etag.empty());
  9056. // Two representations, two validators.
  9057. EXPECT_NE(identity_etag, gzip_etag);
  9058. // Each one revalidates against the request that would produce it...
  9059. auto fresh =
  9060. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9061. {"If-None-Match", gzip_etag}});
  9062. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9063. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9064. auto fresh_identity =
  9065. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9066. {"If-None-Match", identity_etag}});
  9067. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9068. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9069. // ...and not against the other representation.
  9070. auto crossed =
  9071. cli.Get("/dir/index.html",
  9072. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9073. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9074. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9075. }
  9076. // The opt-in covers responses the server reads off disk itself. A caller's own
  9077. // known-length provider keeps its Content-Length and, more importantly, keeps
  9078. // delivering incrementally: routing it through a compressor would hold every
  9079. // write back until zlib's window filled.
  9080. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9081. auto port = start(enable);
  9082. Client cli(HOST, port);
  9083. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::OK_200, res->status);
  9086. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9087. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9088. EXPECT_EQ("aaabbb", res->body);
  9089. }
  9090. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9091. auto port = start(enable);
  9092. Client cli(HOST, port);
  9093. cli.set_read_timeout(1, 0);
  9094. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9095. Headers{{"Accept-Encoding", "gzip"}});
  9096. ASSERT_TRUE(handle.is_valid());
  9097. // The provider writes 100 bytes and then stalls for longer than the read
  9098. // timeout. Those first bytes have to arrive anyway: run the response through
  9099. // a compressor and zlib holds them until its window fills, so the read would
  9100. // come back empty instead.
  9101. char buf[256];
  9102. auto n = handle.read(buf, sizeof(buf));
  9103. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9104. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9105. }
  9106. #endif
  9107. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9108. TEST_F(ServerTest, Brotli) {
  9109. Headers headers;
  9110. headers.emplace("Accept-Encoding", "br");
  9111. auto res = cli_.Get("/compress", headers);
  9112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9113. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9115. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9117. "7890123456789012345678901234567890",
  9118. res->body);
  9119. EXPECT_EQ(StatusCode::OK_200, res->status);
  9120. }
  9121. #endif
  9122. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9123. TEST_F(ServerTest, Zstd) {
  9124. Headers headers;
  9125. headers.emplace("Accept-Encoding", "zstd");
  9126. auto res = cli_.Get("/compress", headers);
  9127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9128. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9130. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9131. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9132. "7890123456789012345678901234567890",
  9133. res->body);
  9134. EXPECT_EQ(StatusCode::OK_200, res->status);
  9135. }
  9136. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9137. Headers headers;
  9138. headers.emplace("Accept-Encoding", "");
  9139. auto res = cli_.Get("/compress", headers);
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9143. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9144. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9145. "7890123456789012345678901234567890",
  9146. res->body);
  9147. EXPECT_EQ(StatusCode::OK_200, res->status);
  9148. }
  9149. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9150. Headers headers;
  9151. headers.emplace("Accept-Encoding", "zstd");
  9152. std::string body;
  9153. auto res =
  9154. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9155. EXPECT_EQ(100U, data_length);
  9156. body.append(data, data_length);
  9157. return true;
  9158. });
  9159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9160. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9162. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9164. "7890123456789012345678901234567890",
  9165. body);
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9169. Headers headers;
  9170. headers.emplace("Accept-Encoding", "zstd");
  9171. cli_.set_decompress(false);
  9172. auto res = cli_.Get("/compress", headers);
  9173. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9174. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9175. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9176. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9178. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9180. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9181. EXPECT_EQ(StatusCode::OK_200, res->status);
  9182. ASSERT_EQ(26U, res->body.size());
  9183. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9184. 0);
  9185. }
  9186. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9187. Headers headers;
  9188. headers.emplace("Accept-Encoding", "");
  9189. std::string body;
  9190. auto res =
  9191. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9192. EXPECT_EQ(100U, data_length);
  9193. body.append(data, data_length);
  9194. return true;
  9195. });
  9196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9197. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9199. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9200. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9201. "7890123456789012345678901234567890",
  9202. body);
  9203. EXPECT_EQ(StatusCode::OK_200, res->status);
  9204. }
  9205. TEST_F(ServerTest, NoZstd) {
  9206. Headers headers;
  9207. headers.emplace("Accept-Encoding", "zstd");
  9208. auto res = cli_.Get("/nocompress", headers);
  9209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9210. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9211. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9212. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9213. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9214. "7890123456789012345678901234567890",
  9215. res->body);
  9216. EXPECT_EQ(StatusCode::OK_200, res->status);
  9217. }
  9218. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9219. Headers headers;
  9220. headers.emplace("Accept-Encoding", "zstd");
  9221. std::string body;
  9222. auto res = cli_.Get("/nocompress", headers,
  9223. [&](const char *data, size_t data_length) {
  9224. EXPECT_EQ(100U, data_length);
  9225. body.append(data, data_length);
  9226. return true;
  9227. });
  9228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9229. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9230. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9231. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9232. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9233. "7890123456789012345678901234567890",
  9234. body);
  9235. EXPECT_EQ(StatusCode::OK_200, res->status);
  9236. }
  9237. // TODO: How to enable zstd ??
  9238. TEST_F(ServerTest, MultipartFormDataZstd) {
  9239. UploadFormDataItems items = {
  9240. {"key1", "test", "", ""},
  9241. {"key2", "--abcdefg123", "", ""},
  9242. };
  9243. Headers headers;
  9244. headers.emplace("Accept-Encoding", "zstd");
  9245. cli_.set_compress(true);
  9246. auto res = cli_.Post("/compress-multipart", headers, items);
  9247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9248. EXPECT_EQ(StatusCode::OK_200, res->status);
  9249. }
  9250. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9251. Headers headers;
  9252. headers.emplace("Accept-Encoding", "zstd");
  9253. cli_.set_compress(true);
  9254. auto res = cli_.Put(
  9255. "/put", headers, 3,
  9256. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9257. sink.os << "PUT";
  9258. return true;
  9259. },
  9260. "text/plain");
  9261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9262. EXPECT_EQ(StatusCode::OK_200, res->status);
  9263. EXPECT_EQ("PUT", res->body);
  9264. }
  9265. // Pre-compression logging tests
  9266. TEST_F(ServerTest, PreCompressionLogging) {
  9267. // Test data for compression (matches the actual /compress endpoint content)
  9268. const std::string test_content =
  9269. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9270. "3456789012345678901234567890";
  9271. // Variables to capture logging data
  9272. std::string pre_compression_body;
  9273. std::string pre_compression_content_type;
  9274. std::string pre_compression_content_encoding;
  9275. std::string post_compression_body;
  9276. std::string post_compression_content_type;
  9277. std::string post_compression_content_encoding;
  9278. // Set up pre-compression logger
  9279. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9280. const Response &res) {
  9281. pre_compression_body = res.body;
  9282. pre_compression_content_type = res.get_header_value("Content-Type");
  9283. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9284. });
  9285. // Set up post-compression logger
  9286. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9287. post_compression_body = res.body;
  9288. post_compression_content_type = res.get_header_value("Content-Type");
  9289. post_compression_content_encoding =
  9290. res.get_header_value("Content-Encoding");
  9291. });
  9292. // Test with gzip compression
  9293. Headers headers;
  9294. headers.emplace("Accept-Encoding", "gzip");
  9295. auto res = cli_.Get("/compress", headers);
  9296. // Verify response was compressed
  9297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9298. EXPECT_EQ(StatusCode::OK_200, res->status);
  9299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9300. // Verify pre-compression logger captured uncompressed content
  9301. EXPECT_EQ(test_content, pre_compression_body);
  9302. EXPECT_EQ("text/plain", pre_compression_content_type);
  9303. EXPECT_TRUE(pre_compression_content_encoding
  9304. .empty()); // No encoding header before compression
  9305. // Verify post-compression logger captured compressed content
  9306. EXPECT_NE(test_content,
  9307. post_compression_body); // Should be different after compression
  9308. EXPECT_EQ("text/plain", post_compression_content_type);
  9309. EXPECT_EQ("gzip", post_compression_content_encoding);
  9310. // Verify compressed content is smaller
  9311. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9312. }
  9313. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9314. const std::string test_content =
  9315. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9316. "3456789012345678901234567890";
  9317. std::string pre_compression_body;
  9318. std::string post_compression_body;
  9319. svr_.set_pre_compression_logger(
  9320. [&](const Request & /*req*/, const Response &res) {
  9321. pre_compression_body = res.body;
  9322. });
  9323. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9324. post_compression_body = res.body;
  9325. });
  9326. Headers headers;
  9327. headers.emplace("Accept-Encoding", "br");
  9328. auto res = cli_.Get("/compress", headers);
  9329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9330. EXPECT_EQ(StatusCode::OK_200, res->status);
  9331. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9332. // Verify pre-compression content is uncompressed
  9333. EXPECT_EQ(test_content, pre_compression_body);
  9334. // Verify post-compression content is compressed
  9335. EXPECT_NE(test_content, post_compression_body);
  9336. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9337. }
  9338. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9339. const std::string test_content =
  9340. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9341. "3456789012345678901234567890";
  9342. std::string pre_compression_body;
  9343. std::string post_compression_body;
  9344. svr_.set_pre_compression_logger(
  9345. [&](const Request & /*req*/, const Response &res) {
  9346. pre_compression_body = res.body;
  9347. });
  9348. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9349. post_compression_body = res.body;
  9350. });
  9351. // Request without compression (use /nocompress endpoint)
  9352. Headers headers;
  9353. auto res = cli_.Get("/nocompress", headers);
  9354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9355. EXPECT_EQ(StatusCode::OK_200, res->status);
  9356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9357. // Pre-compression logger should not be called when no compression is applied
  9358. EXPECT_TRUE(
  9359. pre_compression_body.empty()); // Pre-compression logger not called
  9360. EXPECT_EQ(
  9361. test_content,
  9362. post_compression_body); // Post-compression logger captures final content
  9363. }
  9364. TEST_F(ServerTest, LoggerSeesContentLength) {
  9365. size_t logged_content_length = 0;
  9366. std::string logged_content_length_header;
  9367. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9368. logged_content_length = res.content_length_;
  9369. logged_content_length_header = res.get_header_value("Content-Length");
  9370. });
  9371. auto res = cli_.Get("/nocompress");
  9372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9373. EXPECT_EQ(StatusCode::OK_200, res->status);
  9374. EXPECT_EQ(res->body.size(), logged_content_length);
  9375. EXPECT_EQ(std::to_string(logged_content_length),
  9376. logged_content_length_header);
  9377. }
  9378. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9379. const std::string test_content =
  9380. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9381. "3456789012345678901234567890";
  9382. std::string pre_compression_body;
  9383. bool pre_logger_called = false;
  9384. // Set only pre-compression logger
  9385. svr_.set_pre_compression_logger(
  9386. [&](const Request & /*req*/, const Response &res) {
  9387. pre_compression_body = res.body;
  9388. pre_logger_called = true;
  9389. });
  9390. Headers headers;
  9391. headers.emplace("Accept-Encoding", "gzip");
  9392. auto res = cli_.Get("/compress", headers);
  9393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9394. EXPECT_EQ(StatusCode::OK_200, res->status);
  9395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9396. // Verify pre-compression logger was called
  9397. EXPECT_TRUE(pre_logger_called);
  9398. EXPECT_EQ(test_content, pre_compression_body);
  9399. }
  9400. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9401. {
  9402. // Test with Expect: 100-continue header - success case
  9403. // Server returns 100 Continue, client sends body, server returns 200 OK
  9404. Request req;
  9405. req.method = "POST";
  9406. req.path = "/post-large";
  9407. req.set_header("Expect", "100-continue");
  9408. req.body = LARGE_DATA;
  9409. Response res;
  9410. auto error = Error::Success;
  9411. cli_.set_keep_alive(true);
  9412. auto ret = cli_.send(req, res, error);
  9413. EXPECT_TRUE(ret);
  9414. EXPECT_EQ(StatusCode::OK_200, res.status);
  9415. EXPECT_EQ(LARGE_DATA, res.body);
  9416. }
  9417. {
  9418. // Test with Expect: 100-continue header - error case
  9419. // Client should not send the body when server returns an error
  9420. Request req;
  9421. req.method = "POST";
  9422. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9423. req.set_header("Expect", "100-continue");
  9424. req.body = LARGE_DATA;
  9425. Response res;
  9426. auto error = Error::Success;
  9427. auto start = std::chrono::high_resolution_clock::now();
  9428. cli_.set_keep_alive(true);
  9429. auto ret = cli_.send(req, res, error);
  9430. auto end = std::chrono::high_resolution_clock::now();
  9431. auto elapsed =
  9432. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9433. .count();
  9434. // With Expect: 100-continue, request completes successfully but with error
  9435. EXPECT_TRUE(ret);
  9436. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9437. EXPECT_EQ("close", res.get_header_value("Connection"));
  9438. EXPECT_FALSE(cli_.is_socket_open());
  9439. EXPECT_LE(elapsed, 2000);
  9440. }
  9441. {
  9442. // Send an extra GET request to ensure error recovery without hanging
  9443. Request req;
  9444. req.method = "GET";
  9445. req.path = "/hi";
  9446. auto start = std::chrono::high_resolution_clock::now();
  9447. auto res = cli_.send(req);
  9448. auto end = std::chrono::high_resolution_clock::now();
  9449. auto elapsed =
  9450. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9451. .count();
  9452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9453. EXPECT_EQ(StatusCode::OK_200, res->status);
  9454. EXPECT_EQ("Hello World!", res->body);
  9455. EXPECT_LE(elapsed, 500);
  9456. }
  9457. }
  9458. TEST(ZstdDecompressor, ChunkedDecompression) {
  9459. std::string data;
  9460. for (size_t i = 0; i < 32 * 1024; ++i) {
  9461. data.push_back(static_cast<char>('a' + i % 26));
  9462. }
  9463. std::string compressed_data;
  9464. {
  9465. httplib::detail::zstd_compressor compressor;
  9466. bool result = compressor.compress(
  9467. data.data(), data.size(),
  9468. /*last=*/true,
  9469. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9470. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9471. compressed_data_size);
  9472. return true;
  9473. });
  9474. ASSERT_TRUE(result);
  9475. }
  9476. std::string decompressed_data;
  9477. {
  9478. httplib::detail::zstd_decompressor decompressor;
  9479. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9480. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9481. size_t chunk_size = 130;
  9482. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9483. chunk_begin += chunk_size) {
  9484. size_t current_chunk_size =
  9485. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9486. bool result = decompressor.decompress(
  9487. compressed_data.data() + chunk_begin, current_chunk_size,
  9488. [&](const char *decompressed_data_chunk,
  9489. size_t decompressed_data_chunk_size) {
  9490. decompressed_data.insert(decompressed_data.size(),
  9491. decompressed_data_chunk,
  9492. decompressed_data_chunk_size);
  9493. return true;
  9494. });
  9495. ASSERT_TRUE(result);
  9496. }
  9497. }
  9498. ASSERT_EQ(data, decompressed_data);
  9499. }
  9500. TEST(ZstdDecompressor, Decompress) {
  9501. std::string original_text = "Compressed with ZSTD";
  9502. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9503. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9504. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9505. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9506. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9507. std::string decompressed_data;
  9508. {
  9509. httplib::detail::zstd_decompressor decompressor;
  9510. bool result = decompressor.decompress(
  9511. compressed_data.data(), compressed_data.size(),
  9512. [&](const char *decompressed_data_chunk,
  9513. size_t decompressed_data_chunk_size) {
  9514. decompressed_data.insert(decompressed_data.size(),
  9515. decompressed_data_chunk,
  9516. decompressed_data_chunk_size);
  9517. return true;
  9518. });
  9519. ASSERT_TRUE(result);
  9520. }
  9521. ASSERT_EQ(original_text, decompressed_data);
  9522. }
  9523. #endif
  9524. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9525. // separate chunks so that the server sees each part in its own read(). Used to
  9526. // place a read boundary at a specific offset of a request body.
  9527. static bool send_request_in_parts(time_t read_timeout_sec,
  9528. const std::vector<std::string> &parts,
  9529. std::string *resp = nullptr,
  9530. int port = PORT) {
  9531. auto error = Error::Success;
  9532. auto client_sock = detail::create_client_socket(
  9533. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9534. /*connection_timeout_sec=*/5, 0,
  9535. /*read_timeout_sec=*/5, 0,
  9536. /*write_timeout_sec=*/5, 0, std::string(), error);
  9537. if (client_sock == INVALID_SOCKET) { return false; }
  9538. auto ret = detail::process_client_socket(
  9539. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9540. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9541. for (size_t i = 0; i < parts.size(); i++) {
  9542. const auto &part = parts[i];
  9543. if (part.size() !=
  9544. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9545. return false;
  9546. }
  9547. if (i + 1 < parts.size()) {
  9548. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9549. }
  9550. }
  9551. char buf[512];
  9552. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9553. while (line_reader.getline()) {
  9554. if (resp) { *resp += line_reader.ptr(); }
  9555. }
  9556. return true;
  9557. });
  9558. detail::close_socket(client_sock);
  9559. return ret;
  9560. }
  9561. // Sends a raw request to a server listening at HOST:PORT.
  9562. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9563. std::string *resp = nullptr, int port = PORT) {
  9564. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9565. }
  9566. #ifdef CPPHTTPLIB_SSL_ENABLED
  9567. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9569. ASSERT_TRUE(svr.is_valid());
  9570. svr.set_read_timeout(1, 0);
  9571. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9572. auto se = detail::scope_exit([&] {
  9573. svr.stop();
  9574. t.join();
  9575. ASSERT_FALSE(svr.is_running());
  9576. });
  9577. svr.wait_until_ready();
  9578. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9579. // keeps each wait well within the read timeout. The server gives up a
  9580. // second in, so the bytes sent after that fail.
  9581. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9582. parts.resize(26, std::string(1, '\0'));
  9583. EXPECT_FALSE(send_request_in_parts(5, parts));
  9584. }
  9585. #endif
  9586. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9587. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9588. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9589. const std::vector<std::string> &parts,
  9590. std::string *resp = nullptr,
  9591. int port = PORT) {
  9592. auto error = Error::Success;
  9593. auto sock = detail::create_client_socket(
  9594. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9595. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9596. /*write_timeout_sec=*/5, 0, std::string(), error);
  9597. if (sock == INVALID_SOCKET) { return false; }
  9598. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9599. auto ctx = SSL_CTX_new(TLS_client_method());
  9600. auto ssl = SSL_new(ctx);
  9601. auto ssl_se = detail::scope_exit([&] {
  9602. SSL_free(ssl);
  9603. SSL_CTX_free(ctx);
  9604. });
  9605. SSL_set_fd(ssl, static_cast<int>(sock));
  9606. if (SSL_connect(ssl) != 1) { return false; }
  9607. for (size_t i = 0; i < parts.size(); i++) {
  9608. const auto &part = parts[i];
  9609. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9610. static_cast<int>(part.size())) {
  9611. return false;
  9612. }
  9613. if (i + 1 < parts.size()) {
  9614. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9615. }
  9616. }
  9617. char buf[512];
  9618. int n;
  9619. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9620. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9621. }
  9622. return true;
  9623. }
  9624. #endif
  9625. // The request line, then a header value a byte at a time.
  9626. static std::vector<std::string> slow_request_head_parts() {
  9627. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9628. parts.resize(26, "a");
  9629. parts.emplace_back("\r\n\r\n");
  9630. return parts;
  9631. }
  9632. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9633. // within the one-second read timeout. The server gives up a second in, before
  9634. // the head is complete.
  9635. static void
  9636. expect_slow_request_head_dropped(Server &svr,
  9637. const std::function<std::string()> &send) {
  9638. std::atomic<bool> handled(false);
  9639. svr.Get("/", [&](const Request &, Response &res) {
  9640. handled = true;
  9641. res.set_content("ok", "text/plain");
  9642. });
  9643. svr.set_read_timeout(1, 0);
  9644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9645. auto se = detail::scope_exit([&] {
  9646. svr.stop();
  9647. t.join();
  9648. ASSERT_FALSE(svr.is_running());
  9649. });
  9650. svr.wait_until_ready();
  9651. auto resp = send();
  9652. EXPECT_FALSE(handled);
  9653. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9654. }
  9655. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9656. Server svr;
  9657. expect_slow_request_head_dropped(svr, [] {
  9658. std::string resp;
  9659. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9660. return resp;
  9661. });
  9662. }
  9663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9664. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9666. ASSERT_TRUE(svr.is_valid());
  9667. expect_slow_request_head_dropped(svr, [] {
  9668. std::string resp;
  9669. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9670. return resp;
  9671. });
  9672. }
  9673. #endif
  9674. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9675. Server svr;
  9676. std::string header_value;
  9677. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9678. header_value = req.get_header_value("foo");
  9679. res.set_content("ok", "text/plain");
  9680. });
  9681. thread t = thread([&] { svr.listen(HOST, PORT); });
  9682. auto se = detail::scope_exit([&] {
  9683. svr.stop();
  9684. t.join();
  9685. ASSERT_FALSE(svr.is_running());
  9686. });
  9687. svr.wait_until_ready();
  9688. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9689. // like characters are not treated the same - use vertical tab and escape.
  9690. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9691. "foo: \t \v bar \x1B\t \r\n"
  9692. "Connection: close\r\n"
  9693. "\r\n";
  9694. std::string res;
  9695. ASSERT_TRUE(send_request(5, req, &res));
  9696. EXPECT_EQ(header_value, "");
  9697. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9698. }
  9699. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9700. Server svr;
  9701. std::string received;
  9702. svr.Get("/order", [&](const Request &req, Response &res) {
  9703. received = entries_to_string(req.headers);
  9704. res.set_content("ok", "text/plain");
  9705. });
  9706. auto port = svr.bind_to_any_port(HOST);
  9707. thread t = thread([&] { svr.listen_after_bind(); });
  9708. auto se = detail::scope_exit([&] {
  9709. svr.stop();
  9710. t.join();
  9711. ASSERT_FALSE(svr.is_running());
  9712. });
  9713. svr.wait_until_ready();
  9714. const std::string req = "GET /order HTTP/1.1\r\n"
  9715. "Host: localhost\r\n"
  9716. "X-First: 1\r\n"
  9717. "X-Dup: a\r\n"
  9718. "X-Second: 2\r\n"
  9719. "X-Dup: b\r\n"
  9720. "Connection: close\r\n"
  9721. "\r\n";
  9722. std::string res;
  9723. ASSERT_TRUE(send_request(5, req, &res, port));
  9724. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9725. EXPECT_EQ(
  9726. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9727. received);
  9728. }
  9729. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9730. Server svr;
  9731. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9732. res.set_header("Set-Cookie", "first=1");
  9733. res.set_header("X-Between", "y");
  9734. res.set_header("Set-Cookie", "second=2");
  9735. res.set_content("ok", "text/plain");
  9736. });
  9737. auto port = svr.bind_to_any_port(HOST);
  9738. thread t = thread([&] { svr.listen_after_bind(); });
  9739. auto se = detail::scope_exit([&] {
  9740. svr.stop();
  9741. t.join();
  9742. ASSERT_FALSE(svr.is_running());
  9743. });
  9744. svr.wait_until_ready();
  9745. Client cli(HOST, port);
  9746. auto res = cli.Get("/cookies");
  9747. ASSERT_TRUE(res);
  9748. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9749. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9750. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9751. }
  9752. // A stream may send a byte at a time with a small extension on each chunk,
  9753. // however long it runs
  9754. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9755. Server svr;
  9756. svr.Post("/count", [](const Request &req, Response &res) {
  9757. res.set_content(std::to_string(req.body.size()), "text/plain");
  9758. });
  9759. auto port = svr.bind_to_any_port(HOST);
  9760. ASSERT_LT(0, port);
  9761. thread t = thread([&] { svr.listen_after_bind(); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. t.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. });
  9767. svr.wait_until_ready();
  9768. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9769. "\r\nTransfer-Encoding: chunked\r\n"
  9770. "Connection: close\r\n\r\n";
  9771. for (auto i = 0; i < 4096; i++) {
  9772. req += "1;a=b\r\nx\r\n";
  9773. }
  9774. req += "0\r\n\r\n";
  9775. std::string res;
  9776. ASSERT_TRUE(send_request(5, req, &res, port));
  9777. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9778. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9779. }
  9780. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9781. Server svr;
  9782. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9783. auto i = new int(0);
  9784. res.set_header("Trailer", "X-Safe, X-Reflected");
  9785. res.set_chunked_content_provider(
  9786. "text/plain",
  9787. [i](size_t /*offset*/, DataSink &sink) {
  9788. if (*i == 0) {
  9789. sink.os << "body";
  9790. } else {
  9791. Headers trailer;
  9792. // A valid trailer that must survive.
  9793. trailer.emplace("X-Safe", "safe");
  9794. // Attacker-controlled value carrying CR/LF (response splitting).
  9795. trailer.emplace("X-Reflected",
  9796. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9797. // Attacker-controlled name carrying CR/LF.
  9798. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9799. sink.done_with_trailer(trailer);
  9800. }
  9801. (*i)++;
  9802. return true;
  9803. },
  9804. [i](bool /*success*/) { delete i; });
  9805. });
  9806. thread t = thread([&] { svr.listen(HOST, PORT); });
  9807. auto se = detail::scope_exit([&] {
  9808. svr.stop();
  9809. t.join();
  9810. ASSERT_FALSE(svr.is_running());
  9811. });
  9812. svr.wait_until_ready();
  9813. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9814. "Host: " + HOST +
  9815. "\r\n"
  9816. "Connection: close\r\n"
  9817. "\r\n";
  9818. std::string res;
  9819. ASSERT_TRUE(send_request(5, req, &res));
  9820. // The injected fields must not appear anywhere in the raw response.
  9821. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9822. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9823. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9824. // Invalid trailers are dropped entirely, matching set_header().
  9825. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9826. // The valid trailer still passes through.
  9827. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9828. }
  9829. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9830. // A custom header writer gets only the fields the default one writes
  9831. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9832. std::string s;
  9833. for (const auto &h : hdrs) {
  9834. s += h.first + ": " + h.second + "\r\n";
  9835. }
  9836. s += "\r\n";
  9837. return strm.write(s.data(), s.size());
  9838. };
  9839. for (auto custom_writer : {false, true}) {
  9840. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9841. Server svr;
  9842. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9843. svr.set_post_routing_handler([](const Request &, Response &res) {
  9844. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9845. });
  9846. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9847. // res.headers is a public field an application can populate directly,
  9848. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9849. // A valid header that must survive.
  9850. res.headers.emplace("X-Safe", "safe");
  9851. // Attacker-controlled value carrying CR/LF (response splitting).
  9852. res.headers.emplace("X-Reflected",
  9853. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9854. // Attacker-controlled name carrying CR/LF.
  9855. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9856. res.set_content("body", "text/plain");
  9857. });
  9858. thread t = thread([&] { svr.listen(HOST, PORT); });
  9859. auto se = detail::scope_exit([&] {
  9860. svr.stop();
  9861. t.join();
  9862. ASSERT_FALSE(svr.is_running());
  9863. });
  9864. svr.wait_until_ready();
  9865. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9866. "Host: " + HOST +
  9867. "\r\n"
  9868. "Connection: close\r\n"
  9869. "\r\n";
  9870. std::string res;
  9871. ASSERT_TRUE(send_request(5, req, &res));
  9872. // The injected fields must not appear anywhere in the raw response.
  9873. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9874. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9875. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9876. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9877. // Invalid headers are dropped entirely, matching set_header().
  9878. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9879. // The valid header still passes through.
  9880. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9881. }
  9882. }
  9883. // Forward declaration: in split builds split.py strips `inline` and moves the
  9884. // definition into httplib.cc, so detail::write_request_line is not visible from
  9885. // the public httplib.h. Re-declaring it here lets the tests link against the
  9886. // symbol in both header-only and split builds.
  9887. namespace httplib {
  9888. namespace detail {
  9889. ssize_t write_request_line(Stream &strm, const std::string &method,
  9890. const std::string &path);
  9891. } // namespace detail
  9892. } // namespace httplib
  9893. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9894. // A well-formed target is written verbatim.
  9895. {
  9896. detail::BufferStream strm;
  9897. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9898. EXPECT_GT(n, 0);
  9899. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9900. }
  9901. // A target carrying CR/LF, SP or other control octets must be rejected
  9902. // before anything reaches the wire, otherwise it splits the request line and
  9903. // injects a header or a whole request.
  9904. const std::string evil_targets[] = {
  9905. "/a\r\nInjected: pwned",
  9906. "/a\rInjected",
  9907. "/a\nInjected",
  9908. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9909. "/a b",
  9910. "/a\tb",
  9911. "/a\x7f",
  9912. };
  9913. for (const auto &evil : evil_targets) {
  9914. detail::BufferStream strm;
  9915. auto n = detail::write_request_line(strm, "GET", evil);
  9916. EXPECT_LT(n, 0);
  9917. EXPECT_TRUE(strm.get_buffer().empty());
  9918. }
  9919. }
  9920. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9921. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9922. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9923. // target reaches write_request. The client must fail cleanly with
  9924. // Error::Write instead of putting a request-line-less, header-injecting
  9925. // request on the wire.
  9926. Server svr;
  9927. svr.Get("/a", [](const Request &, Response &res) {
  9928. res.set_content("ok", "text/plain");
  9929. });
  9930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9931. auto se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. thread.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. });
  9936. svr.wait_until_ready();
  9937. {
  9938. Client cli(HOST, PORT);
  9939. cli.set_path_encode(false);
  9940. // The request is rejected before anything is written, so the connection
  9941. // stays silent and the subsequent response read would otherwise block for
  9942. // the full default read timeout. Shorten it -- the assertion is on the
  9943. // error, not the timeout.
  9944. cli.set_read_timeout(1, 0);
  9945. auto res = cli.Get("/a\r\nInjected: pwned");
  9946. EXPECT_FALSE(res);
  9947. EXPECT_EQ(Error::Write, res.error());
  9948. }
  9949. }
  9950. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9951. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9952. // including extension methods.
  9953. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9954. for (const auto &method : good_methods) {
  9955. detail::BufferStream strm;
  9956. auto n = detail::write_request_line(strm, method, "/");
  9957. EXPECT_GT(n, 0);
  9958. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9959. }
  9960. // A method carrying CR/LF would split the request line and smuggle a whole
  9961. // request ahead of the real one. A space or an empty method corrupts the
  9962. // request line. All must be rejected before anything reaches the wire.
  9963. const std::string evil_methods[] = {
  9964. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9965. "GET\r\nInjected: pwned",
  9966. "GET\r",
  9967. "GET\n",
  9968. "GE T",
  9969. "",
  9970. };
  9971. for (const auto &evil : evil_methods) {
  9972. detail::BufferStream strm;
  9973. auto n = detail::write_request_line(strm, evil, "/");
  9974. EXPECT_LT(n, 0);
  9975. EXPECT_TRUE(strm.get_buffer().empty());
  9976. }
  9977. }
  9978. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9979. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9980. // through Client::send must fail with Error::Write and no request, neither
  9981. // the smuggled one nor the real one, may reach the server.
  9982. Server svr;
  9983. std::atomic<int> request_count(0);
  9984. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9985. request_count++;
  9986. res.status = StatusCode::OK_200;
  9987. return Server::HandlerResponse::Handled;
  9988. });
  9989. auto port = svr.bind_to_any_port(HOST);
  9990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. thread.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. {
  9998. Client cli(HOST, port);
  9999. const std::string evil_methods[] = {
  10000. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10001. "GE T",
  10002. "",
  10003. };
  10004. for (const auto &evil : evil_methods) {
  10005. Request req;
  10006. req.method = evil;
  10007. req.path = "/";
  10008. auto res = cli.send(req);
  10009. EXPECT_FALSE(res);
  10010. EXPECT_EQ(Error::Write, res.error());
  10011. }
  10012. auto handle =
  10013. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10014. EXPECT_FALSE(handle.is_valid());
  10015. EXPECT_EQ(Error::Write, handle.error);
  10016. // A valid request on the same client still goes through.
  10017. auto res = cli.Get("/");
  10018. ASSERT_TRUE(res);
  10019. EXPECT_EQ(StatusCode::OK_200, res->status);
  10020. }
  10021. EXPECT_EQ(1, request_count.load());
  10022. }
  10023. // Sends a raw request and verifies that there isn't a crash or exception.
  10024. static void test_raw_request(const std::string &req,
  10025. std::string *out = nullptr) {
  10026. Server svr;
  10027. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10028. res.set_content("ok", "text/plain");
  10029. });
  10030. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10031. res.set_content("ok", "text/plain");
  10032. });
  10033. svr.Get("/header_field_value_check",
  10034. [&](const Request & /*req*/, Response &res) {
  10035. res.set_content("ok", "text/plain");
  10036. });
  10037. svr.CustomRoute("PROPFIND", "/dav",
  10038. [&](const Request & /*req*/, Response &res) {
  10039. res.status = StatusCode::MultiStatus_207;
  10040. });
  10041. // Server read timeout must be longer than the client read timeout for the
  10042. // bug to reproduce, probably to force the server to process a request
  10043. // without a trailing blank line.
  10044. const time_t client_read_timeout_sec = 1;
  10045. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10046. bool listen_thread_ok = false;
  10047. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10048. auto se = detail::scope_exit([&] {
  10049. svr.stop();
  10050. t.join();
  10051. ASSERT_FALSE(svr.is_running());
  10052. EXPECT_TRUE(listen_thread_ok);
  10053. });
  10054. svr.wait_until_ready();
  10055. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10056. }
  10057. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10058. // A certain header line causes an exception if the header property is parsed
  10059. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10060. test_raw_request(
  10061. "GET /hi HTTP/1.1\r\n"
  10062. " : "
  10063. " "
  10064. " ");
  10065. }
  10066. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10067. // A certain header line causes an exception if the header property *name* is
  10068. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10069. // greedy matcher and requires backtracking when there are a lot of ":"
  10070. // characters.
  10071. // This occurs with libc++ but not libstdc++.
  10072. test_raw_request(
  10073. "GET /hi HTTP/1.1\r\n"
  10074. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10075. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10076. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10077. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10078. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10079. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10080. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10081. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10082. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10083. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10084. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10085. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10086. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10087. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10088. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10089. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10090. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10091. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10092. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10093. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10094. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10095. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10096. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10097. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10098. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10099. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10100. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10101. "&&&%%%");
  10102. }
  10103. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10104. // Make sure this doesn't crash the server.
  10105. // In a previous version of the header line regex, the "\r" rendered the line
  10106. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10107. // a new position where the leading white space ended and the field value
  10108. // began.
  10109. // The crash occurs with libc++ but not libstdc++.
  10110. test_raw_request("GET /hi HTTP/1.1\r\n"
  10111. "a:" +
  10112. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10113. "\r\n"
  10114. "\r\n");
  10115. }
  10116. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10117. const char *rejected[] = {
  10118. // RFC 9112 §3: one SP between the parts, and nothing else
  10119. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10120. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10121. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10122. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10123. // A request-target has no fragment
  10124. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10125. // An HTTP/1.1 request needs a Host
  10126. "GET /hi HTTP/1.1\r\n\r\n",
  10127. };
  10128. for (auto request : rejected) {
  10129. std::string out;
  10130. test_raw_request(request, &out);
  10131. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10132. }
  10133. std::string out;
  10134. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10135. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10136. }
  10137. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10138. // RFC 9112 §6.1
  10139. const char *requests[] = {
  10140. "PUT /put_hi HTTP/1.1\r\n"
  10141. "Host: localhost\r\n"
  10142. "Content-Length: 0\r\n"
  10143. "Transfer-Encoding: chunked\r\n"
  10144. "\r\n"
  10145. "0\r\n\r\n",
  10146. "PUT /put_hi HTTP/1.0\r\n"
  10147. "Connection: keep-alive\r\n"
  10148. "Transfer-Encoding: chunked\r\n"
  10149. "\r\n"
  10150. "0\r\n\r\n",
  10151. };
  10152. for (auto request : requests) {
  10153. std::string out;
  10154. test_raw_request(request, &out);
  10155. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10156. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10157. }
  10158. }
  10159. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10160. std::string out;
  10161. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10162. "Content-Type: text/plain\r\n"
  10163. "Transfer-Encoding: chunked\r\n"
  10164. "\r\n"
  10165. "nothex\r\n",
  10166. &out);
  10167. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10168. }
  10169. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10170. std::string out;
  10171. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10172. "Content-Type: text/plain\r\n"
  10173. "Transfer-Encoding: chunked\r\n"
  10174. "\r\n"
  10175. "3\r\n"
  10176. "xyz\r\n"
  10177. "NaN\r\n",
  10178. &out);
  10179. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10180. }
  10181. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10182. std::string out;
  10183. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10184. "Content-Type: text/plain\r\n"
  10185. "Transfer-Encoding: chunked\r\n"
  10186. "\r\n"
  10187. // Length is too large for 64 bits.
  10188. "1ffffffffffffffff\r\n"
  10189. "xyz\r\n",
  10190. &out);
  10191. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10192. }
  10193. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10194. test_raw_request("GET /hi HTTP/1.1\r\n"
  10195. "Content-Type: text/plain\r\n\r");
  10196. }
  10197. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10198. std::string out;
  10199. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10200. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10201. }
  10202. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10203. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10204. std::string out;
  10205. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10206. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10207. }
  10208. }
  10209. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10210. std::string out;
  10211. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10212. "Host: localhost\r\n"
  10213. "Connection: close\r\n\r\n",
  10214. &out);
  10215. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10216. }
  10217. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10218. Server svr;
  10219. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10220. EXPECT_TRUE(!req.remote_addr.empty());
  10221. });
  10222. thread t = thread([&] { svr.listen(HOST, PORT); });
  10223. auto se = detail::scope_exit([&] {
  10224. svr.stop();
  10225. t.join();
  10226. ASSERT_FALSE(svr.is_running());
  10227. });
  10228. svr.wait_until_ready();
  10229. // Send an invalid request line to trigger Bad Request
  10230. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10231. std::string out;
  10232. ASSERT_TRUE(send_request(5, bad_req, &out));
  10233. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10234. }
  10235. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10236. // answered right away rather than blocking on a read that waits for EOF.
  10237. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10238. std::string out;
  10239. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10240. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10241. }
  10242. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10243. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10244. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10245. for (const auto *method : methods) {
  10246. Server svr;
  10247. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10248. EXPECT_FALSE(svr.is_valid()) << method;
  10249. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10250. }
  10251. }
  10252. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10253. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10254. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10255. for (const auto *method : methods) {
  10256. Server svr;
  10257. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10258. EXPECT_FALSE(svr.is_valid()) << method;
  10259. }
  10260. }
  10261. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10262. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10263. "COPY", "MOVE", "LOCK",
  10264. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10265. Server svr;
  10266. for (const auto *method : methods) {
  10267. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10268. }
  10269. EXPECT_TRUE(svr.is_valid());
  10270. }
  10271. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10272. Server svr;
  10273. svr.CustomRoute("POST", "/x",
  10274. [](const Request &, Response &, const ContentReader &) {});
  10275. EXPECT_FALSE(svr.is_valid());
  10276. }
  10277. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10278. Server svr;
  10279. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10280. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10281. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10282. EXPECT_FALSE(svr.is_valid());
  10283. }
  10284. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10285. Server svr;
  10286. auto captured = Error::Success;
  10287. svr.set_error_logger(
  10288. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10289. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10290. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10291. }
  10292. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10293. std::string out;
  10294. std::string request(
  10295. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10296. test_raw_request(request, &out);
  10297. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10298. }
  10299. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10300. std::string out;
  10301. std::string request(
  10302. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10303. test_raw_request(request, &out);
  10304. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10305. }
  10306. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10307. std::string out;
  10308. std::string request(
  10309. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10310. test_raw_request(request, &out);
  10311. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10312. }
  10313. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10314. std::string out;
  10315. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10316. "Host: localhost\r\n"
  10317. "Test: \r\n\r\n",
  10318. &out);
  10319. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10320. }
  10321. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10322. Server svr;
  10323. std::string x_custom;
  10324. std::string cookie;
  10325. std::string xff;
  10326. std::string x_unicode;
  10327. std::string x_iis;
  10328. svr.Get("/check", [&](const Request &req, Response &res) {
  10329. x_custom = req.get_header_value("X-Custom");
  10330. cookie = req.get_header_value("Cookie");
  10331. xff = req.get_header_value("X-Forwarded-For");
  10332. x_unicode = req.get_header_value("X-Unicode");
  10333. x_iis = req.get_header_value("X-IIS");
  10334. res.set_content("ok", "text/plain");
  10335. });
  10336. thread t = thread([&] { svr.listen(HOST, PORT); });
  10337. auto se = detail::scope_exit([&] {
  10338. svr.stop();
  10339. t.join();
  10340. ASSERT_FALSE(svr.is_running());
  10341. });
  10342. svr.wait_until_ready();
  10343. const std::string req = "GET /check HTTP/1.1\r\n"
  10344. "Host: localhost\r\n"
  10345. "X-Custom: a%0D%0AInjected: b\r\n"
  10346. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10347. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10348. "X-Unicode: %E3%81%82\r\n"
  10349. "X-IIS: %u00E9\r\n"
  10350. "Connection: close\r\n"
  10351. "\r\n";
  10352. std::string res;
  10353. ASSERT_TRUE(send_request(5, req, &res));
  10354. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10355. // Every value must be returned verbatim (wire form), with no decoding.
  10356. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10357. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10358. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10359. EXPECT_EQ("%E3%81%82", x_unicode);
  10360. EXPECT_EQ("%u00E9", x_iis);
  10361. }
  10362. // Applications that previously relied on automatic percent-decoding can
  10363. // reproduce the old behavior by explicitly calling decode_path_component()
  10364. // or, for RFC 3986 conformance, decode_uri_component().
  10365. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10366. Server svr;
  10367. std::string decoded;
  10368. svr.Get("/check", [&](const Request &req, Response &res) {
  10369. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10370. res.set_content("ok", "text/plain");
  10371. });
  10372. thread t = thread([&] { svr.listen(HOST, PORT); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. t.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. const std::string req = "GET /check HTTP/1.1\r\n"
  10380. "Host: localhost\r\n"
  10381. "X-Custom: hello%20world\r\n"
  10382. "Connection: close\r\n"
  10383. "\r\n";
  10384. std::string res;
  10385. ASSERT_TRUE(send_request(5, req, &res));
  10386. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10387. EXPECT_EQ("hello world", decoded);
  10388. }
  10389. // Regression test for #2033. Browsers send Referer values that include
  10390. // percent-encoded characters such as %0A inside the URL. Decoding the
  10391. // header value would either trip the post-decode CR/LF/NUL guard (the
  10392. // original bug, returning 400) or, after that guard was relaxed, silently
  10393. // store a literal LF — both unacceptable. The wire form must round-trip.
  10394. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10395. Server svr;
  10396. std::string referer;
  10397. svr.Get("/check", [&](const Request &req, Response &res) {
  10398. referer = req.get_header_value("Referer");
  10399. res.set_content("ok", "text/plain");
  10400. });
  10401. thread t = thread([&] { svr.listen(HOST, PORT); });
  10402. auto se = detail::scope_exit([&] {
  10403. svr.stop();
  10404. t.join();
  10405. ASSERT_FALSE(svr.is_running());
  10406. });
  10407. svr.wait_until_ready();
  10408. const std::string req = "GET /check HTTP/1.1\r\n"
  10409. "Host: localhost\r\n"
  10410. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10411. "Connection: close\r\n"
  10412. "\r\n";
  10413. std::string res;
  10414. ASSERT_TRUE(send_request(5, req, &res));
  10415. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10416. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10417. }
  10418. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10419. Server svr;
  10420. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10421. res.set_header("Cache-Control", "no-cache");
  10422. res.set_chunked_content_provider(
  10423. "text/event-stream", [](size_t offset, DataSink &sink) {
  10424. std::string s = "data:";
  10425. s += std::to_string(offset);
  10426. s += "\n\n";
  10427. auto ret = sink.write(s.data(), s.size());
  10428. EXPECT_TRUE(ret);
  10429. std::this_thread::sleep_for(std::chrono::seconds(1));
  10430. return true;
  10431. });
  10432. });
  10433. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10434. svr.wait_until_ready();
  10435. Client client(HOST, PORT);
  10436. const Headers headers = {{"Accept", "text/event-stream"}};
  10437. auto get_thread = std::thread([&client, &headers]() {
  10438. auto res = client.Get(
  10439. "/events", headers,
  10440. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10441. });
  10442. auto se = detail::scope_exit([&] {
  10443. svr.stop();
  10444. get_thread.join();
  10445. listen_thread.join();
  10446. ASSERT_FALSE(svr.is_running());
  10447. });
  10448. // Give GET time to get a few messages.
  10449. std::this_thread::sleep_for(std::chrono::seconds(2));
  10450. }
  10451. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10452. httplib::Server svr;
  10453. svr.Post("/hi",
  10454. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10455. res.status = StatusCode::OK_200;
  10456. });
  10457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10458. svr.wait_until_ready();
  10459. Client cli(HOST, PORT);
  10460. auto res = cli.Post("/hi", "data", "text/plain");
  10461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10462. EXPECT_EQ(StatusCode::OK_200, res->status);
  10463. svr.stop();
  10464. thread.join();
  10465. ASSERT_FALSE(svr.is_running());
  10466. res = cli.Post("/hi", "data", "text/plain");
  10467. ASSERT_FALSE(res);
  10468. }
  10469. TEST(ServerStopTest, ListenFailure) {
  10470. Server svr;
  10471. auto t = thread([&]() {
  10472. auto ret = svr.listen("????", PORT);
  10473. EXPECT_FALSE(ret);
  10474. });
  10475. svr.wait_until_ready();
  10476. svr.stop();
  10477. t.join();
  10478. }
  10479. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10480. TEST(ServerStopTest, Decommision) {
  10481. Server svr;
  10482. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10483. for (int i = 0; i < 4; i++) {
  10484. auto is_even = !(i % 2);
  10485. std::thread t{[&] {
  10486. try {
  10487. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10488. if (is_even) {
  10489. throw std::runtime_error("Some thing that happens to go wrong.");
  10490. }
  10491. svr.listen(HOST, PORT);
  10492. } catch (...) { svr.decommission(); }
  10493. }};
  10494. svr.wait_until_ready();
  10495. // Server is up
  10496. {
  10497. Client cli(HOST, PORT);
  10498. auto res = cli.Get("/hi");
  10499. if (is_even) {
  10500. EXPECT_FALSE(res);
  10501. } else {
  10502. EXPECT_TRUE(res);
  10503. EXPECT_EQ("hi...", res->body);
  10504. }
  10505. }
  10506. svr.stop();
  10507. t.join();
  10508. // Server is down...
  10509. {
  10510. Client cli(HOST, PORT);
  10511. auto res = cli.Get("/hi");
  10512. EXPECT_FALSE(res);
  10513. }
  10514. }
  10515. }
  10516. #endif
  10517. // Helper function for string body upload progress tests
  10518. template <typename SetupHandler, typename ClientCall>
  10519. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10520. ClientCall &&client_call,
  10521. const string &body) {
  10522. Server svr;
  10523. setup_handler(svr);
  10524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10525. auto se = detail::scope_exit([&] {
  10526. svr.stop();
  10527. t.join();
  10528. });
  10529. svr.wait_until_ready();
  10530. Client cli(HOST, PORT);
  10531. vector<uint64_t> progress_values;
  10532. bool progress_called = false;
  10533. auto res =
  10534. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10535. progress_values.push_back(current);
  10536. progress_called = true;
  10537. return true;
  10538. });
  10539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10540. EXPECT_EQ(200, res->status);
  10541. EXPECT_TRUE(progress_called);
  10542. }
  10543. TEST(UploadProgressTest, PostStringBodyBasic) {
  10544. TestStringBodyUploadProgress(
  10545. [](Server &svr) {
  10546. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10547. res.set_content("received", "text/plain");
  10548. });
  10549. },
  10550. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10551. return cli.Post("/test", body, "text/plain", progress_callback);
  10552. },
  10553. "test data for upload progress");
  10554. }
  10555. TEST(UploadProgressTest, PutStringBodyBasic) {
  10556. TestStringBodyUploadProgress(
  10557. [](Server &svr) {
  10558. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10559. res.set_content("put received", "text/plain");
  10560. });
  10561. },
  10562. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10563. return cli.Put("/test", body, "text/plain", progress_callback);
  10564. },
  10565. "put test data for upload progress");
  10566. }
  10567. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10568. TestStringBodyUploadProgress(
  10569. [](Server &svr) {
  10570. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10571. res.set_content("patch received", "text/plain");
  10572. });
  10573. },
  10574. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10575. return cli.Patch("/test", body, "text/plain", progress_callback);
  10576. },
  10577. "patch test data for upload progress");
  10578. }
  10579. // Helper function for content provider upload progress tests
  10580. template <typename SetupHandler, typename ClientCall>
  10581. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10582. ClientCall &&client_call) {
  10583. Server svr;
  10584. setup_handler(svr);
  10585. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. t.join();
  10589. });
  10590. svr.wait_until_ready();
  10591. Client cli(HOST, PORT);
  10592. vector<uint64_t> progress_values;
  10593. auto res =
  10594. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10595. progress_values.push_back(current);
  10596. return true;
  10597. });
  10598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10599. EXPECT_EQ(200, res->status);
  10600. EXPECT_FALSE(progress_values.empty());
  10601. }
  10602. TEST(UploadProgressTest, PostContentProviderProgress) {
  10603. TestContentProviderUploadProgress(
  10604. [](Server &svr) {
  10605. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10606. res.set_content("provider received", "text/plain");
  10607. });
  10608. },
  10609. [](Client &cli, UploadProgress progress_callback) {
  10610. return cli.Post(
  10611. "/test", 9,
  10612. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10613. sink.os << "test data";
  10614. return true;
  10615. },
  10616. "text/plain", progress_callback);
  10617. });
  10618. }
  10619. // Helper function for multipart upload progress tests
  10620. template <typename SetupHandler, typename ClientCall>
  10621. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10622. ClientCall &&client_call,
  10623. const string &endpoint) {
  10624. Server svr;
  10625. setup_handler(svr);
  10626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. });
  10631. svr.wait_until_ready();
  10632. Client cli(HOST, PORT);
  10633. vector<uint64_t> progress_values;
  10634. UploadFormDataItems items = {
  10635. {"field1", "value1", "", ""},
  10636. {"field2", "longer value for progress tracking test", "", ""},
  10637. {"file1", "file content data for upload progress", "test.txt",
  10638. "text/plain"}};
  10639. auto res = client_call(cli, endpoint, items,
  10640. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10641. progress_values.push_back(current);
  10642. return true;
  10643. });
  10644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10645. EXPECT_EQ(200, res->status);
  10646. EXPECT_FALSE(progress_values.empty());
  10647. }
  10648. TEST(UploadProgressTest, PostMultipartProgress) {
  10649. TestMultipartUploadProgress(
  10650. [](Server &svr) {
  10651. svr.Post("/multipart", [](const Request &req, Response &res) {
  10652. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10653. res.set_content("multipart received", "text/plain");
  10654. });
  10655. },
  10656. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10657. UploadProgress progress_callback) {
  10658. return cli.Post(endpoint, items, progress_callback);
  10659. },
  10660. "/multipart");
  10661. }
  10662. // Helper function for basic download progress tests
  10663. template <typename SetupHandler, typename ClientCall>
  10664. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10665. ClientCall &&client_call, const string &endpoint,
  10666. size_t expected_content_size) {
  10667. Server svr;
  10668. setup_handler(svr);
  10669. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10670. auto se = detail::scope_exit([&] {
  10671. svr.stop();
  10672. t.join();
  10673. });
  10674. svr.wait_until_ready();
  10675. Client cli(HOST, PORT);
  10676. vector<uint64_t> progress_values;
  10677. auto res = client_call(cli, endpoint,
  10678. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10679. progress_values.push_back(current);
  10680. return true;
  10681. });
  10682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10683. EXPECT_EQ(200, res->status);
  10684. EXPECT_FALSE(progress_values.empty());
  10685. EXPECT_EQ(expected_content_size, res->body.size());
  10686. }
  10687. TEST(DownloadProgressTest, GetBasic) {
  10688. TestBasicDownloadProgress(
  10689. [](Server &svr) {
  10690. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10691. string content(1000, 'D');
  10692. res.set_content(content, "text/plain");
  10693. });
  10694. },
  10695. [](Client &cli, const string &endpoint,
  10696. DownloadProgress progress_callback) {
  10697. return cli.Get(endpoint, progress_callback);
  10698. },
  10699. "/download", 1000u);
  10700. }
  10701. // Helper function for content receiver download progress tests
  10702. template <typename SetupHandler, typename ClientCall>
  10703. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10704. ClientCall &&client_call,
  10705. const string &endpoint,
  10706. size_t expected_content_size) {
  10707. Server svr;
  10708. setup_handler(svr);
  10709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. t.join();
  10713. });
  10714. svr.wait_until_ready();
  10715. Client cli(HOST, PORT);
  10716. vector<uint64_t> progress_values;
  10717. string received_body;
  10718. auto res = client_call(
  10719. cli, endpoint,
  10720. [&](const char *data, size_t data_length) -> bool {
  10721. received_body.append(data, data_length);
  10722. return true;
  10723. },
  10724. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10725. progress_values.push_back(current);
  10726. return true;
  10727. });
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_EQ(200, res->status);
  10730. EXPECT_FALSE(progress_values.empty());
  10731. EXPECT_EQ(expected_content_size, received_body.size());
  10732. EXPECT_TRUE(res->body.empty());
  10733. }
  10734. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10735. TestContentReceiverDownloadProgress(
  10736. [](Server &svr) {
  10737. svr.Get("/download-receiver",
  10738. [](const Request & /*req*/, Response &res) {
  10739. string content(2000, 'R');
  10740. res.set_content(content, "text/plain");
  10741. });
  10742. },
  10743. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10744. DownloadProgress progress_callback) {
  10745. return cli.Get(endpoint, content_receiver, progress_callback);
  10746. },
  10747. "/download-receiver", 2000u);
  10748. }
  10749. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10750. // A provider reaching a pass with nothing to hand over - an empty buffer
  10751. // popped off a queue, say - must not be taken to mean the body is finished.
  10752. // It used to end the loop with the terminating chunk unwritten while the
  10753. // server still considered the response complete, so the peer waited for an
  10754. // end that never arrived.
  10755. Server svr;
  10756. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10757. auto step = std::make_shared<int>(0);
  10758. res.set_chunked_content_provider("text/plain",
  10759. [step](size_t /*offset*/, DataSink &sink) {
  10760. switch ((*step)++) {
  10761. case 0: sink.write("", 0); break;
  10762. case 1: sink.write("hello", 5); break;
  10763. default: sink.done(); break;
  10764. }
  10765. return true;
  10766. });
  10767. });
  10768. auto port = svr.bind_to_any_port(HOST);
  10769. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10770. auto listen_se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli(HOST, port);
  10777. // Without the fix the body is never terminated, so bound the wait rather
  10778. // than letting the test hang on the default read timeout.
  10779. cli.set_read_timeout(5, 0);
  10780. auto res = cli.Get("/stream");
  10781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10782. EXPECT_EQ(StatusCode::OK_200, res->status);
  10783. EXPECT_EQ("hello", res->body);
  10784. }
  10785. TEST(StreamingTest, NoContentLengthStreaming) {
  10786. Server svr;
  10787. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10788. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10789. if (offset < 6) {
  10790. sink.os << (offset < 3 ? "a" : "b");
  10791. } else {
  10792. sink.done();
  10793. }
  10794. return true;
  10795. });
  10796. });
  10797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10798. auto listen_se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client client(HOST, PORT);
  10805. auto get_thread = std::thread([&client]() {
  10806. std::string s;
  10807. auto res =
  10808. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10809. s += std::string(data, len);
  10810. return true;
  10811. });
  10812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10813. EXPECT_EQ(StatusCode::OK_200, res->status);
  10814. EXPECT_EQ("aaabbb", s);
  10815. });
  10816. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10817. // Give GET time to get a few messages.
  10818. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10819. }
  10820. TEST(MountTest, Unmount) {
  10821. Server svr;
  10822. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. listen_thread.join();
  10826. ASSERT_FALSE(svr.is_running());
  10827. });
  10828. svr.wait_until_ready();
  10829. Client cli("localhost", PORT);
  10830. svr.set_mount_point("/mount2", "./www2");
  10831. auto res = cli.Get("/");
  10832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10833. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10834. res = cli.Get("/mount2/dir/test.html");
  10835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10836. EXPECT_EQ(StatusCode::OK_200, res->status);
  10837. svr.set_mount_point("/", "./www");
  10838. res = cli.Get("/dir/");
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. EXPECT_EQ(StatusCode::OK_200, res->status);
  10841. svr.remove_mount_point("/");
  10842. res = cli.Get("/dir/");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10845. svr.remove_mount_point("/mount2");
  10846. res = cli.Get("/mount2/dir/test.html");
  10847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10848. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10849. }
  10850. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10851. Server svr;
  10852. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10853. svr.Get("/api/hello", [](const Request &, Response &res) {
  10854. res.set_content("api", "text/plain");
  10855. });
  10856. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10857. auto se = detail::scope_exit([&] {
  10858. svr.stop();
  10859. listen_thread.join();
  10860. ASSERT_FALSE(svr.is_running());
  10861. });
  10862. svr.wait_until_ready();
  10863. Client cli(HOST, PORT);
  10864. auto res = cli.Get("/dir/test.html");
  10865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10866. EXPECT_EQ(StatusCode::OK_200, res->status);
  10867. res = cli.Get("/api/hello");
  10868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10869. EXPECT_EQ(StatusCode::OK_200, res->status);
  10870. EXPECT_EQ("api", res->body);
  10871. }
  10872. TEST(MountTest, PathSegmentBoundary) {
  10873. Server svr;
  10874. svr.set_mount_point("/mount2", "./www2");
  10875. svr.set_mount_point("/", "./www");
  10876. auto port = svr.bind_to_any_port(HOST);
  10877. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10878. auto se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. listen_thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. Client cli(HOST, port);
  10885. auto res = cli.Get("/mount2/dir/test.html");
  10886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10887. EXPECT_EQ(StatusCode::OK_200, res->status);
  10888. // "/mount2" must not match part-way through a path segment.
  10889. res = cli.Get("/mount2dir/test.html");
  10890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10892. // A mount point ending in '/' keeps matching every path below it.
  10893. res = cli.Get("/dir/test.html");
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res->status);
  10896. }
  10897. TEST(MountTest, Redicect) {
  10898. Server svr;
  10899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10900. auto se = detail::scope_exit([&] {
  10901. svr.stop();
  10902. listen_thread.join();
  10903. ASSERT_FALSE(svr.is_running());
  10904. });
  10905. svr.set_mount_point("/", "./www");
  10906. svr.wait_until_ready();
  10907. Client cli("localhost", PORT);
  10908. auto res = cli.Get("/dir/");
  10909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10910. EXPECT_EQ(StatusCode::OK_200, res->status);
  10911. res = cli.Get("/dir");
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10914. res = cli.Get("/file");
  10915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10916. EXPECT_EQ(StatusCode::OK_200, res->status);
  10917. res = cli.Get("/file/");
  10918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10920. cli.set_follow_location(true);
  10921. res = cli.Get("/dir");
  10922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10923. EXPECT_EQ(StatusCode::OK_200, res->status);
  10924. }
  10925. TEST(MountTest, MultibytesPathName) {
  10926. Server svr;
  10927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10928. auto se = detail::scope_exit([&] {
  10929. svr.stop();
  10930. listen_thread.join();
  10931. ASSERT_FALSE(svr.is_running());
  10932. });
  10933. svr.set_mount_point("/", "./www");
  10934. svr.wait_until_ready();
  10935. Client cli("localhost", PORT);
  10936. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10938. EXPECT_EQ(StatusCode::OK_200, res->status);
  10939. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10940. }
  10941. // A mount point serves no path with an empty segment or one ending in '.' or
  10942. // a space, so a guard in the pre-routing handler sees the path of every file
  10943. // that is served
  10944. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10945. Server svr;
  10946. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10947. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10948. if (req.path == "/dir/test.html") {
  10949. res.status = StatusCode::Unauthorized_401;
  10950. return Server::HandlerResponse::Handled;
  10951. }
  10952. return Server::HandlerResponse::Unhandled;
  10953. });
  10954. auto port = svr.bind_to_any_port(HOST);
  10955. ASSERT_LT(0, port);
  10956. thread t = thread([&] { svr.listen_after_bind(); });
  10957. auto se = detail::scope_exit([&] {
  10958. svr.stop();
  10959. t.join();
  10960. ASSERT_FALSE(svr.is_running());
  10961. });
  10962. svr.wait_until_ready();
  10963. Client cli(HOST, port);
  10964. for (auto path :
  10965. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10966. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10967. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10968. "/dir/test.html%3A%3A$DATA"}) {
  10969. SCOPED_TRACE(path);
  10970. auto res = cli.Get(path);
  10971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10973. }
  10974. }
  10975. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10976. Server svr;
  10977. svr.set_mount_point("/", "./www");
  10978. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10979. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10980. auto port = svr.bind_to_any_port(HOST);
  10981. ASSERT_GT(port, 0);
  10982. thread t = thread([&] { svr.listen_after_bind(); });
  10983. auto se = detail::scope_exit([&] {
  10984. svr.stop();
  10985. t.join();
  10986. ASSERT_FALSE(svr.is_running());
  10987. });
  10988. svr.wait_until_ready();
  10989. Client cli(HOST, port);
  10990. auto res = cli.Get("/dir/test.abcde");
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10993. res = cli.Get("/dir/test.html");
  10994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10995. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10996. }
  10997. #ifdef _WIN32
  10998. // Issue #2435: mmap::open() must succeed even when another handle holds
  10999. // the file open for writing (e.g. an active log file).
  11000. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11001. const char *path = "mmap_concurrent_writer_test.txt";
  11002. const char *content = "hello";
  11003. {
  11004. std::ofstream f(path, std::ios::binary);
  11005. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11006. }
  11007. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11008. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11009. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11010. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11011. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11012. detail::mmap m(path);
  11013. ASSERT_TRUE(m.is_open());
  11014. EXPECT_EQ(strlen(content), m.size());
  11015. char buf[8];
  11016. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11017. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11018. }
  11019. #endif
  11020. #ifndef _WIN32
  11021. // A directory or a device has no size to serve.
  11022. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11023. const char *path = "./mmap_not_regular_test_dir";
  11024. ASSERT_EQ(0, ::mkdir(path, 0755));
  11025. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11026. for (auto p : {path, "/dev/null"}) {
  11027. detail::mmap m(p);
  11028. EXPECT_FALSE(m.is_open()) << p;
  11029. EXPECT_EQ(0U, m.size()) << p;
  11030. }
  11031. Server svr;
  11032. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11033. res.set_file_content("/dev/null");
  11034. });
  11035. auto port = svr.bind_to_any_port(HOST);
  11036. thread t = thread([&] { svr.listen_after_bind(); });
  11037. auto se = detail::scope_exit([&] {
  11038. svr.stop();
  11039. t.join();
  11040. });
  11041. svr.wait_until_ready();
  11042. auto res = Client(HOST, port).Get("/null");
  11043. ASSERT_TRUE(res);
  11044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11045. }
  11046. #endif
  11047. #ifdef __linux__
  11048. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11049. TEST(MmapTest, FileIsNotMapped) {
  11050. const char *path = "mmap_not_mapped_test.txt";
  11051. {
  11052. std::ofstream f(path, std::ios::binary);
  11053. f << "hello";
  11054. }
  11055. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11056. detail::mmap m(path);
  11057. ASSERT_TRUE(m.is_open());
  11058. std::ifstream maps("/proc/self/maps");
  11059. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11060. std::istreambuf_iterator<char>());
  11061. EXPECT_EQ(std::string::npos, mappings.find(path));
  11062. }
  11063. #endif
  11064. TEST(KeepAliveTest, ReadTimeout) {
  11065. Server svr;
  11066. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11067. std::this_thread::sleep_for(std::chrono::seconds(2));
  11068. res.set_content("a", "text/plain");
  11069. });
  11070. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11071. res.set_content("b", "text/plain");
  11072. });
  11073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. listen_thread.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. Client cli("localhost", PORT);
  11081. cli.set_keep_alive(true);
  11082. cli.set_read_timeout(std::chrono::seconds(1));
  11083. auto resa = cli.Get("/a");
  11084. ASSERT_FALSE(resa);
  11085. EXPECT_EQ(Error::Read, resa.error());
  11086. auto resb = cli.Get("/b");
  11087. ASSERT_TRUE(resb);
  11088. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11089. EXPECT_EQ("b", resb->body);
  11090. }
  11091. TEST(KeepAliveTest, MaxCount) {
  11092. size_t keep_alive_max_count = 3;
  11093. Server svr;
  11094. svr.set_keep_alive_max_count(keep_alive_max_count);
  11095. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11096. res.set_content("Hello World!", "text/plain");
  11097. });
  11098. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11099. auto se = detail::scope_exit([&] {
  11100. svr.stop();
  11101. listen_thread.join();
  11102. ASSERT_FALSE(svr.is_running());
  11103. });
  11104. svr.wait_until_ready();
  11105. Client cli(HOST, PORT);
  11106. cli.set_keep_alive(true);
  11107. for (size_t i = 0; i < 5; i++) {
  11108. auto result = cli.Get("/hi");
  11109. ASSERT_TRUE(result);
  11110. EXPECT_EQ(StatusCode::OK_200, result->status);
  11111. if (i == keep_alive_max_count - 1) {
  11112. EXPECT_EQ("close", result->get_header_value("Connection"));
  11113. } else {
  11114. EXPECT_FALSE(result->has_header("Connection"));
  11115. }
  11116. }
  11117. }
  11118. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11119. // can pull the next one into the server's buffer. The server must serve it
  11120. // without waiting for the socket to become readable again. The keep-alive
  11121. // timeout outlasts the client's read timeout, so a request left waiting for it
  11122. // shows up as a missing response.
  11123. static void serve_pipelining_routes(Server &svr,
  11124. const std::function<void(int)> &client) {
  11125. svr.set_keep_alive_timeout(5);
  11126. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11127. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11128. });
  11129. svr.Post("/echo", [](const Request &req, Response &res) {
  11130. res.set_content("echo " + req.body, "text/plain");
  11131. });
  11132. auto port = svr.bind_to_any_port(HOST);
  11133. thread t = thread([&] { svr.listen_after_bind(); });
  11134. auto se = detail::scope_exit([&] {
  11135. svr.stop();
  11136. t.join();
  11137. });
  11138. svr.wait_until_ready();
  11139. client(port);
  11140. }
  11141. static std::string
  11142. send_pipelined_requests(const std::vector<std::string> &parts) {
  11143. Server svr;
  11144. std::string res;
  11145. serve_pipelining_routes(svr, [&](int port) {
  11146. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11147. });
  11148. return res;
  11149. }
  11150. static void expect_in_order(const std::string &res,
  11151. const std::vector<std::string> &bodies) {
  11152. size_t pos = 0;
  11153. for (const auto &body : bodies) {
  11154. pos = res.find(body, pos);
  11155. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11156. pos += body.size();
  11157. }
  11158. }
  11159. TEST(KeepAliveTest, PipelinedRequests) {
  11160. auto res = send_pipelined_requests(
  11161. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11162. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11163. "Content-Length: 4\r\n\r\nbody"
  11164. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11165. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11166. }
  11167. // The second request starts in the server's buffer and ends on the socket.
  11168. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11169. auto res =
  11170. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11171. "GET /hi/2 HTTP/1.1\r\nHo",
  11172. "st: localhost\r\nConnection: close\r\n\r\n"});
  11173. expect_in_order(res, {"hi 1", "hi 2"});
  11174. }
  11175. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11176. // CRLF after a body does not turn into a 400 for the next request.
  11177. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11178. auto res = send_pipelined_requests(
  11179. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11180. "Content-Length: 4\r\n\r\nbody\r\n"
  11181. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11182. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11183. expect_in_order(res, {"echo body", "hi 2"});
  11184. }
  11185. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11186. // must not be served as the next request.
  11187. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11188. auto res = send_pipelined_requests(
  11189. {"INVALID REQUEST LINE\r\n\r\n"
  11190. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11191. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11192. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11193. }
  11194. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11195. // Over TLS, the next request is held by the TLS library as already decrypted
  11196. // data rather than on the socket.
  11197. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11199. std::string res;
  11200. serve_pipelining_routes(svr, [&](int port) {
  11201. // One part, so all three requests arrive in one TLS record
  11202. EXPECT_TRUE(send_ssl_request_in_parts(
  11203. 2,
  11204. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11205. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11206. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11207. &res, port));
  11208. });
  11209. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11210. }
  11211. #endif
  11212. TEST(KeepAliveTest, Issue1041) {
  11213. Server svr;
  11214. svr.set_keep_alive_timeout(3);
  11215. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11216. res.set_content("Hello World!", "text/plain");
  11217. });
  11218. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. listen_thread.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. Client cli(HOST, PORT);
  11226. cli.set_keep_alive(true);
  11227. auto result = cli.Get("/hi");
  11228. ASSERT_TRUE(result);
  11229. EXPECT_EQ(StatusCode::OK_200, result->status);
  11230. std::this_thread::sleep_for(std::chrono::seconds(5));
  11231. result = cli.Get("/hi");
  11232. ASSERT_TRUE(result);
  11233. EXPECT_EQ(StatusCode::OK_200, result->status);
  11234. }
  11235. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11236. Server svr;
  11237. svr.set_keep_alive_max_count(0);
  11238. std::set<int> remote_ports;
  11239. svr.Get("/hi", [&](const Request &req, Response &res) {
  11240. remote_ports.insert(req.remote_port);
  11241. res.set_content("hi", "text/plain");
  11242. });
  11243. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. listen_thread.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. Client cli(HOST, PORT);
  11251. cli.set_keep_alive(true);
  11252. for (int i = 0; i < 3; i++) {
  11253. auto res = cli.Get("/hi");
  11254. ASSERT_TRUE(res);
  11255. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11256. }
  11257. // All three over one connection
  11258. EXPECT_EQ(1u, remote_ports.size());
  11259. }
  11260. TEST(KeepAliveTest, Issue1959) {
  11261. Server svr;
  11262. svr.set_keep_alive_timeout(5);
  11263. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11264. res.set_content("a", "text/plain");
  11265. });
  11266. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11267. auto se = detail::scope_exit([&] {
  11268. if (!svr.is_running()) return;
  11269. svr.stop();
  11270. listen_thread.join();
  11271. ASSERT_FALSE(svr.is_running());
  11272. });
  11273. svr.wait_until_ready();
  11274. Client cli("localhost", PORT);
  11275. cli.set_keep_alive(true);
  11276. using namespace std::chrono;
  11277. auto start = steady_clock::now();
  11278. cli.Get("/a");
  11279. svr.stop();
  11280. listen_thread.join();
  11281. auto end = steady_clock::now();
  11282. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11283. EXPECT_LT(elapsed, 5000);
  11284. }
  11285. #ifdef CPPHTTPLIB_SSL_ENABLED
  11286. TEST(KeepAliveTest, SSLClientReconnection) {
  11287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11288. ASSERT_TRUE(svr.is_valid());
  11289. svr.set_keep_alive_timeout(1);
  11290. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11291. res.set_content("Hello World!", "text/plain");
  11292. });
  11293. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11294. auto se = detail::scope_exit([&] {
  11295. svr.stop();
  11296. listen_thread.join();
  11297. ASSERT_FALSE(svr.is_running());
  11298. });
  11299. svr.wait_until_ready();
  11300. SSLClient cli(HOST, PORT);
  11301. cli.enable_server_certificate_verification(false);
  11302. cli.set_keep_alive(true);
  11303. auto result = cli.Get("/hi");
  11304. ASSERT_TRUE(result);
  11305. EXPECT_EQ(StatusCode::OK_200, result->status);
  11306. result = cli.Get("/hi");
  11307. ASSERT_TRUE(result);
  11308. EXPECT_EQ(StatusCode::OK_200, result->status);
  11309. std::this_thread::sleep_for(std::chrono::seconds(2));
  11310. // Recoonect
  11311. result = cli.Get("/hi");
  11312. ASSERT_TRUE(result);
  11313. EXPECT_EQ(StatusCode::OK_200, result->status);
  11314. result = cli.Get("/hi");
  11315. ASSERT_TRUE(result);
  11316. EXPECT_EQ(StatusCode::OK_200, result->status);
  11317. }
  11318. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11320. ASSERT_TRUE(svr.is_valid());
  11321. svr.set_keep_alive_timeout(1);
  11322. std::string content = "reconnect";
  11323. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11324. res.set_content("Hello World!", "text/plain");
  11325. });
  11326. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11327. auto se = detail::scope_exit([&] {
  11328. svr.stop();
  11329. listen_thread.join();
  11330. ASSERT_FALSE(svr.is_running());
  11331. });
  11332. svr.wait_until_ready();
  11333. SSLClient cli(HOST, PORT);
  11334. cli.enable_server_certificate_verification(false);
  11335. cli.set_keep_alive(true);
  11336. auto result = cli.Post(
  11337. "/hi", content.size(),
  11338. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11339. sink.write(content.c_str(), content.size());
  11340. return true;
  11341. },
  11342. "text/plain");
  11343. ASSERT_TRUE(result);
  11344. EXPECT_EQ(200, result->status);
  11345. std::this_thread::sleep_for(std::chrono::seconds(2));
  11346. // Recoonect
  11347. result = cli.Post(
  11348. "/hi", content.size(),
  11349. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11350. sink.write(content.c_str(), content.size());
  11351. return true;
  11352. },
  11353. "text/plain");
  11354. ASSERT_TRUE(result);
  11355. EXPECT_EQ(200, result->status);
  11356. result = cli.Post(
  11357. "/hi", content.size(),
  11358. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11359. sink.write(content.c_str(), content.size());
  11360. return true;
  11361. },
  11362. "text/plain");
  11363. ASSERT_TRUE(result);
  11364. EXPECT_EQ(200, result->status);
  11365. }
  11366. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11367. using namespace httplib::tls;
  11368. {
  11369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11370. ASSERT_TRUE(svr.is_valid());
  11371. svr.Get("/sni", [&](const Request &req, Response &res) {
  11372. std::string expected = req.sni();
  11373. EXPECT_EQ(expected, req.get_param_value("expected"));
  11374. res.set_content("ok", "text/plain");
  11375. });
  11376. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11377. auto se = detail::scope_exit([&] {
  11378. svr.stop();
  11379. listen_thread.join();
  11380. ASSERT_FALSE(svr.is_running());
  11381. });
  11382. svr.wait_until_ready();
  11383. {
  11384. SSLClient cli("localhost", PORT);
  11385. cli.enable_server_certificate_verification(false);
  11386. auto res = cli.Get("/sni?expected=localhost");
  11387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11388. }
  11389. {
  11390. SSLClient cli("::1", PORT);
  11391. cli.enable_server_certificate_verification(false);
  11392. auto res = cli.Get("/sni?expected=");
  11393. // NOTE: This may fail if the server is listening on IPv4 only
  11394. // (e.g., when localhost resolves to 127.0.0.1 only)
  11395. if (res) {
  11396. EXPECT_EQ(StatusCode::OK_200, res->status);
  11397. } else {
  11398. EXPECT_EQ(Error::Connection, res.error());
  11399. }
  11400. }
  11401. }
  11402. }
  11403. // The SNI of a failed handshake does not reach the next connection that the
  11404. // same worker thread serves
  11405. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11407. ASSERT_TRUE(svr.is_valid());
  11408. svr.new_task_queue = [] { return new ThreadPool(1); };
  11409. svr.Get("/sni", [](const Request &req, Response &res) {
  11410. res.set_content(req.sni(), "text/plain");
  11411. });
  11412. auto port = svr.bind_to_any_port("127.0.0.1");
  11413. ASSERT_LT(0, port);
  11414. thread t = thread([&] { svr.listen_after_bind(); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. });
  11420. svr.wait_until_ready();
  11421. {
  11422. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11423. SSLClient cli("localhost", port);
  11424. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11425. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11426. auto res = cli.Get("/sni");
  11427. ASSERT_FALSE(res);
  11428. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11429. }
  11430. // An IP host sends no SNI (RFC 6066)
  11431. SSLClient cli("127.0.0.1", port);
  11432. cli.enable_server_certificate_verification(false);
  11433. auto res = cli.Get("/sni");
  11434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11435. EXPECT_EQ("", res->body);
  11436. }
  11437. #endif
  11438. TEST(ClientProblemDetectionTest, ContentProvider) {
  11439. Server svr;
  11440. size_t content_length = 1024 * 1024;
  11441. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11442. res.set_content_provider(
  11443. content_length, "text/plain",
  11444. [&](size_t offset, size_t length, DataSink &sink) {
  11445. auto out_len = std::min(length, static_cast<size_t>(1024));
  11446. std::string out(out_len, '@');
  11447. sink.write(out.data(), out_len);
  11448. return offset < 4096;
  11449. },
  11450. [](bool success) { ASSERT_FALSE(success); });
  11451. });
  11452. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11453. res.set_content_provider(
  11454. 0, "text/plain",
  11455. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11456. EXPECT_TRUE(false);
  11457. return true;
  11458. },
  11459. [](bool success) { ASSERT_FALSE(success); });
  11460. });
  11461. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11462. auto se = detail::scope_exit([&] {
  11463. svr.stop();
  11464. listen_thread.join();
  11465. ASSERT_FALSE(svr.is_running());
  11466. });
  11467. svr.wait_until_ready();
  11468. Client cli("localhost", PORT);
  11469. {
  11470. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11471. size_t /*data_length*/) { return false; });
  11472. ASSERT_FALSE(res);
  11473. }
  11474. {
  11475. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11476. size_t /*data_length*/) { return false; });
  11477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11478. }
  11479. }
  11480. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11481. // A provider that reports success without writing anything and without
  11482. // calling done() used to be handed the same offset and length again on every
  11483. // pass, so it spun for as long as the peer stayed connected.
  11484. Server svr;
  11485. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11486. res.set_content("ok", "text/plain");
  11487. });
  11488. auto port = svr.bind_to_any_port(HOST);
  11489. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. listen_thread.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. });
  11495. svr.wait_until_ready();
  11496. std::atomic<int> call_count{0};
  11497. Client cli(HOST, port);
  11498. auto res = cli.Post(
  11499. "/", 1024,
  11500. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11501. // Give up after enough passes to show the spin, so that losing the
  11502. // check below fails this test instead of hanging it.
  11503. return ++call_count < 100;
  11504. },
  11505. "text/plain");
  11506. ASSERT_FALSE(res);
  11507. EXPECT_EQ(Error::Write, res.error());
  11508. EXPECT_EQ(1, call_count.load());
  11509. }
  11510. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11511. // A writer only has to assign `write`. The other three used to be left as
  11512. // empty std::functions, so a provider calling one threw
  11513. // std::bad_function_call out of the thread running it and took the whole
  11514. // process down.
  11515. DataSink sink;
  11516. std::string written;
  11517. sink.write = [&](const char *data, size_t data_len) {
  11518. written.append(data, data_len);
  11519. return true;
  11520. };
  11521. EXPECT_TRUE(sink.is_writable());
  11522. sink.done();
  11523. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11524. EXPECT_TRUE(written.empty());
  11525. }
  11526. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11527. // A sink that cannot carry trailers still has to finish.
  11528. DataSink sink;
  11529. auto done_count = 0;
  11530. sink.done = [&]() { done_count++; };
  11531. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11532. EXPECT_EQ(1, done_count);
  11533. }
  11534. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11535. Server svr;
  11536. const std::string body(4096, 'x');
  11537. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11538. res.set_content_provider(body.size(), "text/plain",
  11539. [&](size_t offset, size_t length, DataSink &sink) {
  11540. sink.write(body.data() + offset, length);
  11541. sink.done();
  11542. return true;
  11543. });
  11544. });
  11545. auto port = svr.bind_to_any_port(HOST);
  11546. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11547. auto se = detail::scope_exit([&] {
  11548. svr.stop();
  11549. listen_thread.join();
  11550. ASSERT_FALSE(svr.is_running());
  11551. });
  11552. svr.wait_until_ready();
  11553. Client cli(HOST, port);
  11554. auto res = cli.Get("/");
  11555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11556. EXPECT_EQ(StatusCode::OK_200, res->status);
  11557. EXPECT_EQ(body, res->body);
  11558. }
  11559. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11560. Server svr;
  11561. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11562. res.set_content_provider(
  11563. 1024, "text/plain",
  11564. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11565. sink.write("hello", 5);
  11566. sink.done(); // short of the 1024 bytes the response promised
  11567. return true;
  11568. });
  11569. });
  11570. auto port = svr.bind_to_any_port(HOST);
  11571. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11572. auto se = detail::scope_exit([&] {
  11573. svr.stop();
  11574. listen_thread.join();
  11575. ASSERT_FALSE(svr.is_running());
  11576. });
  11577. svr.wait_until_ready();
  11578. Client cli(HOST, port);
  11579. cli.set_read_timeout(5, 0);
  11580. // The response is short of its Content-Length, so the client cannot read a
  11581. // complete body. What matters is that this returns at all: a no-op done()
  11582. // would leave the writer looping over a provider that never makes progress.
  11583. auto res = cli.Get("/");
  11584. EXPECT_FALSE(res);
  11585. }
  11586. // Read as the next response by a peer that sees it after a framed body.
  11587. static const std::string smuggled_response =
  11588. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11589. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11590. Server svr;
  11591. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11592. res.set_content_provider(
  11593. 5, "text/plain",
  11594. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11595. auto data = "AAAAA" + smuggled_response;
  11596. sink.write(data.data(), data.size());
  11597. return true;
  11598. });
  11599. });
  11600. thread t = thread([&] { svr.listen(HOST, PORT); });
  11601. auto se = detail::scope_exit([&] {
  11602. svr.stop();
  11603. t.join();
  11604. ASSERT_FALSE(svr.is_running());
  11605. });
  11606. svr.wait_until_ready();
  11607. std::string resp;
  11608. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11609. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11610. resp.clear();
  11611. ASSERT_TRUE(send_request(
  11612. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11613. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11614. }
  11615. TEST(NoContentTest, BodyIsNotSent) {
  11616. Server svr;
  11617. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11618. res.status = StatusCode::NoContent_204;
  11619. res.set_content(smuggled_response, "text/plain");
  11620. });
  11621. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11622. res.status = StatusCode::NotModified_304;
  11623. res.set_chunked_content_provider(
  11624. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11625. sink.write(smuggled_response.data(), smuggled_response.size());
  11626. sink.done();
  11627. return true;
  11628. });
  11629. });
  11630. thread t = thread([&] { svr.listen(HOST, PORT); });
  11631. auto se = detail::scope_exit([&] {
  11632. svr.stop();
  11633. t.join();
  11634. ASSERT_FALSE(svr.is_running());
  11635. });
  11636. svr.wait_until_ready();
  11637. for (auto path : {"/204", "/304"}) {
  11638. std::string resp;
  11639. ASSERT_TRUE(send_request(
  11640. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11641. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11642. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11643. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11644. }
  11645. }
  11646. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11647. Server svr;
  11648. std::atomic<bool> smuggled(false);
  11649. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11650. res.set_content("ok", "text/plain");
  11651. });
  11652. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11653. smuggled = true;
  11654. });
  11655. auto port = svr.bind_to_any_port(HOST);
  11656. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. listen_thread.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. // What follows the body would be read as the next request.
  11664. Client cli(HOST, port);
  11665. auto res = cli.Post(
  11666. "/", 5,
  11667. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11668. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11669. sink.write(data.data(), data.size());
  11670. return true;
  11671. },
  11672. "text/plain");
  11673. ASSERT_FALSE(res);
  11674. EXPECT_EQ(Error::Write, res.error());
  11675. EXPECT_FALSE(smuggled);
  11676. }
  11677. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11678. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11679. // The compressed path builds the whole body before connecting, so this
  11680. // fails client-side and never reaches a server.
  11681. Client cli(HOST, PORT);
  11682. cli.set_compress(true);
  11683. auto res = cli.Post(
  11684. "/", 1024,
  11685. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11686. sink.write("hello", 5);
  11687. sink.done(); // short of the 1024 bytes the request announced
  11688. return true;
  11689. },
  11690. "text/plain");
  11691. ASSERT_FALSE(res);
  11692. EXPECT_EQ(Error::Write, res.error());
  11693. }
  11694. #endif
  11695. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11696. Server svr;
  11697. svr.set_error_handler([](Request const &, Response &res) -> void {
  11698. res.set_chunked_content_provider(
  11699. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11700. sink.os << "hello";
  11701. sink.os << "world";
  11702. sink.done();
  11703. return true;
  11704. });
  11705. });
  11706. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. listen_thread.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. Client cli("localhost", PORT);
  11714. auto res = cli.Get("/");
  11715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11717. EXPECT_EQ("helloworld", res->body);
  11718. }
  11719. // A body set after a content provider must replace it, not be sent through it.
  11720. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11721. Server svr;
  11722. svr.set_mount_point("/", "./www");
  11723. svr.set_file_request_handler([](const Request &req, Response &res) {
  11724. if (req.path == "/dir/test.html") {
  11725. res.status = StatusCode::Forbidden_403;
  11726. res.set_content(std::string(5000, 'D'), "text/plain");
  11727. } else if (req.path == "/file") {
  11728. res.status = StatusCode::Forbidden_403;
  11729. res.body = "Denied";
  11730. }
  11731. });
  11732. auto port = svr.bind_to_any_port(HOST);
  11733. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11734. auto se = detail::scope_exit([&] {
  11735. svr.stop();
  11736. t.join();
  11737. ASSERT_FALSE(svr.is_running());
  11738. });
  11739. svr.wait_until_ready();
  11740. Client cli(HOST, port);
  11741. {
  11742. auto res = cli.Get("/dir/test.html");
  11743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11744. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11745. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11746. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11747. }
  11748. {
  11749. auto res = cli.Get("/file");
  11750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11751. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11752. EXPECT_EQ("Denied", res->body);
  11753. }
  11754. {
  11755. auto res = cli.Get("/dir/index.html");
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ(0U, res->body.find("<html>"));
  11759. }
  11760. }
  11761. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11762. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11763. Server svr;
  11764. std::vector<bool> released;
  11765. std::mutex released_mutex;
  11766. auto releaser = [&](bool success) {
  11767. std::lock_guard<std::mutex> guard(released_mutex);
  11768. released.push_back(success);
  11769. };
  11770. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11771. return sink.write(&"hello"[offset], length);
  11772. };
  11773. svr.Get("/sized", [&](const Request &, Response &res) {
  11774. res.status = StatusCode::NotFound_404;
  11775. res.set_content_provider(5, "text/plain", provider, releaser);
  11776. });
  11777. svr.Get("/chunked", [&](const Request &, Response &res) {
  11778. res.status = StatusCode::ServiceUnavailable_503;
  11779. res.set_chunked_content_provider(
  11780. "text/plain",
  11781. [](size_t, DataSink &sink) {
  11782. sink.os << "chunk";
  11783. sink.done();
  11784. return true;
  11785. },
  11786. releaser);
  11787. });
  11788. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11789. res.set_content_provider(5, "text/plain", provider, releaser);
  11790. throw std::runtime_error("after the provider");
  11791. });
  11792. svr.set_error_handler([](const Request &req, Response &res) {
  11793. // Leave the exception handler's content to it.
  11794. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11795. res.set_content(std::string(1000, 'E'), "text/html");
  11796. return Server::HandlerResponse::Handled;
  11797. });
  11798. svr.set_exception_handler(
  11799. [](const Request &, Response &res, std::exception_ptr) {
  11800. res.status = StatusCode::InternalServerError_500;
  11801. res.set_content(std::string(1000, 'X'), "text/html");
  11802. });
  11803. auto port = svr.bind_to_any_port(HOST);
  11804. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11805. auto se = detail::scope_exit([&] {
  11806. svr.stop();
  11807. t.join();
  11808. ASSERT_FALSE(svr.is_running());
  11809. });
  11810. svr.wait_until_ready();
  11811. Client cli(HOST, port);
  11812. {
  11813. auto res = cli.Get("/sized");
  11814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11816. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11817. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11818. }
  11819. {
  11820. auto res = cli.Get("/chunked");
  11821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11822. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11823. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11824. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11825. }
  11826. {
  11827. auto res = cli.Get("/throw");
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11830. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11831. }
  11832. std::lock_guard<std::mutex> guard(released_mutex);
  11833. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11834. }
  11835. #endif
  11836. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11837. Server svr;
  11838. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11839. return sink.write(&"abc"[offset], length);
  11840. };
  11841. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11842. res.set_file_content("./www/dir/test.html");
  11843. res.set_content("body", "text/plain");
  11844. });
  11845. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11846. res.set_content(std::string(100, 'B'), "text/plain");
  11847. res.set_file_content("./www/dir/test.html");
  11848. });
  11849. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11850. res.set_content(std::string(100, 'B'), "text/plain");
  11851. res.set_content_provider(3, "text/x-provider", abc);
  11852. });
  11853. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11854. res.set_content_provider(3, "text/x-provider", abc);
  11855. res.set_content(std::string(100, 'B'), "text/plain");
  11856. });
  11857. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11858. res.set_content_provider(3, "text/x-provider", abc);
  11859. res.set_file_content("./www/dir/test.html", "text/x-file");
  11860. });
  11861. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11862. res.set_file_content("./www/dir/test.html");
  11863. res.set_header("Content-Type", "text/x-handler");
  11864. });
  11865. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11866. res.set_content_provider(3, "text/plain", abc);
  11867. res.body = "direct";
  11868. });
  11869. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11870. res.set_file_content("./www/dir/test.html");
  11871. res.body = "direct";
  11872. });
  11873. auto port = svr.bind_to_any_port(HOST);
  11874. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11875. auto se = detail::scope_exit([&] {
  11876. svr.stop();
  11877. t.join();
  11878. ASSERT_FALSE(svr.is_running());
  11879. });
  11880. svr.wait_until_ready();
  11881. Client cli(HOST, port);
  11882. auto expect_body = [&](const char *path, const std::string &body,
  11883. const std::string &type) {
  11884. // Uncompressed, so Content-Length can be compared with the body.
  11885. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11886. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11887. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11888. EXPECT_EQ(body, res->body) << path;
  11889. EXPECT_EQ(std::to_string(body.size()),
  11890. res->get_header_value("Content-Length"))
  11891. << path;
  11892. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11893. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11894. };
  11895. expect_body("/file-then-body", "body", "text/plain");
  11896. expect_body("/body-then-file", "test.html", "text/html");
  11897. expect_body("/body-then-provider", "abc", "text/x-provider");
  11898. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11899. expect_body("/provider-then-file", "test.html", "text/x-file");
  11900. expect_body("/file-then-header", "test.html", "text/x-handler");
  11901. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11902. expect_body("/file-then-direct-body", "direct", "text/plain");
  11903. // Ranges are checked against the body, not the dropped provider.
  11904. {
  11905. auto res = cli.Get("/provider-then-direct-body",
  11906. Headers{{make_range_header({{1, 2}})}});
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11909. EXPECT_EQ("ir", res->body);
  11910. }
  11911. {
  11912. auto res = cli.Get("/file-then-direct-body",
  11913. Headers{{make_range_header({{7, 8}})}});
  11914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11915. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11916. }
  11917. }
  11918. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11919. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11920. const char *path = "./truncated_while_served.txt";
  11921. const size_t size = 32 * 1024 * 1024;
  11922. {
  11923. std::ofstream f(path, std::ios::binary);
  11924. f << std::string(size, 'x');
  11925. }
  11926. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11927. // Over TLS, where the bytes are encrypted in this process rather than
  11928. // copied by send().
  11929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11930. svr.Get("/file", [&](const Request &, Response &res) {
  11931. res.set_file_content(path, "text/plain");
  11932. });
  11933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11934. auto se = detail::scope_exit([&] {
  11935. svr.stop();
  11936. thread.join();
  11937. ASSERT_FALSE(svr.is_running());
  11938. });
  11939. svr.wait_until_ready();
  11940. // The file shrinks once the first bytes are in, as a rewrite in place
  11941. // would, and reading the mapping past its new end used to raise SIGBUS.
  11942. SSLClient cli(HOST, PORT);
  11943. cli.enable_server_certificate_verification(false);
  11944. size_t received = 0;
  11945. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11946. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11947. received += len;
  11948. return true;
  11949. });
  11950. EXPECT_FALSE(res);
  11951. EXPECT_LT(received, size);
  11952. }
  11953. #endif
  11954. // Forward declaration (see the base64_encode note).
  11955. namespace httplib {
  11956. namespace detail {
  11957. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11958. const std::string &content_type,
  11959. EncodingType encoding);
  11960. } // namespace detail
  11961. } // namespace httplib
  11962. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11963. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11964. ASSERT_TRUE(mm->is_open());
  11965. Response res;
  11966. detail::set_file_content_provider(res, mm, "text/html",
  11967. detail::EncodingType::None);
  11968. std::string out;
  11969. DataSink sink;
  11970. sink.write = [&](const char *d, size_t l) {
  11971. out.append(d, l);
  11972. return true;
  11973. };
  11974. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11975. EXPECT_EQ("test.html", out);
  11976. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11977. EXPECT_EQ("test.html", out);
  11978. }
  11979. TEST(LongPollingTest, ClientCloseDetection) {
  11980. Server svr;
  11981. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11982. res.set_chunked_content_provider(
  11983. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11984. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11985. sink.os << "hello";
  11986. auto count = 10;
  11987. while (count > 0 && sink.is_writable()) {
  11988. this_thread::sleep_for(chrono::milliseconds(10));
  11989. count--;
  11990. }
  11991. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11992. return true;
  11993. });
  11994. });
  11995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11996. auto se = detail::scope_exit([&] {
  11997. svr.stop();
  11998. listen_thread.join();
  11999. ASSERT_FALSE(svr.is_running());
  12000. });
  12001. svr.wait_until_ready();
  12002. Client cli("localhost", PORT);
  12003. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12004. EXPECT_EQ("hello", string(data, data_length));
  12005. return false; // close the socket immediately.
  12006. });
  12007. ASSERT_FALSE(res);
  12008. }
  12009. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12010. Server svr;
  12011. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12012. res.set_chunked_content_provider(
  12013. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12014. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12015. sink.os << "hello";
  12016. EXPECT_TRUE(sink.os.good());
  12017. // Wait for the client to close the connection
  12018. auto count = 10;
  12019. while (count > 0 && sink.is_writable()) {
  12020. this_thread::sleep_for(chrono::milliseconds(10));
  12021. count--;
  12022. }
  12023. // After client disconnect, write repeatedly until the socket
  12024. // write actually fails (small writes may be absorbed by the
  12025. // kernel buffer)
  12026. std::string chunk(1024, 'x');
  12027. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12028. sink.os << chunk;
  12029. }
  12030. EXPECT_TRUE(sink.os.fail());
  12031. return true;
  12032. });
  12033. });
  12034. auto port = svr.bind_to_any_port("localhost");
  12035. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12036. auto se = detail::scope_exit([&] {
  12037. svr.stop();
  12038. listen_thread.join();
  12039. ASSERT_FALSE(svr.is_running());
  12040. });
  12041. svr.wait_until_ready();
  12042. Client cli("localhost", port);
  12043. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12044. EXPECT_EQ("hello", string(data, data_length));
  12045. return false; // close the socket immediately.
  12046. });
  12047. ASSERT_FALSE(res);
  12048. }
  12049. TEST(GetWithParametersTest, GetWithParameters) {
  12050. Server svr;
  12051. svr.Get("/", [&](const Request &req, Response &) {
  12052. EXPECT_EQ("world", req.get_param_value("hello"));
  12053. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12054. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12055. });
  12056. svr.Get("/params", [&](const Request &req, Response &) {
  12057. EXPECT_EQ("world", req.get_param_value("hello"));
  12058. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12059. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12060. });
  12061. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12062. EXPECT_EQ("resource-id", req.matches[1]);
  12063. EXPECT_EQ("foo", req.get_param_value("param1"));
  12064. EXPECT_EQ("bar", req.get_param_value("param2"));
  12065. });
  12066. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12067. EXPECT_EQ("user-id", req.path_params.at("id"));
  12068. EXPECT_EQ("foo", req.get_param_value("param1"));
  12069. EXPECT_EQ("bar", req.get_param_value("param2"));
  12070. });
  12071. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12072. auto se = detail::scope_exit([&] {
  12073. svr.stop();
  12074. listen_thread.join();
  12075. ASSERT_FALSE(svr.is_running());
  12076. });
  12077. svr.wait_until_ready();
  12078. {
  12079. Client cli(HOST, PORT);
  12080. Params params;
  12081. params.emplace("hello", "world");
  12082. params.emplace("hello2", "world2");
  12083. params.emplace("hello3", "world3");
  12084. auto res = cli.Get("/", params, Headers{});
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. EXPECT_EQ(StatusCode::OK_200, res->status);
  12087. }
  12088. {
  12089. Client cli(HOST, PORT);
  12090. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12092. EXPECT_EQ(StatusCode::OK_200, res->status);
  12093. }
  12094. {
  12095. Client cli(HOST, PORT);
  12096. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12098. EXPECT_EQ(StatusCode::OK_200, res->status);
  12099. }
  12100. {
  12101. Client cli(HOST, PORT);
  12102. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12104. EXPECT_EQ(StatusCode::OK_200, res->status);
  12105. }
  12106. }
  12107. TEST(GetWithParametersTest, GetWithParameters2) {
  12108. Server svr;
  12109. svr.Get("/", [&](const Request &req, Response &res) {
  12110. auto text = req.get_param_value("hello");
  12111. res.set_content(text, "text/plain");
  12112. });
  12113. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12114. auto se = detail::scope_exit([&] {
  12115. svr.stop();
  12116. listen_thread.join();
  12117. ASSERT_FALSE(svr.is_running());
  12118. });
  12119. svr.wait_until_ready();
  12120. Client cli("localhost", PORT);
  12121. Params params;
  12122. params.emplace("hello", "world");
  12123. std::string body;
  12124. auto res = cli.Get("/", params, Headers{},
  12125. [&](const char *data, size_t data_length) {
  12126. body.append(data, data_length);
  12127. return true;
  12128. });
  12129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12130. EXPECT_EQ(StatusCode::OK_200, res->status);
  12131. EXPECT_EQ("world", body);
  12132. }
  12133. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12134. Server svr;
  12135. svr.Get("/search", [&](const Request &req, Response &res) {
  12136. auto q = req.get_param_value("q");
  12137. res.set_content(q, "text/plain");
  12138. });
  12139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12140. auto se = detail::scope_exit([&] {
  12141. svr.stop();
  12142. listen_thread.join();
  12143. ASSERT_FALSE(svr.is_running());
  12144. });
  12145. svr.wait_until_ready();
  12146. Client cli("localhost", PORT);
  12147. // Verify that Get(path, params) works without requiring Headers argument
  12148. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12150. EXPECT_EQ(StatusCode::OK_200, res->status);
  12151. EXPECT_EQ("cpp-httplib", res->body);
  12152. }
  12153. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12154. auto host = "httpbingo.org";
  12155. auto path = std::string{"/range/32"};
  12156. #ifdef CPPHTTPLIB_SSL_ENABLED
  12157. SSLClient cli(host);
  12158. #else
  12159. Client cli(host);
  12160. #endif
  12161. cli.set_default_headers({make_range_header({{1, 10}})});
  12162. cli.set_connection_timeout(5);
  12163. {
  12164. auto res = cli.Get(path);
  12165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12166. EXPECT_EQ("bcdefghijk", res->body);
  12167. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12168. }
  12169. {
  12170. auto res = cli.Get(path);
  12171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12172. EXPECT_EQ("bcdefghijk", res->body);
  12173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12174. }
  12175. }
  12176. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12177. Server svr;
  12178. svr.set_default_headers({{"Hello", "World"}});
  12179. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12180. res.set_content("ok", "text/plain");
  12181. });
  12182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12183. auto se = detail::scope_exit([&] {
  12184. svr.stop();
  12185. listen_thread.join();
  12186. ASSERT_FALSE(svr.is_running());
  12187. });
  12188. svr.wait_until_ready();
  12189. Client cli("localhost", PORT);
  12190. auto res = cli.Get("/");
  12191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12192. EXPECT_EQ(StatusCode::OK_200, res->status);
  12193. EXPECT_EQ("ok", res->body);
  12194. EXPECT_EQ("World", res->get_header_value("Hello"));
  12195. }
  12196. #ifdef CPPHTTPLIB_SSL_ENABLED
  12197. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12199. ASSERT_TRUE(svr.is_valid());
  12200. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12201. std::this_thread::sleep_for(std::chrono::seconds(2));
  12202. res.set_content("a", "text/plain");
  12203. });
  12204. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12205. res.set_content("b", "text/plain");
  12206. });
  12207. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12208. auto se = detail::scope_exit([&] {
  12209. svr.stop();
  12210. listen_thread.join();
  12211. ASSERT_FALSE(svr.is_running());
  12212. });
  12213. svr.wait_until_ready();
  12214. SSLClient cli("localhost", PORT);
  12215. cli.enable_server_certificate_verification(false);
  12216. cli.set_keep_alive(true);
  12217. cli.set_read_timeout(std::chrono::seconds(1));
  12218. auto resa = cli.Get("/a");
  12219. ASSERT_TRUE(!resa);
  12220. EXPECT_EQ(Error::Read, resa.error());
  12221. auto resb = cli.Get("/b");
  12222. ASSERT_TRUE(resb);
  12223. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12224. EXPECT_EQ("b", resb->body);
  12225. }
  12226. // Closing an idle keep-alive connection sends close_notify and returns. The
  12227. // server must not wait for the client's close_notify: an idle client never
  12228. // sends one, so the worker would be held until the read timeout expires, and
  12229. // stop() would wait for it.
  12230. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12232. ASSERT_TRUE(svr.is_valid());
  12233. svr.set_keep_alive_timeout(1);
  12234. svr.set_read_timeout(10, 0);
  12235. svr.Get("/", [](const Request &, Response &res) {
  12236. res.set_content("ok", "text/plain");
  12237. });
  12238. auto port = svr.bind_to_any_port(HOST);
  12239. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12240. auto se = detail::scope_exit([&] {
  12241. if (listen_thread.joinable()) {
  12242. svr.stop();
  12243. listen_thread.join();
  12244. }
  12245. });
  12246. svr.wait_until_ready();
  12247. SSLClient cli(HOST, port);
  12248. cli.enable_server_certificate_verification(false);
  12249. cli.set_keep_alive(true);
  12250. auto res = cli.Get("/");
  12251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12252. EXPECT_EQ(StatusCode::OK_200, res->status);
  12253. // Stay idle past the keep-alive timeout so the server closes the connection.
  12254. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12255. auto start = std::chrono::steady_clock::now();
  12256. svr.stop();
  12257. listen_thread.join();
  12258. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12259. std::chrono::steady_clock::now() - start)
  12260. .count();
  12261. EXPECT_LT(elapsed, 3000);
  12262. }
  12263. #endif
  12264. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12265. protected:
  12266. ServerTestWithAI_PASSIVE()
  12267. : cli_(HOST, PORT)
  12268. #ifdef CPPHTTPLIB_SSL_ENABLED
  12269. ,
  12270. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12271. #endif
  12272. {
  12273. #ifdef CPPHTTPLIB_SSL_ENABLED
  12274. cli_.enable_server_certificate_verification(false);
  12275. #endif
  12276. }
  12277. virtual void SetUp() {
  12278. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12279. res.set_content("Hello World!", "text/plain");
  12280. });
  12281. t_ = thread(
  12282. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12283. svr_.wait_until_ready();
  12284. }
  12285. virtual void TearDown() {
  12286. svr_.stop();
  12287. t_.join();
  12288. }
  12289. #ifdef CPPHTTPLIB_SSL_ENABLED
  12290. SSLClient cli_;
  12291. SSLServer svr_;
  12292. #else
  12293. Client cli_;
  12294. Server svr_;
  12295. #endif
  12296. thread t_;
  12297. };
  12298. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12299. auto res = cli_.Get("/hi");
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12303. EXPECT_EQ("Hello World!", res->body);
  12304. }
  12305. class ServerUpDownTest : public ::testing::Test {
  12306. protected:
  12307. ServerUpDownTest() : cli_(HOST, PORT) {}
  12308. virtual void SetUp() {
  12309. t_ = thread([&]() {
  12310. svr_.bind_to_any_port(HOST);
  12311. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12312. ASSERT_TRUE(svr_.listen_after_bind());
  12313. });
  12314. svr_.wait_until_ready();
  12315. }
  12316. virtual void TearDown() {
  12317. svr_.stop();
  12318. t_.join();
  12319. }
  12320. Client cli_;
  12321. Server svr_;
  12322. thread t_;
  12323. };
  12324. TEST_F(ServerUpDownTest, QuickStartStop) {
  12325. // Should not crash, especially when run with
  12326. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12327. }
  12328. class PayloadMaxLengthTest : public ::testing::Test {
  12329. protected:
  12330. PayloadMaxLengthTest()
  12331. : cli_(HOST, PORT)
  12332. #ifdef CPPHTTPLIB_SSL_ENABLED
  12333. ,
  12334. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12335. #endif
  12336. {
  12337. #ifdef CPPHTTPLIB_SSL_ENABLED
  12338. cli_.enable_server_certificate_verification(false);
  12339. #endif
  12340. }
  12341. virtual void SetUp() {
  12342. svr_.set_payload_max_length(8);
  12343. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12344. res.set_content("test", "text/plain");
  12345. });
  12346. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12347. svr_.wait_until_ready();
  12348. }
  12349. virtual void TearDown() {
  12350. svr_.stop();
  12351. t_.join();
  12352. }
  12353. #ifdef CPPHTTPLIB_SSL_ENABLED
  12354. SSLClient cli_;
  12355. SSLServer svr_;
  12356. #else
  12357. Client cli_;
  12358. Server svr_;
  12359. #endif
  12360. thread t_;
  12361. };
  12362. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12363. auto res = cli_.Post("/test", "123456789", "text/plain");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12366. res = cli_.Post("/test", "12345678", "text/plain");
  12367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12368. EXPECT_EQ(StatusCode::OK_200, res->status);
  12369. }
  12370. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12371. // Test chunked encoding with payload exceeding the 8-byte limit
  12372. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12373. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12375. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12376. }
  12377. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12378. // Test chunked encoding with payload within the 8-byte limit
  12379. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12380. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. EXPECT_EQ(StatusCode::OK_200, res->status);
  12383. }
  12384. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12385. // Test using send_request to send chunked data exceeding payload limit
  12386. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12387. "Host: " +
  12388. std::string(HOST) + ":" + std::to_string(PORT) +
  12389. "\r\n"
  12390. "Transfer-Encoding: chunked\r\n"
  12391. "Connection: close\r\n"
  12392. "\r\n"
  12393. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12394. "0123456789\r\n"
  12395. "0\r\n" // End chunk
  12396. "\r\n";
  12397. std::string response;
  12398. bool result = send_request(1, chunked_request, &response);
  12399. if (!result) {
  12400. // If send_request fails, it might be because the server closed the
  12401. // connection due to payload limit enforcement, which is acceptable
  12402. SUCCEED()
  12403. << "Server rejected oversized chunked request (connection closed)";
  12404. } else {
  12405. // If we got a response, check if it's an error response or connection was
  12406. // closed early Short response length indicates connection was closed due to
  12407. // payload limit
  12408. if (response.length() <= 10) {
  12409. SUCCEED() << "Server closed connection for oversized chunked request";
  12410. } else {
  12411. // Check for error status codes
  12412. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12413. response.find("Payload Too Large") != std::string::npos ||
  12414. response.find("400") != std::string::npos);
  12415. }
  12416. }
  12417. }
  12418. class LargePayloadMaxLengthTest : public ::testing::Test {
  12419. protected:
  12420. LargePayloadMaxLengthTest()
  12421. : cli_(HOST, PORT)
  12422. #ifdef CPPHTTPLIB_SSL_ENABLED
  12423. ,
  12424. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12425. #endif
  12426. {
  12427. #ifdef CPPHTTPLIB_SSL_ENABLED
  12428. cli_.enable_server_certificate_verification(false);
  12429. #endif
  12430. }
  12431. virtual void SetUp() {
  12432. // Set 10MB payload limit
  12433. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12434. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12435. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content("Large payload test", "text/plain");
  12437. });
  12438. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12439. svr_.wait_until_ready();
  12440. }
  12441. virtual void TearDown() {
  12442. svr_.stop();
  12443. t_.join();
  12444. }
  12445. #ifdef CPPHTTPLIB_SSL_ENABLED
  12446. SSLClient cli_;
  12447. SSLServer svr_;
  12448. #else
  12449. Client cli_;
  12450. Server svr_;
  12451. #endif
  12452. thread t_;
  12453. };
  12454. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12455. // Test chunked encoding with payload within 10MB limit
  12456. std::string medium_payload(5 * 1024 * 1024,
  12457. 'A'); // 5MB payload, within 10MB limit
  12458. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12460. EXPECT_EQ(StatusCode::OK_200, res->status);
  12461. }
  12462. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12463. // Test chunked encoding with payload exceeding 10MB limit
  12464. std::string large_payload(12 * 1024 * 1024,
  12465. 'B'); // 12MB payload, exceeds 10MB limit
  12466. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12467. // Server may either return 413 or close the connection
  12468. if (res) {
  12469. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12470. } else {
  12471. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12472. }
  12473. }
  12474. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12475. Server svr;
  12476. svr.Get("/", [](const Request &, Response &res) {
  12477. // Claims the most the client accepts, far more than it sends, then drops
  12478. // the connection.
  12479. res.set_content_provider(std::string().max_size(), "text/plain",
  12480. [](size_t, size_t, DataSink &sink) {
  12481. sink.write("abc", 3);
  12482. return false;
  12483. });
  12484. });
  12485. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12486. auto se = detail::scope_exit([&] {
  12487. svr.stop();
  12488. thread.join();
  12489. ASSERT_FALSE(svr.is_running());
  12490. });
  12491. svr.wait_until_ready();
  12492. Client cli(HOST, PORT);
  12493. cli.set_payload_max_length(0);
  12494. EXPECT_FALSE(cli.Get("/"));
  12495. }
  12496. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12497. // Stream API does, not as a plain read failure
  12498. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12499. Server svr;
  12500. svr.Get("/big", [](const Request &, Response &res) {
  12501. res.set_content(std::string(100000, 'b'), "text/plain");
  12502. });
  12503. auto port = svr.bind_to_any_port(HOST);
  12504. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12505. auto se = detail::scope_exit([&] {
  12506. svr.stop();
  12507. thread.join();
  12508. });
  12509. svr.wait_until_ready();
  12510. Client cli(HOST, port);
  12511. cli.set_payload_max_length(1000);
  12512. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12513. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12514. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12515. [](const char *, size_t) { return true; });
  12516. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12517. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12518. // Small on the wire, over the limit once decompressed
  12519. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12520. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12521. #endif
  12522. }
  12523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12524. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12525. // path.
  12526. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12527. Server svr;
  12528. const size_t LIMIT = 64 * 1024; // 64KB
  12529. svr.set_payload_max_length(LIMIT);
  12530. size_t total = 0;
  12531. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12532. const ContentReader &content_reader) {
  12533. content_reader([&](const char * /*data*/, size_t len) {
  12534. total += len;
  12535. return true;
  12536. });
  12537. res.status = 200;
  12538. res.set_content("stream_ok", "text/plain");
  12539. });
  12540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12541. auto se = detail::scope_exit([&] {
  12542. svr.stop();
  12543. thread.join();
  12544. ASSERT_FALSE(svr.is_running());
  12545. });
  12546. svr.wait_until_ready();
  12547. // Prepare 256KB raw data and gzip-compress it
  12548. std::string raw(256 * 1024, 'A');
  12549. std::string gz;
  12550. {
  12551. z_stream zs{};
  12552. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12553. Z_DEFAULT_STRATEGY);
  12554. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12555. zs.avail_in = static_cast<uInt>(raw.size());
  12556. char outbuf[4096];
  12557. int ret;
  12558. do {
  12559. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12560. zs.avail_out = sizeof(outbuf);
  12561. ret = deflate(&zs, Z_FINISH);
  12562. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12563. } while (ret != Z_STREAM_END);
  12564. deflateEnd(&zs);
  12565. }
  12566. Client cli(HOST, PORT);
  12567. cli.set_connection_timeout(std::chrono::seconds(5));
  12568. Headers headers = {{"Content-Encoding", "gzip"}};
  12569. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12570. "application/octet-stream");
  12571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12572. // Server must reject oversized decompressed payloads with 413.
  12573. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12574. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12575. EXPECT_LE(total, LIMIT);
  12576. }
  12577. #endif
  12578. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12579. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12580. // the payload must be passed through untouched instead of being rejected.
  12581. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12582. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12583. Server svr;
  12584. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12585. res.set_content(body, "image/jpeg");
  12586. res.set_header("Content-Encoding", "UTF-8");
  12587. });
  12588. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12589. res.set_content(body, "image/jpeg");
  12590. res.set_header("Content-Encoding", "identity");
  12591. });
  12592. svr.Post("/echo", [](const Request &req, Response &res) {
  12593. res.set_content(req.body, "image/jpeg");
  12594. });
  12595. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12596. auto se = detail::scope_exit([&] {
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. Client cli(HOST, PORT);
  12603. {
  12604. auto res = cli.Get("/image");
  12605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12606. EXPECT_EQ(StatusCode::OK_200, res->status);
  12607. EXPECT_EQ(body, res->body);
  12608. }
  12609. {
  12610. auto res = cli.Get("/identity");
  12611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12612. EXPECT_EQ(StatusCode::OK_200, res->status);
  12613. EXPECT_EQ(body, res->body);
  12614. }
  12615. {
  12616. // The same applies to a request body reaching the server.
  12617. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12618. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12620. EXPECT_EQ(StatusCode::OK_200, res->status);
  12621. EXPECT_EQ(body, res->body);
  12622. }
  12623. }
  12624. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12625. // gzip-encoded response even when the build has no zlib support.
  12626. static const char GZIPPED_HELLO_WORLD[] = {
  12627. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12628. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12629. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12630. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12631. // A content coding is a whole token, not something the field value merely
  12632. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12633. // as "fibre" look like Brotli, and turned a multi-coding value like
  12634. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12635. // it was never meant to see.
  12636. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12637. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12638. Server svr;
  12639. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12640. res.set_content(body, "image/jpeg");
  12641. res.set_header("Content-Encoding", "fibre");
  12642. });
  12643. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12644. res.set_content(body, "image/jpeg");
  12645. res.set_header("Content-Encoding", "gzip, br");
  12646. });
  12647. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12648. res.set_content(body, "image/jpeg");
  12649. res.set_header("Content-Encoding", "x-zstd-ish");
  12650. });
  12651. auto port = svr.bind_to_any_port(HOST);
  12652. thread t = thread([&]() { svr.listen_after_bind(); });
  12653. auto se = detail::scope_exit([&] {
  12654. svr.stop();
  12655. t.join();
  12656. ASSERT_FALSE(svr.is_running());
  12657. });
  12658. svr.wait_until_ready();
  12659. Client cli(HOST, port);
  12660. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12661. auto res = cli.Get(path);
  12662. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12663. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12664. // Not a coding we recognize, so the payload comes back untouched
  12665. EXPECT_EQ(body, res->body) << path;
  12666. }
  12667. }
  12668. // A content coding cpp-httplib recognizes but was not built with must be
  12669. // reported as such. Handing the still-compressed payload back to the caller
  12670. // would silently corrupt it.
  12671. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12672. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12673. Server svr;
  12674. // "image/jpeg" keeps the server from applying a content coding of its own,
  12675. // so the hand-crafted Content-Encoding below survives.
  12676. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12677. res.set_content(gzipped, "image/jpeg");
  12678. res.set_header("Content-Encoding", "gzip");
  12679. });
  12680. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12681. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12682. res.set_content(gzipped, "image/jpeg");
  12683. res.set_header("Content-Encoding", "GZIP");
  12684. });
  12685. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12686. auto se = detail::scope_exit([&] {
  12687. svr.stop();
  12688. t.join();
  12689. ASSERT_FALSE(svr.is_running());
  12690. });
  12691. svr.wait_until_ready();
  12692. Client cli(HOST, PORT);
  12693. {
  12694. auto res = cli.Get("/gzipped");
  12695. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12697. EXPECT_EQ("Hello World!", res->body);
  12698. #else
  12699. ASSERT_FALSE(res);
  12700. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12701. #endif
  12702. }
  12703. {
  12704. // open_stream() must behave the same way.
  12705. auto handle = cli.open_stream("GET", "/gzipped");
  12706. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12707. ASSERT_TRUE(handle.is_valid());
  12708. std::string received;
  12709. char buf[256];
  12710. ssize_t n;
  12711. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12712. received.append(buf, static_cast<size_t>(n));
  12713. }
  12714. EXPECT_EQ("Hello World!", received);
  12715. #else
  12716. EXPECT_FALSE(handle.is_valid());
  12717. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12718. #endif
  12719. }
  12720. {
  12721. // A differently-cased coding must not be mistaken for an unknown one, or
  12722. // the body would be handed back still compressed.
  12723. auto res = cli.Get("/gzipped-uppercase");
  12724. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12726. EXPECT_EQ("Hello World!", res->body);
  12727. #else
  12728. ASSERT_FALSE(res);
  12729. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12730. #endif
  12731. }
  12732. }
  12733. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12734. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12735. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12736. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12737. // body a second time and appending a second Content-Encoding field line, so
  12738. // clients that decode one coding per listed value handed back raw gzip bytes.
  12739. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12740. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12741. Server svr;
  12742. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12743. // keeps the server from applying a coding of its own.
  12744. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12745. res.set_content(gzipped, "text/plain");
  12746. res.set_header("Content-Encoding", "gzip");
  12747. });
  12748. auto port = svr.bind_to_any_port(HOST);
  12749. thread t = thread([&]() { svr.listen_after_bind(); });
  12750. auto se = detail::scope_exit([&] {
  12751. svr.stop();
  12752. t.join();
  12753. ASSERT_FALSE(svr.is_running());
  12754. });
  12755. svr.wait_until_ready();
  12756. Client cli(HOST, port);
  12757. Headers headers = {{"Accept-Encoding", "gzip"}};
  12758. auto res = cli.Get("/pre-gzipped", headers);
  12759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12760. EXPECT_EQ(StatusCode::OK_200, res->status);
  12761. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12762. EXPECT_EQ("Hello World!", res->body);
  12763. }
  12764. // set_compress(false) sends every handler response as it is, buffered or
  12765. // streamed
  12766. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12767. const std::string text(1000, 'a');
  12768. Server svr;
  12769. svr.set_compress(false);
  12770. svr.Get("/buffered", [&](const Request &, Response &res) {
  12771. res.set_content(text, "text/plain");
  12772. });
  12773. svr.Get("/streamed", [&](const Request &, Response &res) {
  12774. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12775. sink.write(text.data(), text.size());
  12776. sink.done();
  12777. return true;
  12778. });
  12779. });
  12780. auto port = svr.bind_to_any_port(HOST);
  12781. ASSERT_LT(0, port);
  12782. thread t = thread([&] { svr.listen_after_bind(); });
  12783. auto se = detail::scope_exit([&] {
  12784. svr.stop();
  12785. t.join();
  12786. ASSERT_FALSE(svr.is_running());
  12787. });
  12788. svr.wait_until_ready();
  12789. Client cli(HOST, port);
  12790. cli.set_decompress(false);
  12791. for (auto path : {"/buffered", "/streamed"}) {
  12792. SCOPED_TRACE(path);
  12793. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12795. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12796. EXPECT_EQ(text, res->body);
  12797. }
  12798. }
  12799. // A chunked provider settles its coding where the headers are written and
  12800. // reuses it at write time. Both ends of that have to hold: a handler's own
  12801. // Content-Encoding suppresses the coding, and a response without one is still
  12802. // compressed as it always was.
  12803. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12804. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12805. const std::string plain = "Hello World! Hello World! Hello World!";
  12806. Server svr;
  12807. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12808. res.set_header("Content-Encoding", "gzip");
  12809. res.set_chunked_content_provider(
  12810. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12811. sink.write(gzipped.data(), gzipped.size());
  12812. sink.done();
  12813. return true;
  12814. });
  12815. });
  12816. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12817. res.set_chunked_content_provider(
  12818. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12819. sink.write(plain.data(), plain.size());
  12820. sink.done();
  12821. return true;
  12822. });
  12823. });
  12824. auto port = svr.bind_to_any_port(HOST);
  12825. thread t = thread([&]() { svr.listen_after_bind(); });
  12826. auto se = detail::scope_exit([&] {
  12827. svr.stop();
  12828. t.join();
  12829. ASSERT_FALSE(svr.is_running());
  12830. });
  12831. svr.wait_until_ready();
  12832. Client cli(HOST, port);
  12833. Headers headers = {{"Accept-Encoding", "gzip"}};
  12834. {
  12835. auto res = cli.Get("/pre-gzipped", headers);
  12836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12837. EXPECT_EQ(StatusCode::OK_200, res->status);
  12838. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12839. EXPECT_EQ("Hello World!", res->body);
  12840. }
  12841. {
  12842. auto res = cli.Get("/negotiated", headers);
  12843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12844. EXPECT_EQ(StatusCode::OK_200, res->status);
  12845. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12846. EXPECT_EQ(plain, res->body);
  12847. }
  12848. }
  12849. #endif
  12850. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12851. // the same message as the comma-joined one, so both have to be read the same
  12852. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12853. // single gzip coding, and a body the sender says was encoded twice was handed
  12854. // back after one pass, still compressed but presented as decoded.
  12855. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12856. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12857. Server svr;
  12858. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12859. res.set_content(body, "image/jpeg");
  12860. res.headers.emplace("Content-Encoding", "gzip");
  12861. res.headers.emplace("Content-Encoding", "gzip");
  12862. });
  12863. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12864. res.set_content(body, "image/jpeg");
  12865. res.set_header("Content-Encoding", "gzip, gzip");
  12866. });
  12867. auto port = svr.bind_to_any_port(HOST);
  12868. thread t = thread([&]() { svr.listen_after_bind(); });
  12869. auto se = detail::scope_exit([&] {
  12870. svr.stop();
  12871. t.join();
  12872. ASSERT_FALSE(svr.is_running());
  12873. });
  12874. svr.wait_until_ready();
  12875. Client cli(HOST, port);
  12876. // Two codings is not something cpp-httplib decodes, so both representations
  12877. // take the pass-through path rather than one of them being gunzipped once.
  12878. for (const char *path : {"/split", "/joined"}) {
  12879. auto res = cli.Get(path);
  12880. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12881. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12882. EXPECT_EQ(body, res->body) << path;
  12883. }
  12884. }
  12885. // Regression test for DoS vulnerability: a malicious server sending a response
  12886. // without Content-Length header must not cause unbounded memory consumption on
  12887. // the client side. The client should stop reading after a reasonable limit,
  12888. // similar to the server-side set_payload_max_length protection.
  12889. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12890. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12891. #ifndef _WIN32
  12892. signal(SIGPIPE, SIG_IGN);
  12893. #endif
  12894. auto server_thread = std::thread([] {
  12895. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12896. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12897. default_socket_options(srv);
  12898. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12899. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12900. sockaddr_in addr{};
  12901. addr.sin_family = AF_INET;
  12902. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12903. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12904. int opt = 1;
  12905. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12906. #ifdef _WIN32
  12907. reinterpret_cast<const char *>(&opt),
  12908. #else
  12909. &opt,
  12910. #endif
  12911. sizeof(opt));
  12912. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12913. ::listen(srv, 1);
  12914. sockaddr_in cli_addr{};
  12915. socklen_t cli_len = sizeof(cli_addr);
  12916. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12917. if (cli != INVALID_SOCKET) {
  12918. char buf[4096];
  12919. ::recv(cli, buf, sizeof(buf), 0);
  12920. // Malicious response: no Content-Length, no chunked encoding
  12921. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12922. "Connection: close\r\n"
  12923. "\r\n";
  12924. ::send(cli,
  12925. #ifdef _WIN32
  12926. static_cast<const char *>(response_header.c_str()),
  12927. static_cast<int>(response_header.size()),
  12928. #else
  12929. response_header.c_str(), response_header.size(),
  12930. #endif
  12931. 0);
  12932. // Send 10MB of data
  12933. std::string chunk(64 * 1024, 'A');
  12934. size_t total_sent = 0;
  12935. while (total_sent < MALICIOUS_DATA_SIZE) {
  12936. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12937. auto sent = ::send(cli,
  12938. #ifdef _WIN32
  12939. static_cast<const char *>(chunk.c_str()),
  12940. static_cast<int>(to_send),
  12941. #else
  12942. chunk.c_str(), to_send,
  12943. #endif
  12944. 0);
  12945. if (sent <= 0) break;
  12946. total_sent += static_cast<size_t>(sent);
  12947. }
  12948. detail::close_socket(cli);
  12949. }
  12950. detail::close_socket(srv);
  12951. });
  12952. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12953. size_t total_read = 0;
  12954. {
  12955. Client cli("127.0.0.1", PORT + 2);
  12956. cli.set_read_timeout(5, 0);
  12957. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12958. auto stream = cli.open_stream("GET", "/malicious");
  12959. ASSERT_TRUE(stream.is_valid());
  12960. char buffer[64 * 1024];
  12961. ssize_t n;
  12962. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12963. total_read += static_cast<size_t>(n);
  12964. }
  12965. } // StreamHandle and Client destroyed here, closing the socket
  12966. server_thread.join();
  12967. // With set_payload_max_length, the client must stop reading before consuming
  12968. // all 10MB. The read loop should be cut off at or near the configured limit.
  12969. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12970. << "Client read " << total_read << " bytes, exceeding the configured "
  12971. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12972. }
  12973. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12974. // the entire response body without truncation.
  12975. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12976. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12977. #ifndef _WIN32
  12978. signal(SIGPIPE, SIG_IGN);
  12979. #endif
  12980. auto server_thread = std::thread([] {
  12981. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12982. default_socket_options(srv);
  12983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12984. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12985. sockaddr_in addr{};
  12986. addr.sin_family = AF_INET;
  12987. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12989. int opt = 1;
  12990. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12991. #ifdef _WIN32
  12992. reinterpret_cast<const char *>(&opt),
  12993. #else
  12994. &opt,
  12995. #endif
  12996. sizeof(opt));
  12997. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12998. ::listen(srv, 1);
  12999. sockaddr_in cli_addr{};
  13000. socklen_t cli_len = sizeof(cli_addr);
  13001. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13002. if (cli != INVALID_SOCKET) {
  13003. char buf[4096];
  13004. ::recv(cli, buf, sizeof(buf), 0);
  13005. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13006. "Connection: close\r\n"
  13007. "\r\n";
  13008. ::send(cli,
  13009. #ifdef _WIN32
  13010. static_cast<const char *>(response_header.c_str()),
  13011. static_cast<int>(response_header.size()),
  13012. #else
  13013. response_header.c_str(), response_header.size(),
  13014. #endif
  13015. 0);
  13016. std::string chunk(64 * 1024, 'A');
  13017. size_t total_sent = 0;
  13018. while (total_sent < DATA_SIZE) {
  13019. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13020. auto sent = ::send(cli,
  13021. #ifdef _WIN32
  13022. static_cast<const char *>(chunk.c_str()),
  13023. static_cast<int>(to_send),
  13024. #else
  13025. chunk.c_str(), to_send,
  13026. #endif
  13027. 0);
  13028. if (sent <= 0) break;
  13029. total_sent += static_cast<size_t>(sent);
  13030. }
  13031. #ifdef _WIN32
  13032. ::shutdown(cli, SD_SEND);
  13033. #else
  13034. ::shutdown(cli, SHUT_WR);
  13035. #endif
  13036. // Drain until the client closes its end, ensuring all data is delivered
  13037. char drain[1024];
  13038. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13039. detail::close_socket(cli);
  13040. }
  13041. detail::close_socket(srv);
  13042. });
  13043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13044. size_t total_read = 0;
  13045. {
  13046. Client cli("127.0.0.1", PORT + 2);
  13047. cli.set_read_timeout(5, 0);
  13048. cli.set_payload_max_length(0); // 0 means no limit
  13049. auto stream = cli.open_stream("GET", "/data");
  13050. ASSERT_TRUE(stream.is_valid());
  13051. char buffer[64 * 1024];
  13052. ssize_t n;
  13053. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13054. total_read += static_cast<size_t>(n);
  13055. }
  13056. }
  13057. server_thread.join();
  13058. EXPECT_EQ(total_read, DATA_SIZE)
  13059. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13060. << " bytes without truncation, but only read " << total_read << " bytes.";
  13061. }
  13062. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13063. // enormous Content-Length must not cause the client to pre-allocate a huge
  13064. // response body buffer. The reservation is capped at payload_max_length_, and
  13065. // the read itself fails when the body exceeds the limit.
  13066. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13067. #ifndef _WIN32
  13068. signal(SIGPIPE, SIG_IGN);
  13069. #endif
  13070. auto server_thread = std::thread([] {
  13071. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13072. default_socket_options(srv);
  13073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13075. sockaddr_in addr{};
  13076. addr.sin_family = AF_INET;
  13077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13079. int opt = 1;
  13080. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13081. #ifdef _WIN32
  13082. reinterpret_cast<const char *>(&opt),
  13083. #else
  13084. &opt,
  13085. #endif
  13086. sizeof(opt));
  13087. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13088. ::listen(srv, 1);
  13089. sockaddr_in cli_addr{};
  13090. socklen_t cli_len = sizeof(cli_addr);
  13091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13092. if (cli != INVALID_SOCKET) {
  13093. char buf[4096];
  13094. ::recv(cli, buf, sizeof(buf), 0);
  13095. // Malicious response: claim a 20GB body but send only a tiny payload.
  13096. std::string response = "HTTP/1.1 200 OK\r\n"
  13097. "Content-Length: 20000000000\r\n"
  13098. "\r\n"
  13099. "abc";
  13100. ::send(cli,
  13101. #ifdef _WIN32
  13102. static_cast<const char *>(response.c_str()),
  13103. static_cast<int>(response.size()),
  13104. #else
  13105. response.c_str(), response.size(),
  13106. #endif
  13107. 0);
  13108. detail::close_socket(cli);
  13109. }
  13110. detail::close_socket(srv);
  13111. });
  13112. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13113. {
  13114. Client cli("127.0.0.1", PORT + 2);
  13115. cli.set_read_timeout(5, 0);
  13116. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13117. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13118. // (server claims more bytes than payload_max_length permits), but it must
  13119. // not exhaust memory before getting there.
  13120. auto res = cli.Get("/malicious");
  13121. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13122. }
  13123. server_thread.join();
  13124. }
  13125. // Verify that content_receiver bypasses the default payload_max_length,
  13126. // allowing streaming downloads larger than 100MB without requiring an explicit
  13127. // set_payload_max_length call.
  13128. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13129. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13130. #ifndef _WIN32
  13131. signal(SIGPIPE, SIG_IGN);
  13132. #endif
  13133. auto server_thread = std::thread([] {
  13134. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13135. default_socket_options(srv);
  13136. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13137. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13138. sockaddr_in addr{};
  13139. addr.sin_family = AF_INET;
  13140. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13141. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13142. int opt = 1;
  13143. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13144. #ifdef _WIN32
  13145. reinterpret_cast<const char *>(&opt),
  13146. #else
  13147. &opt,
  13148. #endif
  13149. sizeof(opt));
  13150. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13151. ::listen(srv, 1);
  13152. sockaddr_in cli_addr{};
  13153. socklen_t cli_len = sizeof(cli_addr);
  13154. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13155. if (cli != INVALID_SOCKET) {
  13156. char buf[4096];
  13157. ::recv(cli, buf, sizeof(buf), 0);
  13158. // Response with Content-Length larger than default 100MB limit
  13159. auto content_length = std::to_string(DATA_SIZE);
  13160. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13161. "Content-Length: " +
  13162. content_length +
  13163. "\r\n"
  13164. "Connection: close\r\n"
  13165. "\r\n";
  13166. ::send(cli,
  13167. #ifdef _WIN32
  13168. static_cast<const char *>(response_header.c_str()),
  13169. static_cast<int>(response_header.size()),
  13170. #else
  13171. response_header.c_str(), response_header.size(),
  13172. #endif
  13173. 0);
  13174. std::string chunk(64 * 1024, 'A');
  13175. size_t total_sent = 0;
  13176. while (total_sent < DATA_SIZE) {
  13177. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13178. auto sent = ::send(cli,
  13179. #ifdef _WIN32
  13180. static_cast<const char *>(chunk.c_str()),
  13181. static_cast<int>(to_send),
  13182. #else
  13183. chunk.c_str(), to_send,
  13184. #endif
  13185. 0);
  13186. if (sent <= 0) break;
  13187. total_sent += static_cast<size_t>(sent);
  13188. }
  13189. detail::close_socket(cli);
  13190. }
  13191. detail::close_socket(srv);
  13192. });
  13193. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13194. size_t total_received = 0;
  13195. {
  13196. Client cli("127.0.0.1", PORT + 2);
  13197. cli.set_read_timeout(10, 0);
  13198. // Do NOT call set_payload_max_length — use the default 100MB limit
  13199. auto res =
  13200. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13201. total_received += data_length;
  13202. return true;
  13203. });
  13204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13205. EXPECT_EQ(StatusCode::OK_200, res->status);
  13206. }
  13207. server_thread.join();
  13208. EXPECT_EQ(total_received, DATA_SIZE)
  13209. << "With content_receiver, the client should read all " << DATA_SIZE
  13210. << " bytes despite the default 100MB payload_max_length, but only read "
  13211. << total_received << " bytes.";
  13212. }
  13213. // Verify that an explicit set_payload_max_length smaller than the response is
  13214. // enforced even when a content_receiver is used.
  13215. TEST(ClientVulnerabilityTest,
  13216. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13217. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13218. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13219. #ifndef _WIN32
  13220. signal(SIGPIPE, SIG_IGN);
  13221. #endif
  13222. auto server_thread = std::thread([] {
  13223. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13224. default_socket_options(srv);
  13225. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13226. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13227. sockaddr_in addr{};
  13228. addr.sin_family = AF_INET;
  13229. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13230. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13231. int opt = 1;
  13232. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13233. #ifdef _WIN32
  13234. reinterpret_cast<const char *>(&opt),
  13235. #else
  13236. &opt,
  13237. #endif
  13238. sizeof(opt));
  13239. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13240. ::listen(srv, 1);
  13241. sockaddr_in cli_addr{};
  13242. socklen_t cli_len = sizeof(cli_addr);
  13243. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13244. if (cli != INVALID_SOCKET) {
  13245. char buf[4096];
  13246. ::recv(cli, buf, sizeof(buf), 0);
  13247. auto content_length = std::to_string(DATA_SIZE);
  13248. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13249. "Content-Length: " +
  13250. content_length +
  13251. "\r\n"
  13252. "Connection: close\r\n"
  13253. "\r\n";
  13254. ::send(cli,
  13255. #ifdef _WIN32
  13256. static_cast<const char *>(response_header.c_str()),
  13257. static_cast<int>(response_header.size()),
  13258. #else
  13259. response_header.c_str(), response_header.size(),
  13260. #endif
  13261. 0);
  13262. std::string chunk(64 * 1024, 'A');
  13263. size_t total_sent = 0;
  13264. while (total_sent < DATA_SIZE) {
  13265. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13266. auto sent = ::send(cli,
  13267. #ifdef _WIN32
  13268. static_cast<const char *>(chunk.c_str()),
  13269. static_cast<int>(to_send),
  13270. #else
  13271. chunk.c_str(), to_send,
  13272. #endif
  13273. 0);
  13274. if (sent <= 0) break;
  13275. total_sent += static_cast<size_t>(sent);
  13276. }
  13277. detail::close_socket(cli);
  13278. }
  13279. detail::close_socket(srv);
  13280. });
  13281. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13282. size_t total_received = 0;
  13283. {
  13284. Client cli("127.0.0.1", PORT + 2);
  13285. cli.set_read_timeout(10, 0);
  13286. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13287. auto res =
  13288. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13289. total_received += data_length;
  13290. return true;
  13291. });
  13292. // Should fail because 200MB exceeds the explicit 150MB limit
  13293. EXPECT_FALSE(res);
  13294. }
  13295. server_thread.join();
  13296. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13297. << "Client with content_receiver should respect the explicit "
  13298. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13299. << total_received << " bytes.";
  13300. }
  13301. // Verify that an explicit set_payload_max_length larger than the response
  13302. // allows the content_receiver to read all data successfully.
  13303. TEST(ClientVulnerabilityTest,
  13304. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13305. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13306. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13307. #ifndef _WIN32
  13308. signal(SIGPIPE, SIG_IGN);
  13309. #endif
  13310. auto server_thread = std::thread([] {
  13311. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13312. default_socket_options(srv);
  13313. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13314. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13315. sockaddr_in addr{};
  13316. addr.sin_family = AF_INET;
  13317. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13318. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13319. int opt = 1;
  13320. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13321. #ifdef _WIN32
  13322. reinterpret_cast<const char *>(&opt),
  13323. #else
  13324. &opt,
  13325. #endif
  13326. sizeof(opt));
  13327. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13328. ::listen(srv, 1);
  13329. sockaddr_in cli_addr{};
  13330. socklen_t cli_len = sizeof(cli_addr);
  13331. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13332. if (cli != INVALID_SOCKET) {
  13333. char buf[4096];
  13334. ::recv(cli, buf, sizeof(buf), 0);
  13335. auto content_length = std::to_string(DATA_SIZE);
  13336. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13337. "Content-Length: " +
  13338. content_length +
  13339. "\r\n"
  13340. "Connection: close\r\n"
  13341. "\r\n";
  13342. ::send(cli,
  13343. #ifdef _WIN32
  13344. static_cast<const char *>(response_header.c_str()),
  13345. static_cast<int>(response_header.size()),
  13346. #else
  13347. response_header.c_str(), response_header.size(),
  13348. #endif
  13349. 0);
  13350. std::string chunk(64 * 1024, 'A');
  13351. size_t total_sent = 0;
  13352. while (total_sent < DATA_SIZE) {
  13353. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13354. auto sent = ::send(cli,
  13355. #ifdef _WIN32
  13356. static_cast<const char *>(chunk.c_str()),
  13357. static_cast<int>(to_send),
  13358. #else
  13359. chunk.c_str(), to_send,
  13360. #endif
  13361. 0);
  13362. if (sent <= 0) break;
  13363. total_sent += static_cast<size_t>(sent);
  13364. }
  13365. #ifdef _WIN32
  13366. ::shutdown(cli, SD_SEND);
  13367. #else
  13368. ::shutdown(cli, SHUT_WR);
  13369. #endif
  13370. char drain[1024];
  13371. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13372. detail::close_socket(cli);
  13373. }
  13374. detail::close_socket(srv);
  13375. });
  13376. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13377. size_t total_received = 0;
  13378. {
  13379. Client cli("127.0.0.1", PORT + 2);
  13380. cli.set_read_timeout(10, 0);
  13381. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13382. auto res =
  13383. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13384. total_received += data_length;
  13385. return true;
  13386. });
  13387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13388. EXPECT_EQ(StatusCode::OK_200, res->status);
  13389. }
  13390. server_thread.join();
  13391. EXPECT_EQ(total_received, DATA_SIZE)
  13392. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13393. << " bytes (larger than " << DATA_SIZE
  13394. << " bytes response), content_receiver should read all data, but only "
  13395. "read "
  13396. << total_received << " bytes.";
  13397. }
  13398. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13399. // Regression test for "zip bomb" attack on the client side: a malicious server
  13400. // sends a small gzip-compressed response that decompresses to a huge payload.
  13401. // The client must enforce payload_max_length on the decompressed size.
  13402. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13403. constexpr size_t DECOMPRESSED_SIZE =
  13404. 10 * 1024 * 1024; // 10MB after decompression
  13405. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13406. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13407. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13408. std::string compressed;
  13409. {
  13410. httplib::detail::gzip_compressor compressor;
  13411. bool ok =
  13412. compressor.compress(uncompressed.data(), uncompressed.size(),
  13413. /*last=*/true, [&](const char *buf, size_t len) {
  13414. compressed.append(buf, len);
  13415. return true;
  13416. });
  13417. ASSERT_TRUE(ok);
  13418. }
  13419. // Sanity: compressed data should be much smaller than the decompressed size
  13420. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13421. #ifndef _WIN32
  13422. signal(SIGPIPE, SIG_IGN);
  13423. #endif
  13424. // Set up the listening socket in the main thread so the server is guaranteed
  13425. // to be ready before the client connects (eliminates race condition).
  13426. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13427. default_socket_options(srv);
  13428. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13429. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13430. sockaddr_in addr{};
  13431. addr.sin_family = AF_INET;
  13432. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13433. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13434. int opt = 1;
  13435. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13436. #ifdef _WIN32
  13437. reinterpret_cast<const char *>(&opt),
  13438. #else
  13439. &opt,
  13440. #endif
  13441. sizeof(opt));
  13442. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13443. ASSERT_EQ(0, ::listen(srv, 1));
  13444. auto server_thread = std::thread([&compressed, srv] {
  13445. sockaddr_in cli_addr{};
  13446. socklen_t cli_len = sizeof(cli_addr);
  13447. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13448. if (cli != INVALID_SOCKET) {
  13449. // Read the full HTTP request (until \r\n\r\n)
  13450. char buf[4096];
  13451. size_t total = 0;
  13452. while (total < sizeof(buf)) {
  13453. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13454. if (n <= 0) break;
  13455. total += static_cast<size_t>(n);
  13456. // Check for end of headers
  13457. if (total >= 4) {
  13458. std::string req(buf, total);
  13459. if (req.find("\r\n\r\n") != std::string::npos) break;
  13460. }
  13461. }
  13462. // Malicious response: gzip-compressed body, no Content-Length
  13463. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13464. "Content-Encoding: gzip\r\n"
  13465. "Connection: close\r\n"
  13466. "\r\n";
  13467. ::send(cli,
  13468. #ifdef _WIN32
  13469. static_cast<const char *>(response_header.c_str()),
  13470. static_cast<int>(response_header.size()),
  13471. #else
  13472. response_header.c_str(), response_header.size(),
  13473. #endif
  13474. 0);
  13475. // Send the compressed payload (small on the wire, huge when decompressed)
  13476. size_t total_sent = 0;
  13477. while (total_sent < compressed.size()) {
  13478. auto to_send = std::min(compressed.size() - total_sent,
  13479. static_cast<size_t>(64 * 1024));
  13480. auto sent =
  13481. ::send(cli,
  13482. #ifdef _WIN32
  13483. static_cast<const char *>(compressed.c_str() + total_sent),
  13484. static_cast<int>(to_send),
  13485. #else
  13486. compressed.c_str() + total_sent, to_send,
  13487. #endif
  13488. 0);
  13489. if (sent <= 0) break;
  13490. total_sent += static_cast<size_t>(sent);
  13491. }
  13492. detail::close_socket(cli);
  13493. }
  13494. });
  13495. auto se = detail::scope_exit([&] {
  13496. detail::close_socket(srv);
  13497. server_thread.join();
  13498. });
  13499. size_t total_decompressed = 0;
  13500. {
  13501. Client cli("127.0.0.1", PORT + 3);
  13502. cli.set_read_timeout(5, 0);
  13503. cli.set_decompress(true);
  13504. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13505. auto stream = cli.open_stream("GET", "/zipbomb");
  13506. ASSERT_TRUE(stream.is_valid());
  13507. char buffer[64 * 1024];
  13508. ssize_t n;
  13509. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13510. total_decompressed += static_cast<size_t>(n);
  13511. }
  13512. }
  13513. // The decompressed size must be capped by payload_max_length. Without
  13514. // protection, the client would decompress the full 10MB from a tiny
  13515. // compressed payload, enabling a zip bomb DoS attack.
  13516. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13517. << "Client decompressed " << total_decompressed
  13518. << " bytes from a gzip response. The decompressed size should be "
  13519. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13520. }
  13521. #endif
  13522. TEST(HostAndPortPropertiesTest, NoSSL) {
  13523. httplib::Client cli("www.google.com", 1234);
  13524. ASSERT_EQ("www.google.com", cli.host());
  13525. ASSERT_EQ(1234, cli.port());
  13526. }
  13527. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13528. httplib::Client cli("www.google.com:1234");
  13529. ASSERT_EQ("www.google.com", cli.host());
  13530. ASSERT_EQ(1234, cli.port());
  13531. }
  13532. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13533. // Port number that overflows int — should not crash, client becomes invalid
  13534. httplib::Client cli("http://www.google.com:99999999999999999999");
  13535. ASSERT_FALSE(cli.is_valid());
  13536. }
  13537. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13538. // Port 99999 exceeds valid range (1-65535) — should not crash
  13539. httplib::Client cli("http://www.google.com:99999");
  13540. ASSERT_FALSE(cli.is_valid());
  13541. auto res = cli.Get("/");
  13542. EXPECT_FALSE(res);
  13543. EXPECT_EQ(Error::Connection, res.error());
  13544. }
  13545. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13546. httplib::Client cli("http://user:pass@localhost:1234");
  13547. ASSERT_FALSE(cli.is_valid());
  13548. EXPECT_FALSE(cli.Get("/"));
  13549. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13550. }
  13551. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13552. httplib::Client cli("http://www.google.com:80abc");
  13553. ASSERT_FALSE(cli.is_valid());
  13554. }
  13555. #ifdef CPPHTTPLIB_SSL_ENABLED
  13556. TEST(HostAndPortPropertiesTest, SSL) {
  13557. httplib::SSLClient cli("www.google.com");
  13558. ASSERT_EQ("www.google.com", cli.host());
  13559. ASSERT_EQ(443, cli.port());
  13560. }
  13561. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13562. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13563. std::string cert;
  13564. read_file(CA_CERT_FILE, cert);
  13565. httplib::SSLClient httplib_client("www.google.com");
  13566. // Load CA store first time
  13567. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13568. // Load CA store second time (update)
  13569. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13570. // Verify client is still valid and can make connections
  13571. httplib_client.enable_server_certificate_verification(true);
  13572. auto res = httplib_client.Get("/");
  13573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13574. // Google may return 200 or 301 depending on various factors
  13575. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13576. res->status == StatusCode::MovedPermanently_301);
  13577. }
  13578. TEST(SSLClientTest, ServerNameIndication_Online) {
  13579. auto host = "httpbingo.org";
  13580. auto path = std::string{"/get"};
  13581. SSLClient cli(host, 443);
  13582. auto res = cli.Get(path);
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. ASSERT_EQ(StatusCode::OK_200, res->status);
  13585. }
  13586. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13587. // Use a site that will cause SSL verification failure due to self-signed cert
  13588. SSLClient cli("self-signed.badssl.com", 443);
  13589. cli.enable_server_certificate_verification(true);
  13590. auto res = cli.Get("/");
  13591. ASSERT_TRUE(!res);
  13592. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13593. // Verify backend error is captured for SSLServerVerification
  13594. // This occurs when certificate verification fails
  13595. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13596. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13597. EXPECT_NE(0UL, res.ssl_backend_error());
  13598. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13599. res.ssl_error());
  13600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13601. #if !defined(_WIN32) || \
  13602. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13603. // On non-Windows or when Windows Schannel is disabled, the error comes
  13604. // from OpenSSL's verification
  13605. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13606. res.ssl_backend_error());
  13607. #endif
  13608. #endif
  13609. }
  13610. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13611. // Use a site where hostname doesn't match the certificate
  13612. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13613. SSLClient cli("wrong.host.badssl.com", 443);
  13614. cli.enable_server_certificate_verification(true);
  13615. cli.enable_server_hostname_verification(true);
  13616. auto res = cli.Get("/");
  13617. ASSERT_TRUE(!res);
  13618. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13619. // Verify backend error is captured for hostname verification failure
  13620. EXPECT_NE(0UL, res.ssl_backend_error());
  13621. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13622. res.ssl_error());
  13623. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13624. #if !defined(_WIN32) || \
  13625. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13626. // On non-Windows or when Windows Schannel is disabled, the error comes
  13627. // from OpenSSL's hostname verification
  13628. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13629. res.ssl_backend_error());
  13630. #endif
  13631. #endif
  13632. }
  13633. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13634. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13635. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13636. SSLClient cli("www.google.com", 443);
  13637. cli.enable_server_certificate_verification(true);
  13638. auto res = cli.Get("/");
  13639. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13640. }
  13641. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13642. SSLClient cli("www.google.com", 443);
  13643. cli.enable_server_certificate_verification(true);
  13644. cli.enable_windows_certificate_verification(false);
  13645. auto res = cli.Get("/");
  13646. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13647. }
  13648. // The server sends an intermediate cross-signed by a root Windows trusts,
  13649. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13650. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13651. SSLClient cli("accounts.spotify.com", 443);
  13652. auto res = cli.Get("/");
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13654. << " ssl_backend_error=" << res.ssl_backend_error();
  13655. }
  13656. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13657. // policy status, which no backend reports for a self-signed certificate.
  13658. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13659. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13660. ASSERT_TRUE(svr.is_valid());
  13661. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13662. auto se = detail::scope_exit([&] {
  13663. svr.stop();
  13664. t.join();
  13665. ASSERT_FALSE(svr.is_running());
  13666. });
  13667. svr.wait_until_ready();
  13668. SSLClient cli("127.0.0.1", PORT);
  13669. cli.set_connection_timeout(30);
  13670. auto res = cli.Get("/");
  13671. ASSERT_FALSE(res);
  13672. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13673. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13674. }
  13675. #endif
  13676. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13677. Client cli("https://google.com");
  13678. auto res = cli.Get("/");
  13679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13680. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13681. }
  13682. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13683. SSLClient cli("google.com");
  13684. cli.set_ca_cert_path(CA_CERT_FILE);
  13685. auto res = cli.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13688. }
  13689. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13690. SSLClient cli("google.com");
  13691. cli.enable_server_certificate_verification(true);
  13692. cli.set_ca_cert_path("hello");
  13693. auto res = cli.Get("/");
  13694. ASSERT_TRUE(!res);
  13695. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13696. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13697. // should be set
  13698. EXPECT_EQ(0, res.ssl_error());
  13699. // Verify backend error is captured for SSLLoadingCerts
  13700. // This error occurs when loading CA certificates fails
  13701. EXPECT_NE(0UL, res.ssl_backend_error());
  13702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13703. // OpenSSL specific error codes:
  13704. // > openssl errstr 0x80000002
  13705. // error:80000002:system library::No such file or directory
  13706. // > openssl errstr 0xA000126
  13707. // error:0A000126:SSL routines::unexpected eof while reading
  13708. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13709. res.ssl_backend_error() == 0xA000126);
  13710. #endif
  13711. }
  13712. TEST(SSLClientTest, ServerCertificateVerification4) {
  13713. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13714. ASSERT_TRUE(svr.is_valid());
  13715. svr.Get("/test", [&](const Request &, Response &res) {
  13716. res.set_content("test", "text/plain");
  13717. svr.stop();
  13718. ASSERT_TRUE(true);
  13719. });
  13720. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13721. auto se = detail::scope_exit([&] {
  13722. t.join();
  13723. ASSERT_FALSE(svr.is_running());
  13724. });
  13725. svr.wait_until_ready();
  13726. SSLClient cli("127.0.0.1", PORT);
  13727. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13728. cli.enable_server_certificate_verification(true);
  13729. cli.set_connection_timeout(30);
  13730. auto res = cli.Get("/test");
  13731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13732. ASSERT_EQ(StatusCode::OK_200, res->status);
  13733. }
  13734. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13735. std::string cert;
  13736. read_file(CA_CERT_FILE, cert);
  13737. SSLClient cli("google.com");
  13738. cli.load_ca_cert_store(cert.data(), cert.size());
  13739. const auto res = cli.Get("/");
  13740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13741. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13742. }
  13743. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13744. // clang-format off
  13745. static constexpr char cert[] =
  13746. "GlobalSign Root CA\n"
  13747. "==================\n"
  13748. "-----BEGIN CERTIFICATE-----\n"
  13749. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13750. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13751. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13752. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13753. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13754. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13755. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13756. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13757. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13758. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13759. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13760. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13761. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13762. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13763. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13764. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13765. "-----END CERTIFICATE-----\n";
  13766. // clang-format on
  13767. SSLClient cli("google.com");
  13768. cli.load_ca_cert_store(cert, sizeof(cert));
  13769. const auto res = cli.Get("/");
  13770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13771. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13772. }
  13773. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13774. SSLClient cli("www.youtube.com");
  13775. cli.set_ca_cert_path(CA_CERT_FILE);
  13776. cli.enable_server_certificate_verification(true);
  13777. cli.set_follow_location(true);
  13778. auto res = cli.Get("/");
  13779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13780. ASSERT_EQ(StatusCode::OK_200, res->status);
  13781. }
  13782. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13783. SSLClient cli("wWw.YouTube.Com");
  13784. cli.set_ca_cert_path(CA_CERT_FILE);
  13785. cli.enable_server_certificate_verification(true);
  13786. cli.enable_server_hostname_verification(true);
  13787. cli.set_follow_location(true);
  13788. auto res = cli.Get("/");
  13789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13790. ASSERT_EQ(StatusCode::OK_200, res->status);
  13791. }
  13792. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13793. SSLClient cli("gOoGlE.COm");
  13794. cli.enable_server_certificate_verification(true);
  13795. cli.enable_server_hostname_verification(true);
  13796. cli.set_follow_location(true);
  13797. auto res = cli.Get("/");
  13798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13799. ASSERT_EQ(StatusCode::OK_200, res->status);
  13800. }
  13801. TEST(SSLClientTest, Issue2004_Online) {
  13802. Client client("https://google.com");
  13803. client.set_follow_location(true);
  13804. auto res = client.Get("/");
  13805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13806. ASSERT_EQ(StatusCode::OK_200, res->status);
  13807. auto body = res->body;
  13808. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13809. }
  13810. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13811. // Create SSLClient with invalid cert/key to make is_valid() return false
  13812. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13813. "nonexistent_key.pem");
  13814. // is_valid() should be false due to cert loading failure
  13815. ASSERT_FALSE(cli.is_valid());
  13816. auto res = cli.Get("/");
  13817. ASSERT_FALSE(res);
  13818. EXPECT_EQ(Error::SSLConnection, res.error());
  13819. }
  13820. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13821. // Test for Issue #2251: SSL error not properly reported when client cert
  13822. // and key paths are swapped or mismatched
  13823. // This simulates the scenario where user accidentally swaps the cert and key
  13824. // files
  13825. // Using client cert file as private key and vice versa (completely wrong)
  13826. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13827. // Should fail validation due to cert/key mismatch
  13828. ASSERT_FALSE(cli.is_valid());
  13829. // Attempt to make a request should fail with proper error
  13830. auto res = cli.Get("/");
  13831. ASSERT_FALSE(res);
  13832. EXPECT_EQ(Error::SSLConnection, res.error());
  13833. // SSL error should be recorded in the Result object (this is the key fix for
  13834. // Issue #2251)
  13835. auto backend_error = res.ssl_backend_error();
  13836. EXPECT_NE(0u, backend_error);
  13837. }
  13838. // Tests cert/key mismatch detection at the TLS context level
  13839. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13840. // Test that using mismatched cert/key causes connection failure.
  13841. // We verify this at the SSLClient level rather than through internal
  13842. // TLS API functions.
  13843. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13844. cli.enable_server_certificate_verification(false);
  13845. cli.set_connection_timeout(2);
  13846. // The mismatch should cause a connection or handshake error
  13847. auto res = cli.Get("/test");
  13848. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13849. // Either way, the request should fail
  13850. EXPECT_FALSE(res);
  13851. }
  13852. #endif
  13853. #if 0
  13854. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13855. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13856. ASSERT_TRUE(cli != nullptr);
  13857. cli->set_address_family(AF_INET6);
  13858. cli->set_interface("en0");
  13859. auto res = cli->Get("/get");
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. ASSERT_EQ(StatusCode::OK_200, res->status);
  13862. }
  13863. #endif
  13864. // Client certificate tests - work with all TLS backends
  13865. #ifdef CPPHTTPLIB_SSL_ENABLED
  13866. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13867. void ClientCertPresent(
  13868. const std::string &client_cert_file,
  13869. const std::string &client_private_key_file,
  13870. const std::string &client_encrypted_private_key_pass = std::string(),
  13871. const ClientCertServerSetup &setup = nullptr) {
  13872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. if (setup) { setup(svr); }
  13875. svr.Get("/test", [&](const Request &req, Response &res) {
  13876. res.set_content("test", "text/plain");
  13877. auto cert = req.peer_cert();
  13878. ASSERT_TRUE(static_cast<bool>(cert));
  13879. std::string common_name = cert.subject_cn();
  13880. EXPECT_EQ("Common Name", common_name);
  13881. });
  13882. auto port = svr.bind_to_any_port(HOST);
  13883. ASSERT_LT(0, port);
  13884. thread t = thread([&]() { svr.listen_after_bind(); });
  13885. auto se = detail::scope_exit([&] {
  13886. svr.stop();
  13887. t.join();
  13888. ASSERT_FALSE(svr.is_running());
  13889. });
  13890. svr.wait_until_ready();
  13891. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13892. client_encrypted_private_key_pass);
  13893. cli.enable_server_certificate_verification(false);
  13894. cli.set_connection_timeout(30);
  13895. auto res = cli.Get("/test");
  13896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13897. ASSERT_EQ(StatusCode::OK_200, res->status);
  13898. }
  13899. TEST(SSLClientServerTest, ClientCertPresent) {
  13900. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13901. }
  13902. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13903. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13904. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13905. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13906. }
  13907. // Expects svr, which must require client certificates, to reject a client
  13908. // that has none
  13909. void RejectsClientWithoutCert(SSLServer &svr) {
  13910. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13911. auto port = svr.bind_to_any_port(HOST);
  13912. ASSERT_LT(0, port);
  13913. thread t = thread([&]() { svr.listen_after_bind(); });
  13914. auto se = detail::scope_exit([&] {
  13915. svr.stop();
  13916. t.join();
  13917. ASSERT_FALSE(svr.is_running());
  13918. });
  13919. svr.wait_until_ready();
  13920. SSLClient cli(HOST, port);
  13921. cli.set_connection_timeout(30);
  13922. // Skip the server certificate check, so that the request fails because the
  13923. // client certificate is missing rather than because cert.pem is not trusted
  13924. cli.enable_server_certificate_verification(false);
  13925. auto res = cli.Get("/test");
  13926. ASSERT_FALSE(res);
  13927. // The server rejects the client during the handshake, or on TLS 1.3 right
  13928. // after it, which the client notices on its first write or read
  13929. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13930. res.error() == Error::Write || res.error() == Error::Read)
  13931. << to_string(res.error());
  13932. if (res.error() == Error::SSLConnection) {
  13933. EXPECT_NE(0UL, res.ssl_backend_error());
  13934. }
  13935. // A rejection noticed on the write keeps the TLS error the write hit
  13936. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13937. }
  13938. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. if (setup) { setup(svr); }
  13942. RejectsClientWithoutCert(svr);
  13943. }
  13944. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13945. // A server that requires client certificates must keep requiring them after
  13946. // setup changes it, and keep accepting a client that has one
  13947. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13948. ClientCertMissing(setup);
  13949. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13950. setup);
  13951. }
  13952. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13953. ClientCertStillRequired([](SSLServer &svr) {
  13954. ASSERT_TRUE(tls::set_verify_callback(
  13955. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13956. });
  13957. }
  13958. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13959. ClientCertStillRequired([](SSLServer &svr) {
  13960. ASSERT_TRUE(tls::set_verify_callback(
  13961. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13962. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13963. });
  13964. }
  13965. // The client verifies the server certificate during the handshake, so a
  13966. // server that fails the check never gets the client certificate, even when a
  13967. // verifier of the client's own accepts it
  13968. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13969. struct Case {
  13970. const char *trusted_ca;
  13971. const char *host;
  13972. Error error;
  13973. };
  13974. // cert2.pem names localhost: the first client does not trust it, and the
  13975. // second trusts it but asks for another name
  13976. for (const auto &c :
  13977. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13978. Case{SERVER_CERT2_FILE, "example.com",
  13979. Error::SSLServerHostnameVerification}}) {
  13980. for (auto with_verifier : {false, true}) {
  13981. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13982. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13983. CLIENT_CA_CERT_FILE);
  13984. ASSERT_TRUE(svr.is_valid());
  13985. std::atomic<bool> got_client_cert{false};
  13986. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13987. [&](const tls::VerifyContext &) {
  13988. got_client_cert = true;
  13989. return true;
  13990. }));
  13991. auto port = svr.bind_to_any_port("127.0.0.1");
  13992. ASSERT_LT(0, port);
  13993. thread t = thread([&] { svr.listen_after_bind(); });
  13994. svr.wait_until_ready();
  13995. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13996. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  13997. cli.set_ca_cert_path(c.trusted_ca);
  13998. if (with_verifier) {
  13999. cli.set_server_certificate_verifier(
  14000. [](const tls::VerifyContext &) { return true; });
  14001. }
  14002. auto res = cli.Get("/");
  14003. EXPECT_FALSE(res);
  14004. EXPECT_EQ(c.error, res.error());
  14005. svr.stop();
  14006. t.join();
  14007. EXPECT_FALSE(got_client_cert);
  14008. }
  14009. }
  14010. }
  14011. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14012. std::string cert_pem, key_pem, ca_pem;
  14013. read_file(SERVER_CERT_FILE, cert_pem);
  14014. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14015. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14016. ASSERT_TRUE(
  14017. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14018. }
  14019. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14021. ASSERT_TRUE(svr.is_valid());
  14022. UpdateCertsPemWithClientCA(svr);
  14023. RejectsClientWithoutCert(svr);
  14024. }
  14025. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14026. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14027. }
  14028. // A TLS error from one request must not show up in a later request's Result
  14029. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14030. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14031. ASSERT_TRUE(svr.is_valid());
  14032. svr.Get("/test", [](const Request &, Response &res) {
  14033. res.set_content("test", "text/plain");
  14034. });
  14035. auto port = svr.bind_to_any_port(HOST);
  14036. ASSERT_LT(0, port);
  14037. thread t = thread([&]() { svr.listen_after_bind(); });
  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. SSLClient cli(HOST, port);
  14045. cli.set_connection_timeout(30);
  14046. cli.enable_server_hostname_verification(false);
  14047. // cert.pem is not trusted, so the handshake fails
  14048. ASSERT_FALSE(cli.Get("/test"));
  14049. cli.enable_server_certificate_verification(false);
  14050. auto res = cli.Get("/test");
  14051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14052. EXPECT_EQ(0, res.ssl_error());
  14053. EXPECT_EQ(0UL, res.ssl_backend_error());
  14054. }
  14055. // PEM memory-based constructor tests (works with all TLS backends).
  14056. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14057. // terminator after it.
  14058. void PemMemoryClientCertPresent(
  14059. const std::string &client_cert_file,
  14060. const std::string &client_private_key_file,
  14061. const std::string &client_encrypted_private_key_pass = std::string(),
  14062. bool exact_size = false) {
  14063. // Read PEM files into memory
  14064. std::string server_cert_pem, server_key_pem;
  14065. std::string client_ca_pem;
  14066. std::string client_cert_pem, client_key_pem;
  14067. read_file(SERVER_CERT_FILE, server_cert_pem);
  14068. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14069. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14070. read_file(client_cert_file, client_cert_pem);
  14071. read_file(client_private_key_file, client_key_pem);
  14072. std::list<std::vector<char>> exact_copies;
  14073. auto data = [&](const std::string &pem) -> const char * {
  14074. if (!exact_size) { return pem.c_str(); }
  14075. exact_copies.emplace_back(pem.begin(), pem.end());
  14076. return exact_copies.back().data();
  14077. };
  14078. // Create server with PEM memory
  14079. SSLServer::PemMemory server_pem = {
  14080. data(server_cert_pem),
  14081. server_cert_pem.size(),
  14082. data(server_key_pem),
  14083. server_key_pem.size(),
  14084. data(client_ca_pem),
  14085. client_ca_pem.size(),
  14086. nullptr // no password for server key
  14087. };
  14088. SSLServer svr(server_pem);
  14089. ASSERT_TRUE(svr.is_valid());
  14090. svr.Get("/test", [&](const Request &req, Response &res) {
  14091. res.set_content("test", "text/plain");
  14092. auto cert = req.peer_cert();
  14093. ASSERT_TRUE(static_cast<bool>(cert));
  14094. EXPECT_EQ("Common Name", cert.subject_cn());
  14095. });
  14096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14097. auto se = detail::scope_exit([&] {
  14098. svr.stop();
  14099. t.join();
  14100. ASSERT_FALSE(svr.is_running());
  14101. });
  14102. svr.wait_until_ready();
  14103. // Create client with PEM memory
  14104. const char *password = client_encrypted_private_key_pass.empty()
  14105. ? nullptr
  14106. : client_encrypted_private_key_pass.c_str();
  14107. SSLClient::PemMemory client_pem = {
  14108. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14109. client_key_pem.size(), password};
  14110. SSLClient cli(HOST, PORT, client_pem);
  14111. cli.enable_server_certificate_verification(false);
  14112. cli.set_connection_timeout(30);
  14113. auto res = cli.Get("/test");
  14114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14115. ASSERT_EQ(StatusCode::OK_200, res->status);
  14116. }
  14117. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14118. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14119. }
  14120. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14121. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14122. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14123. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14124. }
  14125. // A server built from PEM memory with a client CA requires client certificates,
  14126. // also when the CA is a NUL-terminated string passed with a length of 0
  14127. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14128. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14129. read_file(SERVER_CERT_FILE, server_cert_pem);
  14130. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14131. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14132. SSLServer::PemMemory server_pem = {
  14133. server_cert_pem.c_str(),
  14134. server_cert_pem.size(),
  14135. server_key_pem.c_str(),
  14136. server_key_pem.size(),
  14137. client_ca_pem.c_str(),
  14138. client_ca_pem.size(),
  14139. nullptr // no password for server key
  14140. };
  14141. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14142. SCOPED_TRACE(client_ca_pem_len);
  14143. server_pem.client_ca_pem_len = client_ca_pem_len;
  14144. SSLServer svr(server_pem);
  14145. ASSERT_TRUE(svr.is_valid());
  14146. RejectsClientWithoutCert(svr);
  14147. }
  14148. // An empty CA fails to load instead of turning the check off
  14149. server_pem.client_ca_pem = "";
  14150. server_pem.client_ca_pem_len = 0;
  14151. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14152. }
  14153. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14154. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14155. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14156. true);
  14157. }
  14158. // A length shorter than the PEM cuts it short, so it no longer loads
  14159. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14160. std::string cert, key;
  14161. read_file(SERVER_CERT_FILE, cert);
  14162. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14163. for (auto cut_cert : {true, false}) {
  14164. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14165. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14166. SSLServer::PemMemory server_pem = {
  14167. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14168. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14169. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14170. key_len, nullptr};
  14171. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14172. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14173. key.c_str(), key_len, nullptr};
  14174. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14175. }
  14176. }
  14177. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14178. class NoListenSSLServer : public SSLServer {
  14179. public:
  14180. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14181. const char *client_ca_cert_file_path,
  14182. const char *client_ca_cert_dir_path = nullptr)
  14183. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14184. client_ca_cert_dir_path),
  14185. stop_(false) {}
  14186. std::atomic_bool stop_;
  14187. private:
  14188. bool process_and_close_socket(socket_t /*sock*/) override {
  14189. // Don't create SSL context
  14190. while (!stop_.load()) {
  14191. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14192. }
  14193. return true;
  14194. }
  14195. };
  14196. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14197. CLIENT_CA_CERT_FILE);
  14198. ASSERT_TRUE(svr.is_valid());
  14199. svr.Get("/test", [&](const Request &, Response &res) {
  14200. res.set_content("test", "text/plain");
  14201. });
  14202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14203. auto se = detail::scope_exit([&] {
  14204. svr.stop_ = true;
  14205. svr.stop();
  14206. t.join();
  14207. ASSERT_FALSE(svr.is_running());
  14208. });
  14209. svr.wait_until_ready();
  14210. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14211. cli.enable_server_certificate_verification(false);
  14212. cli.set_connection_timeout(1);
  14213. auto res = cli.Get("/test");
  14214. ASSERT_TRUE(!res);
  14215. EXPECT_EQ(Error::SSLConnection, res.error());
  14216. // Timeout results in WantRead error code (maps to backend-specific value)
  14217. EXPECT_NE(0, res.ssl_error());
  14218. }
  14219. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14220. // Test SSLServer with client certificate verification using the standard
  14221. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14223. CLIENT_CA_CERT_DIR);
  14224. ASSERT_TRUE(svr.is_valid());
  14225. svr.Get("/test", [&](const Request &req, Response &res) {
  14226. res.set_content("test", "text/plain");
  14227. auto cert = req.peer_cert();
  14228. ASSERT_TRUE(static_cast<bool>(cert));
  14229. auto common_name = cert.subject_cn();
  14230. EXPECT_EQ("Common Name", common_name);
  14231. });
  14232. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14233. auto se = detail::scope_exit([&] {
  14234. svr.stop();
  14235. t.join();
  14236. ASSERT_FALSE(svr.is_running());
  14237. });
  14238. svr.wait_until_ready();
  14239. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14240. cli.enable_server_certificate_verification(false);
  14241. cli.set_connection_timeout(30);
  14242. auto res = cli.Get("/test");
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. ASSERT_EQ(StatusCode::OK_200, res->status);
  14245. }
  14246. // Test verify_hostname on every backend: a host is named by a SAN only
  14247. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14248. using namespace httplib::tls;
  14249. // We need a running server to test against
  14250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. ASSERT_TRUE(svr.is_valid());
  14252. svr.Get("/test", [](const Request &, Response &res) {
  14253. res.set_content("ok", "text/plain");
  14254. });
  14255. thread t([&]() { svr.listen(HOST, PORT); });
  14256. auto se = detail::scope_exit([&] {
  14257. svr.stop();
  14258. t.join();
  14259. });
  14260. svr.wait_until_ready();
  14261. bool verify_callback_called = false;
  14262. bool verify_result_wrong = false;
  14263. SSLClient cli(HOST, PORT);
  14264. cli.enable_server_certificate_verification(true);
  14265. cli.set_ca_cert_path(CA_CERT_FILE);
  14266. cli.set_connection_timeout(5);
  14267. // Note: Test certificate has CN="Common Name", not "localhost"
  14268. bool verify_result_cn = false;
  14269. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14270. verify_callback_called = true;
  14271. if (!ctx.cert) return false;
  14272. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14273. verify_result_cn = ctx.check_hostname("Common Name");
  14274. // Test 2: wrong hostname should not match
  14275. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14276. return true; // Accept for the purpose of this test
  14277. });
  14278. auto res = cli.Get("/test");
  14279. // The request may succeed or fail depending on cert configuration
  14280. // but the callback should have been called
  14281. ASSERT_TRUE(verify_callback_called)
  14282. << "Verify callback should have been called";
  14283. EXPECT_FALSE(verify_result_cn)
  14284. << "verify_hostname must not match the certificate CN (no SAN)";
  14285. // Wrong hostname should not match
  14286. EXPECT_FALSE(verify_result_wrong)
  14287. << "verify_hostname should not match 'wronghost.example.com'";
  14288. }
  14289. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14290. // backend verifies it.
  14291. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14292. // Certificate CN is "localhost" and it carries no SAN.
  14293. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14294. ASSERT_TRUE(svr.is_valid());
  14295. svr.Get("/test", [](const Request &, Response &res) {
  14296. res.set_content("ok", "text/plain");
  14297. });
  14298. auto port = svr.bind_to_any_port(HOST);
  14299. thread t([&]() { svr.listen_after_bind(); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. t.join();
  14303. });
  14304. svr.wait_until_ready();
  14305. SSLClient cli("localhost", port);
  14306. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14307. cli.enable_server_certificate_verification(true);
  14308. cli.set_connection_timeout(5);
  14309. auto res = cli.Get("/test");
  14310. ASSERT_FALSE(res);
  14311. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14312. // The same certificate is accepted once host name verification is off, so the
  14313. // failure above is the host name and not the chain.
  14314. cli.enable_server_hostname_verification(false);
  14315. res = cli.Get("/test");
  14316. ASSERT_TRUE(res) << to_string(res.error());
  14317. EXPECT_EQ(StatusCode::OK_200, res->status);
  14318. }
  14319. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14320. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14321. // X509_check_ip behavior and must hold for every backend.
  14322. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14323. using namespace httplib::tls;
  14324. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14325. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14326. ASSERT_TRUE(svr.is_valid());
  14327. svr.Get("/test", [](const Request &, Response &res) {
  14328. res.set_content("ok", "text/plain");
  14329. });
  14330. thread t([&]() { svr.listen(HOST, PORT); });
  14331. auto se = detail::scope_exit([&] {
  14332. svr.stop();
  14333. t.join();
  14334. });
  14335. svr.wait_until_ready();
  14336. bool verify_callback_called = false;
  14337. bool ip_matched_via_cn = true;
  14338. SSLClient cli(HOST, PORT);
  14339. cli.enable_server_certificate_verification(true);
  14340. cli.set_ca_cert_path(CA_CERT_FILE);
  14341. cli.set_connection_timeout(5);
  14342. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14343. verify_callback_called = true;
  14344. if (!ctx.cert) return false;
  14345. // The IP appears only in the CN, so it must NOT be accepted.
  14346. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14347. return true; // Accept for the purpose of this test
  14348. });
  14349. cli.Get("/test");
  14350. ASSERT_TRUE(verify_callback_called)
  14351. << "Verify callback should have been called";
  14352. EXPECT_FALSE(ip_matched_via_cn)
  14353. << "An IP host must not be authenticated via the certificate CN";
  14354. }
  14355. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14356. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14357. using namespace httplib::tls;
  14358. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14359. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14360. ASSERT_TRUE(svr.is_valid());
  14361. svr.Get("/test", [](const Request &, Response &res) {
  14362. res.set_content("ok", "text/plain");
  14363. });
  14364. thread t([&]() { svr.listen(HOST, PORT); });
  14365. auto se = detail::scope_exit([&] {
  14366. svr.stop();
  14367. t.join();
  14368. });
  14369. svr.wait_until_ready();
  14370. bool verify_callback_called = false;
  14371. bool san_matched = false;
  14372. bool wrong_ipv6_matched = true;
  14373. bool cn_ipv6_matched = true;
  14374. SSLClient cli(HOST, PORT);
  14375. cli.enable_server_certificate_verification(true);
  14376. cli.set_ca_cert_path(CA_CERT_FILE);
  14377. cli.set_connection_timeout(5);
  14378. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14379. verify_callback_called = true;
  14380. if (!ctx.cert) return false;
  14381. // Matches the IPv6 iPAddress SAN.
  14382. san_matched = ctx.check_hostname("2001:db8::1");
  14383. // A different IPv6 address must not match.
  14384. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14385. // "::1" lives only in the CN, so it must not be accepted.
  14386. cn_ipv6_matched = ctx.check_hostname("::1");
  14387. return true; // Accept for the purpose of this test
  14388. });
  14389. cli.Get("/test");
  14390. ASSERT_TRUE(verify_callback_called)
  14391. << "Verify callback should have been called";
  14392. EXPECT_TRUE(san_matched)
  14393. << "verify_hostname should match an IPv6 iPAddress SAN";
  14394. EXPECT_FALSE(wrong_ipv6_matched)
  14395. << "verify_hostname should not match a non-matching IPv6 address";
  14396. EXPECT_FALSE(cn_ipv6_matched)
  14397. << "An IPv6 host must not be authenticated via the certificate CN";
  14398. }
  14399. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14400. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14401. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14402. using namespace httplib::tls;
  14403. // SANs: DNS:a.zz, IP:42.46.122.122
  14404. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14405. ASSERT_TRUE(svr.is_valid());
  14406. svr.Get("/test", [](const Request &, Response &res) {
  14407. res.set_content("ok", "text/plain");
  14408. });
  14409. auto port = svr.bind_to_any_port(HOST);
  14410. thread t([&]() { svr.listen_after_bind(); });
  14411. auto se = detail::scope_exit([&] {
  14412. svr.stop();
  14413. t.join();
  14414. });
  14415. svr.wait_until_ready();
  14416. bool verify_callback_called = false;
  14417. bool dns_san_matched = false;
  14418. bool ip_san_matched = false;
  14419. bool ip_matched_via_dns_san = true;
  14420. bool dns_matched_via_ip_san = true;
  14421. bool cn_matched_next_to_dns_san = true;
  14422. SSLClient cli(HOST, port);
  14423. cli.enable_server_certificate_verification(true);
  14424. cli.set_ca_cert_path(CA_CERT_FILE);
  14425. cli.set_connection_timeout(5);
  14426. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14427. verify_callback_called = true;
  14428. if (!ctx.cert) return false;
  14429. dns_san_matched = ctx.check_hostname("a.zz");
  14430. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14431. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14432. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14433. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14434. return true; // Accept for the purpose of this test
  14435. });
  14436. cli.Get("/test");
  14437. ASSERT_TRUE(verify_callback_called)
  14438. << "Verify callback should have been called";
  14439. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14440. EXPECT_TRUE(ip_san_matched)
  14441. << "verify_hostname should match an iPAddress SAN";
  14442. EXPECT_FALSE(ip_matched_via_dns_san)
  14443. << "An IP host must not be authenticated via a dNSName SAN";
  14444. EXPECT_FALSE(dns_matched_via_ip_san)
  14445. << "A DNS host must not be authenticated via an iPAddress SAN";
  14446. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14447. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14448. }
  14449. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14450. // "www.*.example.test" names one host and not every host under example.test.
  14451. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14452. using namespace httplib::tls;
  14453. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14454. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14455. ASSERT_TRUE(svr.is_valid());
  14456. svr.Get("/test", [](const Request &, Response &res) {
  14457. res.set_content("ok", "text/plain");
  14458. });
  14459. auto port = svr.bind_to_any_port(HOST);
  14460. thread t([&]() { svr.listen_after_bind(); });
  14461. auto se = detail::scope_exit([&] {
  14462. svr.stop();
  14463. t.join();
  14464. });
  14465. svr.wait_until_ready();
  14466. bool verify_callback_called = false;
  14467. bool leftmost_wildcard_matched = false;
  14468. bool wildcard_spanned_labels = true;
  14469. bool inner_wildcard_matched = true;
  14470. SSLClient cli(HOST, port);
  14471. cli.enable_server_certificate_verification(true);
  14472. cli.set_ca_cert_path(CA_CERT_FILE);
  14473. cli.set_connection_timeout(5);
  14474. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14475. verify_callback_called = true;
  14476. if (!ctx.cert) return false;
  14477. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14478. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14479. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14480. return true; // Accept for the purpose of this test
  14481. });
  14482. cli.Get("/test");
  14483. ASSERT_TRUE(verify_callback_called)
  14484. << "Verify callback should have been called";
  14485. EXPECT_TRUE(leftmost_wildcard_matched)
  14486. << "A leftmost wildcard should match a single label";
  14487. EXPECT_FALSE(wildcard_spanned_labels)
  14488. << "A wildcard label must not match more than one label";
  14489. EXPECT_FALSE(inner_wildcard_matched)
  14490. << "A wildcard outside the leftmost label must not be honoured";
  14491. }
  14492. // sans() must report each SAN entry under its own type.
  14493. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14494. using namespace httplib::tls;
  14495. // SANs: DNS:a.zz, IP:42.46.122.122
  14496. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14497. ASSERT_TRUE(svr.is_valid());
  14498. svr.Get("/test", [](const Request &, Response &res) {
  14499. res.set_content("ok", "text/plain");
  14500. });
  14501. auto port = svr.bind_to_any_port(HOST);
  14502. thread t([&]() { svr.listen_after_bind(); });
  14503. auto se = detail::scope_exit([&] {
  14504. svr.stop();
  14505. t.join();
  14506. });
  14507. svr.wait_until_ready();
  14508. bool verify_callback_called = false;
  14509. std::vector<SanEntry> sans;
  14510. SSLClient cli(HOST, port);
  14511. cli.enable_server_certificate_verification(true);
  14512. cli.set_ca_cert_path(CA_CERT_FILE);
  14513. cli.set_connection_timeout(5);
  14514. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14515. verify_callback_called = true;
  14516. if (!ctx.cert) return false;
  14517. sans = ctx.sans();
  14518. return true; // Accept for the purpose of this test
  14519. });
  14520. cli.Get("/test");
  14521. ASSERT_TRUE(verify_callback_called)
  14522. << "Verify callback should have been called";
  14523. auto has_san = [&](SanType type, const std::string &value) {
  14524. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14525. return san.type == type && san.value == value;
  14526. });
  14527. };
  14528. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14529. << "sans() should report the dNSName SAN";
  14530. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14531. << "sans() should report the iPAddress SAN";
  14532. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14533. << "sans() must not report the dNSName SAN as an address";
  14534. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14535. << "sans() must not report the iPAddress SAN as a DNS name";
  14536. }
  14537. #endif
  14538. // mbedTLS-specific callback constructor test
  14539. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14540. #ifdef CPPHTTPLIB_SSL_ENABLED
  14541. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14543. ASSERT_TRUE(svr.is_valid());
  14544. // Set up a handler to verify client certificate is present
  14545. bool client_cert_verified = false;
  14546. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14547. // Verify that client certificate was provided
  14548. client_cert_verified = true;
  14549. res.set_content("success", "text/plain");
  14550. });
  14551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14552. auto se = detail::scope_exit([&] {
  14553. svr.stop();
  14554. t.join();
  14555. ASSERT_FALSE(svr.is_running());
  14556. });
  14557. svr.wait_until_ready();
  14558. // Client with certificate
  14559. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14560. cli.enable_server_certificate_verification(false);
  14561. cli.set_connection_timeout(30);
  14562. auto res = cli.Get("/test");
  14563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14564. ASSERT_EQ(StatusCode::OK_200, res->status);
  14565. ASSERT_TRUE(client_cert_verified);
  14566. EXPECT_EQ("success", res->body);
  14567. }
  14568. #endif
  14569. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14570. // backends
  14571. #ifdef CPPHTTPLIB_SSL_ENABLED
  14572. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14573. using namespace httplib::tls;
  14574. // Test that when client CA cert file is provided,
  14575. // the server properly requests and validates client certificates
  14576. // Create a server with client authentication
  14577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14578. ASSERT_TRUE(svr.is_valid());
  14579. bool handler_called = false;
  14580. svr.Get("/test", [&](const Request &req, Response &res) {
  14581. handler_called = true;
  14582. // Verify that a client certificate was provided
  14583. auto cert = req.peer_cert();
  14584. ASSERT_TRUE(static_cast<bool>(cert));
  14585. // Get the issuer name
  14586. std::string issuer_str = cert.issuer_name();
  14587. ASSERT_FALSE(issuer_str.empty());
  14588. // The client certificate should be issued by our test CA
  14589. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14590. res.set_content("authenticated", "text/plain");
  14591. });
  14592. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14593. auto se = detail::scope_exit([&] {
  14594. svr.stop();
  14595. t.join();
  14596. ASSERT_FALSE(svr.is_running());
  14597. });
  14598. svr.wait_until_ready();
  14599. // Connect with a client certificate issued by the CA
  14600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14601. cli.enable_server_certificate_verification(false);
  14602. cli.set_connection_timeout(30);
  14603. auto res = cli.Get("/test");
  14604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14605. ASSERT_EQ(StatusCode::OK_200, res->status);
  14606. ASSERT_TRUE(handler_called);
  14607. EXPECT_EQ("authenticated", res->body);
  14608. }
  14609. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14610. using namespace httplib::tls;
  14611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14612. ASSERT_TRUE(svr.is_valid());
  14613. svr.Get("/test", [](const Request &, Response &res) {
  14614. res.set_content("ok", "text/plain");
  14615. });
  14616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14617. auto se = detail::scope_exit([&] {
  14618. svr.stop();
  14619. t.join();
  14620. });
  14621. svr.wait_until_ready();
  14622. SSLClient cli(HOST, PORT);
  14623. cli.enable_server_certificate_verification(false);
  14624. cli.set_connection_timeout(30);
  14625. bool cert_checked = false;
  14626. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14627. if (ctx.cert) {
  14628. auto sans = ctx.sans();
  14629. // Test certificate may or may not have SANs - just verify the API
  14630. // works If SANs exist, verify the types are valid
  14631. for (const auto &san : sans) {
  14632. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14633. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14634. san.type == SanType::OTHER);
  14635. EXPECT_FALSE(san.value.empty());
  14636. }
  14637. cert_checked = true;
  14638. }
  14639. return true;
  14640. });
  14641. auto res = cli.Get("/test");
  14642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14643. EXPECT_TRUE(cert_checked);
  14644. }
  14645. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14646. using namespace httplib::tls;
  14647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14648. ASSERT_TRUE(svr.is_valid());
  14649. svr.Get("/test", [](const Request &, Response &res) {
  14650. res.set_content("ok", "text/plain");
  14651. });
  14652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14653. auto se = detail::scope_exit([&] {
  14654. svr.stop();
  14655. t.join();
  14656. });
  14657. svr.wait_until_ready();
  14658. SSLClient cli(HOST, PORT);
  14659. cli.enable_server_certificate_verification(false);
  14660. cli.set_connection_timeout(30);
  14661. bool validity_checked = false;
  14662. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14663. if (ctx.cert) {
  14664. time_t not_before = 0, not_after = 0;
  14665. bool result = ctx.validity(not_before, not_after);
  14666. EXPECT_TRUE(result);
  14667. // Verify that not_before < now < not_after for a valid cert
  14668. time_t now = time(nullptr);
  14669. EXPECT_LT(not_before, now);
  14670. EXPECT_GT(not_after, now);
  14671. validity_checked = true;
  14672. }
  14673. return true;
  14674. });
  14675. auto res = cli.Get("/test");
  14676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14677. EXPECT_TRUE(validity_checked);
  14678. }
  14679. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14680. using namespace httplib::tls;
  14681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14682. ASSERT_TRUE(svr.is_valid());
  14683. svr.Get("/test", [](const Request &, Response &res) {
  14684. res.set_content("ok", "text/plain");
  14685. });
  14686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14687. auto se = detail::scope_exit([&] {
  14688. svr.stop();
  14689. t.join();
  14690. });
  14691. svr.wait_until_ready();
  14692. SSLClient cli(HOST, PORT);
  14693. cli.enable_server_certificate_verification(false);
  14694. cli.set_connection_timeout(30);
  14695. bool serial_checked = false;
  14696. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14697. if (ctx.cert) {
  14698. std::string serial = ctx.serial();
  14699. EXPECT_FALSE(serial.empty());
  14700. // Serial should be a hex string
  14701. for (char c : serial) {
  14702. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14703. (c >= 'a' && c <= 'f'));
  14704. }
  14705. serial_checked = true;
  14706. }
  14707. return true;
  14708. });
  14709. auto res = cli.Get("/test");
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. EXPECT_TRUE(serial_checked);
  14712. }
  14713. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14714. // Test 1: Valid CA file - no error should be recorded
  14715. {
  14716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14717. CLIENT_CA_CERT_FILE);
  14718. ASSERT_TRUE(svr.is_valid());
  14719. // With valid setup, last_ssl_error should be 0
  14720. EXPECT_EQ(0, svr.ssl_last_error());
  14721. }
  14722. // Test 2: Invalid CA file content
  14723. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14724. {
  14725. // Create a temporary file with completely invalid content
  14726. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14727. {
  14728. std::ofstream ofs(temp_invalid_ca);
  14729. ofs << "This is not a certificate file at all\n";
  14730. ofs << "Just plain text content\n";
  14731. }
  14732. // Create server with invalid CA file
  14733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14734. // Clean up temporary file
  14735. std::remove(temp_invalid_ca);
  14736. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14737. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14738. // Note: SSL_CTX_load_verify_locations typically fails first,
  14739. // but our error handling code path is still exercised
  14740. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14741. }
  14742. }
  14743. TEST(VerifyCallbackTest, VerifyContextFields) {
  14744. using namespace httplib::tls;
  14745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14746. ASSERT_TRUE(svr.is_valid());
  14747. svr.Get("/test", [](const Request &, Response &res) {
  14748. res.set_content("ok", "text/plain");
  14749. });
  14750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14751. auto se = detail::scope_exit([&] {
  14752. svr.stop();
  14753. t.join();
  14754. });
  14755. svr.wait_until_ready();
  14756. SSLClient cli(HOST, PORT);
  14757. cli.enable_server_certificate_verification(false);
  14758. cli.set_connection_timeout(30);
  14759. int callback_count = 0;
  14760. bool saw_leaf_cert = false;
  14761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14762. if (ctx.cert) {
  14763. callback_count++;
  14764. // We should see at least one certificate (the leaf)
  14765. std::string cn = ctx.subject_cn();
  14766. if (!cn.empty()) { saw_leaf_cert = true; }
  14767. // Verify context fields are populated
  14768. EXPECT_NE(ctx.session, nullptr);
  14769. EXPECT_GE(ctx.depth, 0);
  14770. }
  14771. return true;
  14772. });
  14773. auto res = cli.Get("/test");
  14774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14775. EXPECT_GT(callback_count, 0);
  14776. EXPECT_TRUE(saw_leaf_cert);
  14777. }
  14778. // A verifier that accepts runs alongside the built-in verification, and is the
  14779. // only check once that is turned off.
  14780. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14781. using namespace httplib::tls;
  14782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14783. ASSERT_TRUE(svr.is_valid());
  14784. svr.Get("/test", [](const Request &, Response &res) {
  14785. res.set_content("ok", "text/plain");
  14786. });
  14787. auto port = svr.bind_to_any_port(HOST);
  14788. thread t([&]() { svr.listen_after_bind(); });
  14789. auto se = detail::scope_exit([&] {
  14790. svr.stop();
  14791. t.join();
  14792. });
  14793. svr.wait_until_ready();
  14794. SSLClient cli(HOST, port);
  14795. cli.enable_server_hostname_verification(false);
  14796. auto calls = 0;
  14797. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14798. calls++;
  14799. return true;
  14800. });
  14801. // cert.pem is not trusted
  14802. auto res = cli.Get("/test");
  14803. ASSERT_FALSE(res);
  14804. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14805. EXPECT_GT(calls, 0);
  14806. cli.enable_server_certificate_verification(false);
  14807. res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ("ok", res->body);
  14810. }
  14811. // A verifier belongs to the client that set it, not to the thread that set it.
  14812. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14813. using namespace httplib::tls;
  14814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14815. ASSERT_TRUE(svr.is_valid());
  14816. svr.Get("/test", [](const Request &, Response &res) {
  14817. res.set_content("ok", "text/plain");
  14818. });
  14819. auto port = svr.bind_to_any_port(HOST);
  14820. thread t([&]() { svr.listen_after_bind(); });
  14821. auto se = detail::scope_exit([&] {
  14822. svr.stop();
  14823. t.join();
  14824. });
  14825. svr.wait_until_ready();
  14826. auto rejecting_calls = 0;
  14827. SSLClient rejecting(HOST, port);
  14828. rejecting.enable_server_certificate_verification(false);
  14829. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14830. rejecting_calls++;
  14831. return false;
  14832. });
  14833. auto accepting_calls = 0;
  14834. SSLClient accepting(HOST, port);
  14835. accepting.enable_server_certificate_verification(false);
  14836. // Set on another thread than the requests below.
  14837. thread([&]() {
  14838. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14839. accepting_calls++;
  14840. return true;
  14841. });
  14842. }).join();
  14843. // Requested on another thread than the verifier was set on.
  14844. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14845. EXPECT_GT(rejecting_calls, 0);
  14846. auto res = accepting.Get("/test");
  14847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14848. EXPECT_GT(accepting_calls, 0);
  14849. }
  14850. // A verifier replaced while a handshake runs it lives until it returns.
  14851. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14852. using namespace httplib::tls;
  14853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14854. ASSERT_TRUE(svr.is_valid());
  14855. svr.Get("/test", [](const Request &, Response &res) {
  14856. res.set_content("ok", "text/plain");
  14857. });
  14858. auto port = svr.bind_to_any_port(HOST);
  14859. thread t([&]() { svr.listen_after_bind(); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop();
  14862. t.join();
  14863. });
  14864. svr.wait_until_ready();
  14865. SSLClient cli(HOST, port);
  14866. cli.enable_server_certificate_verification(false);
  14867. std::promise<void> entered;
  14868. std::promise<void> replaced;
  14869. auto replaced_future = replaced.get_future();
  14870. auto first_call = true;
  14871. // Long enough to live on the heap
  14872. std::string expected(64, 'v');
  14873. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14874. if (first_call) {
  14875. first_call = false;
  14876. entered.set_value();
  14877. replaced_future.wait();
  14878. }
  14879. return expected == std::string(64, 'v');
  14880. });
  14881. thread request([&]() {
  14882. auto res = cli.Get("/test");
  14883. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14884. });
  14885. entered.get_future().wait();
  14886. cli.set_server_certificate_verifier(
  14887. [](const VerifyContext &) { return true; });
  14888. replaced.set_value();
  14889. request.join();
  14890. }
  14891. // VerifyContext::session is the same handle the other tls:: functions take.
  14892. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14893. using namespace httplib::tls;
  14894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14895. ASSERT_TRUE(svr.is_valid());
  14896. svr.Get("/test", [](const Request &, Response &res) {
  14897. res.set_content("ok", "text/plain");
  14898. });
  14899. auto port = svr.bind_to_any_port(HOST);
  14900. thread t([&]() { svr.listen_after_bind(); });
  14901. auto se = detail::scope_exit([&] {
  14902. svr.stop();
  14903. t.join();
  14904. });
  14905. svr.wait_until_ready();
  14906. SSLClient cli(HOST, port);
  14907. cli.enable_server_certificate_verification(false);
  14908. session_t verifier_session = nullptr;
  14909. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14910. verifier_session = ctx.session;
  14911. return true;
  14912. });
  14913. session_t session_verifier_session = nullptr;
  14914. cli.set_session_verifier([&](session_t session) {
  14915. session_verifier_session = session;
  14916. return SSLVerifierResponse::NoDecisionMade;
  14917. });
  14918. auto res = cli.Get("/test");
  14919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14920. EXPECT_NE(nullptr, verifier_session);
  14921. EXPECT_EQ(session_verifier_session, verifier_session);
  14922. }
  14923. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14924. using httplib::tls::TlsError;
  14925. // Test that verify_error_to_string returns empty for success
  14926. std::string success_str = TlsError::verify_error_to_string(0);
  14927. EXPECT_TRUE(success_str.empty());
  14928. // Test that verify_error_to_string returns non-empty for error codes
  14929. // Using a common error code (certificate expired)
  14930. std::string error_str =
  14931. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14932. EXPECT_FALSE(error_str.empty());
  14933. }
  14934. TEST(SessionVerifierTest, CertificateAccepted) {
  14935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14936. ASSERT_TRUE(svr.is_valid());
  14937. svr.Get("/test", [](const Request &, Response &res) {
  14938. res.set_content("ok", "text/plain");
  14939. });
  14940. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14941. auto se = detail::scope_exit([&] {
  14942. svr.stop();
  14943. t.join();
  14944. });
  14945. svr.wait_until_ready();
  14946. SSLClient cli(HOST, PORT);
  14947. cli.enable_server_certificate_verification(false);
  14948. cli.set_connection_timeout(30);
  14949. bool callback_called = false;
  14950. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14951. EXPECT_NE(session, nullptr);
  14952. callback_called = true;
  14953. return SSLVerifierResponse::CertificateAccepted;
  14954. });
  14955. auto res = cli.Get("/test");
  14956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14957. EXPECT_EQ(200, res->status);
  14958. EXPECT_TRUE(callback_called);
  14959. }
  14960. TEST(SessionVerifierTest, CertificateRejected) {
  14961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14962. ASSERT_TRUE(svr.is_valid());
  14963. svr.Get("/test", [](const Request &, Response &res) {
  14964. res.set_content("ok", "text/plain");
  14965. });
  14966. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14967. auto se = detail::scope_exit([&] {
  14968. svr.stop();
  14969. t.join();
  14970. });
  14971. svr.wait_until_ready();
  14972. SSLClient cli(HOST, PORT);
  14973. cli.enable_server_certificate_verification(false);
  14974. cli.set_connection_timeout(30);
  14975. bool callback_called = false;
  14976. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14977. EXPECT_NE(session, nullptr);
  14978. callback_called = true;
  14979. return SSLVerifierResponse::CertificateRejected;
  14980. });
  14981. auto res = cli.Get("/test");
  14982. EXPECT_FALSE(res);
  14983. EXPECT_TRUE(callback_called);
  14984. }
  14985. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14987. ASSERT_TRUE(svr.is_valid());
  14988. svr.Get("/test", [](const Request &, Response &res) {
  14989. res.set_content("ok", "text/plain");
  14990. });
  14991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14992. auto se = detail::scope_exit([&] {
  14993. svr.stop();
  14994. t.join();
  14995. });
  14996. svr.wait_until_ready();
  14997. // NoDecisionMade with verification disabled should succeed (no default check)
  14998. SSLClient cli(HOST, PORT);
  14999. cli.enable_server_certificate_verification(false);
  15000. cli.set_connection_timeout(30);
  15001. bool callback_called = false;
  15002. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15003. EXPECT_NE(session, nullptr);
  15004. callback_called = true;
  15005. return SSLVerifierResponse::NoDecisionMade;
  15006. });
  15007. auto res = cli.Get("/test");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(200, res->status);
  15010. EXPECT_TRUE(callback_called);
  15011. }
  15012. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15014. ASSERT_TRUE(svr.is_valid());
  15015. svr.Get("/test", [](const Request &, Response &res) {
  15016. res.set_content("ok", "text/plain");
  15017. });
  15018. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15019. auto se = detail::scope_exit([&] {
  15020. svr.stop();
  15021. t.join();
  15022. });
  15023. svr.wait_until_ready();
  15024. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15025. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15026. // so we only check that the request fails, not whether the callback was
  15027. // called.
  15028. SSLClient cli(HOST, PORT);
  15029. cli.enable_server_certificate_verification(true);
  15030. cli.set_connection_timeout(30);
  15031. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15032. EXPECT_NE(session, nullptr);
  15033. return SSLVerifierResponse::NoDecisionMade;
  15034. });
  15035. auto res = cli.Get("/test");
  15036. EXPECT_FALSE(res);
  15037. }
  15038. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15039. // Test SSL server using PemMemory constructor with client CA certificates
  15040. // Read PEM files
  15041. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15042. read_file(SERVER_CERT_FILE, server_cert_pem);
  15043. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15044. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15045. // Create SSLServer with PemMemory constructor including client CA
  15046. SSLServer::PemMemory server_pem = {
  15047. server_cert_pem.c_str(),
  15048. server_cert_pem.size(),
  15049. server_key_pem.c_str(),
  15050. server_key_pem.size(),
  15051. client_ca_pem.c_str(),
  15052. client_ca_pem.size(),
  15053. nullptr // no password for server key
  15054. };
  15055. SSLServer svr(server_pem);
  15056. ASSERT_TRUE(svr.is_valid());
  15057. // No SSL error should be recorded for valid setup
  15058. EXPECT_EQ(0, svr.ssl_last_error());
  15059. // Set up server endpoints
  15060. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15061. res.set_content("ok", "text/plain");
  15062. });
  15063. // Start server in a thread
  15064. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15065. svr.wait_until_ready();
  15066. // Connect with client certificate (using constructor with paths)
  15067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15068. cli.enable_server_certificate_verification(false);
  15069. auto res = cli.Get("/test-pem-ca");
  15070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15071. EXPECT_EQ(200, res->status);
  15072. EXPECT_EQ("ok", res->body);
  15073. svr.stop();
  15074. server_thread.join();
  15075. }
  15076. #endif
  15077. #ifdef _WIN32
  15078. TEST(CleanupTest, WSACleanup) {
  15079. int ret = WSACleanup();
  15080. ASSERT_EQ(0, ret);
  15081. }
  15082. #endif
  15083. #ifndef CPPHTTPLIB_SSL_ENABLED
  15084. TEST(NoSSLSupport, SimpleInterface) {
  15085. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15086. }
  15087. #endif
  15088. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15089. TEST(InvalidScheme, SimpleInterface) {
  15090. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15091. }
  15092. #endif
  15093. TEST(NoScheme, SimpleInterface) {
  15094. Client cli("yahoo.com:80");
  15095. ASSERT_TRUE(cli.is_valid());
  15096. }
  15097. TEST(SendAPI, SimpleInterface_Online) {
  15098. Client cli("http://yahoo.com");
  15099. Request req;
  15100. req.method = "GET";
  15101. req.path = "/";
  15102. auto res = cli.send(req);
  15103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15104. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15105. }
  15106. TEST(SendAPI, WithParamsInRequest) {
  15107. Server svr;
  15108. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15109. EXPECT_TRUE(req.has_param("test"));
  15110. EXPECT_EQ("test_value", req.get_param_value("test"));
  15111. });
  15112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15113. auto se = detail::scope_exit([&] {
  15114. svr.stop();
  15115. t.join();
  15116. ASSERT_FALSE(svr.is_running());
  15117. });
  15118. svr.wait_until_ready();
  15119. Client cli(HOST, PORT);
  15120. {
  15121. Request req;
  15122. req.method = "GET";
  15123. req.path = "/";
  15124. req.params.emplace("test", "test_value");
  15125. auto res = cli.send(req);
  15126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15127. }
  15128. {
  15129. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. }
  15132. }
  15133. TEST(ClientImplMethods, GetSocketTest) {
  15134. httplib::Server svr;
  15135. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15136. res.status = StatusCode::OK_200;
  15137. });
  15138. auto port = svr.bind_to_any_port("127.0.0.1");
  15139. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15140. auto se = detail::scope_exit([&] {
  15141. svr.stop();
  15142. thread.join();
  15143. ASSERT_FALSE(svr.is_running());
  15144. });
  15145. svr.wait_until_ready();
  15146. {
  15147. httplib::Client cli("127.0.0.1", port);
  15148. cli.set_keep_alive(true);
  15149. // Use the behavior of cpp-httplib of opening the connection
  15150. // only when the first request happens. If that changes,
  15151. // this test would be obsolete.
  15152. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15153. // This also implicitly tests the server. But other tests would fail much
  15154. // earlier than this one to be considered.
  15155. auto res = cli.Get("/");
  15156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15157. EXPECT_EQ(StatusCode::OK_200, res->status);
  15158. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15159. }
  15160. }
  15161. #ifdef CPPHTTPLIB_SSL_ENABLED
  15162. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15163. Client cli("http://yahoo.com");
  15164. auto res = cli.Get("/");
  15165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15166. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15167. cli.set_follow_location(true);
  15168. res = cli.Get("/");
  15169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15170. EXPECT_EQ(StatusCode::OK_200, res->status);
  15171. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15172. }
  15173. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15174. Client cli("https://yahoo.com");
  15175. auto res = cli.Get("/");
  15176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15177. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15178. cli.set_follow_location(true);
  15179. res = cli.Get("/");
  15180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15181. EXPECT_EQ(StatusCode::OK_200, res->status);
  15182. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15183. }
  15184. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15185. Client cli("https://yahoo.com");
  15186. auto res = cli.Get("/");
  15187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15188. ASSERT_FALSE(!res);
  15189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15190. ASSERT_FALSE(res == nullptr);
  15191. ASSERT_TRUE(res != nullptr);
  15192. EXPECT_EQ(Error::Success, res.error());
  15193. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15194. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15195. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15196. cli.set_follow_location(true);
  15197. res = cli.Get("/");
  15198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15199. EXPECT_EQ(Error::Success, res.error());
  15200. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15201. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15202. EXPECT_EQ(StatusCode::OK_200, res->status);
  15203. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15204. }
  15205. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15206. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15207. Client cli("https://cdnjs.cloudflare.com");
  15208. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15209. Headers{{"Accept-Encoding", "br"}});
  15210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15211. EXPECT_EQ(StatusCode::OK_200, res->status);
  15212. EXPECT_EQ(287630U, res->body.size());
  15213. EXPECT_EQ("application/javascript; charset=utf-8",
  15214. res->get_header_value("Content-Type"));
  15215. }
  15216. #endif
  15217. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15218. #undef REDIR_HOST // Silence compiler warning
  15219. #define REDIR_HOST "https://httpbingo.org"
  15220. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15221. Client cli(REDIR_HOST);
  15222. cli.set_follow_location(true);
  15223. auto res =
  15224. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15226. EXPECT_EQ(StatusCode::OK_200, res->status);
  15227. }
  15228. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15229. Client cli(REDIR_HOST);
  15230. cli.set_follow_location(true);
  15231. Params params;
  15232. params.emplace("url", "http://example.com");
  15233. params.emplace("status_code", "302");
  15234. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15236. EXPECT_EQ(StatusCode::OK_200, res->status);
  15237. }
  15238. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15239. Client cli(REDIR_HOST);
  15240. cli.set_follow_location(true);
  15241. Params params;
  15242. params.emplace("url", "http://example.com");
  15243. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15245. EXPECT_EQ(StatusCode::OK_200, res->status);
  15246. }
  15247. TEST(HttpToHttpsRedirectTest, CertFile) {
  15248. auto ssl_port = PORT + 1;
  15249. Server svr;
  15250. ASSERT_TRUE(svr.is_valid());
  15251. svr.Get("/index", [&](const Request &, Response &res) {
  15252. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15253. "/index");
  15254. svr.stop();
  15255. });
  15256. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15257. ASSERT_TRUE(ssl_svr.is_valid());
  15258. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15259. res.set_content("test", "text/plain");
  15260. ssl_svr.stop();
  15261. });
  15262. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15263. thread t2 =
  15264. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15265. auto se = detail::scope_exit([&] {
  15266. t2.join();
  15267. t.join();
  15268. ASSERT_FALSE(svr.is_running());
  15269. });
  15270. svr.wait_until_ready();
  15271. ssl_svr.wait_until_ready();
  15272. Client cli("127.0.0.1", PORT);
  15273. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15274. cli.enable_server_certificate_verification(true);
  15275. cli.set_follow_location(true);
  15276. cli.set_connection_timeout(30);
  15277. auto res = cli.Get("/index");
  15278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15279. ASSERT_EQ(StatusCode::OK_200, res->status);
  15280. }
  15281. TEST(SSLClientRedirectTest, CertFile) {
  15282. auto ssl_port = PORT + 1;
  15283. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15284. ASSERT_TRUE(ssl_svr1.is_valid());
  15285. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15286. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15287. "/index");
  15288. ssl_svr1.stop();
  15289. });
  15290. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15291. ASSERT_TRUE(ssl_svr2.is_valid());
  15292. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15293. res.set_content("test", "text/plain");
  15294. ssl_svr2.stop();
  15295. });
  15296. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15297. thread t2 =
  15298. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15299. auto se = detail::scope_exit([&] {
  15300. t2.join();
  15301. t.join();
  15302. ASSERT_FALSE(ssl_svr1.is_running());
  15303. });
  15304. ssl_svr1.wait_until_ready();
  15305. ssl_svr2.wait_until_ready();
  15306. SSLClient cli("127.0.0.1", PORT);
  15307. std::string cert;
  15308. read_file(SERVER_CERT2_FILE, cert);
  15309. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15310. cli.enable_server_certificate_verification(true);
  15311. cli.set_follow_location(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/index");
  15314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15315. ASSERT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15318. // another port, so the client follows it with a new client.
  15319. static Result GetThroughTlsRedirectToDifferentPort(
  15320. const std::function<void(SSLClient &)> &setup,
  15321. const char *target_cert = SERVER_CERT2_FILE,
  15322. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15323. auto ssl_port = PORT + 1;
  15324. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15325. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15326. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15327. "/index");
  15328. });
  15329. SSLServer ssl_svr2(target_cert, target_key);
  15330. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15331. res.set_content("test", "text/plain");
  15332. });
  15333. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15334. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15335. auto se = detail::scope_exit([&] {
  15336. ssl_svr2.stop();
  15337. ssl_svr1.stop();
  15338. t2.join();
  15339. t.join();
  15340. });
  15341. ssl_svr1.wait_until_ready();
  15342. ssl_svr2.wait_until_ready();
  15343. SSLClient cli("127.0.0.1", PORT);
  15344. cli.set_follow_location(true);
  15345. cli.set_connection_timeout(30);
  15346. setup(cli);
  15347. return cli.Get("/index");
  15348. }
  15349. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15350. auto calls = 0;
  15351. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15352. cli.enable_server_certificate_verification(false);
  15353. // Accept the first server only.
  15354. cli.set_session_verifier([&](tls::session_t) {
  15355. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15356. : SSLVerifierResponse::CertificateRejected;
  15357. });
  15358. });
  15359. ASSERT_FALSE(res);
  15360. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15361. EXPECT_EQ(2, calls);
  15362. }
  15363. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15364. std::string pinned;
  15365. auto res = GetThroughTlsRedirectToDifferentPort(
  15366. [&](SSLClient &cli) {
  15367. cli.enable_server_certificate_verification(false);
  15368. // Pin the first certificate seen.
  15369. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15370. if (pinned.empty()) { pinned = ctx.serial(); }
  15371. return ctx.serial() == pinned;
  15372. });
  15373. },
  15374. // A certificate other than the first server's.
  15375. SERVER_CERT_FILE);
  15376. EXPECT_FALSE(res);
  15377. EXPECT_FALSE(pinned.empty());
  15378. }
  15379. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15380. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15381. std::string cert;
  15382. read_file(SERVER_CERT2_FILE, cert);
  15383. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15384. });
  15385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15386. EXPECT_EQ(StatusCode::OK_200, res->status);
  15387. }
  15388. // The target's certificate is signed by the root CA, which the first server's
  15389. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15390. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15391. auto res = GetThroughTlsRedirectToDifferentPort(
  15392. [](SSLClient &cli) {
  15393. std::string root_ca, cert;
  15394. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15395. read_file(SERVER_CERT2_FILE, cert);
  15396. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15397. cli.load_ca_cert_store(cert.data(), cert.size());
  15398. cli.enable_server_hostname_verification(false);
  15399. },
  15400. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15402. EXPECT_EQ(StatusCode::OK_200, res->status);
  15403. }
  15404. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15405. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15406. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15407. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15408. auto res = GetThroughTlsRedirectToDifferentPort(
  15409. [](SSLClient &cli) {
  15410. std::string root_ca, cert;
  15411. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15412. read_file(SERVER_CERT2_FILE, cert);
  15413. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15414. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15415. cli.enable_server_hostname_verification(false);
  15416. },
  15417. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15418. ASSERT_FALSE(res);
  15419. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15420. }
  15421. #endif
  15422. #endif
  15423. #ifdef CPPHTTPLIB_SSL_ENABLED
  15424. // Test that set_ca_cert_store() skips system certs (consistent with
  15425. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15426. // should be trusted - system certs should NOT be loaded.
  15427. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15428. // Load a specific cert that is NOT a system CA cert
  15429. std::string cert;
  15430. read_file(SERVER_CERT2_FILE, cert);
  15431. SSLClient cli("google.com");
  15432. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15433. cli.enable_server_certificate_verification(true);
  15434. // This should FAIL because:
  15435. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15436. // 2. System certs should NOT be loaded when custom store is set
  15437. // If system certs WERE loaded, this would succeed
  15438. auto res = cli.Get("/");
  15439. ASSERT_FALSE(res);
  15440. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15441. }
  15442. // Same as above, but through the native store handle path. Regression test:
  15443. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15444. // merged system certs into the user-provided store.
  15445. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15446. std::string cert;
  15447. read_file(SERVER_CERT2_FILE, cert);
  15448. SSLClient cli("google.com");
  15449. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15450. cli.enable_server_certificate_verification(true);
  15451. auto res = cli.Get("/");
  15452. ASSERT_FALSE(res);
  15453. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15454. }
  15455. // A custom store set via the native handle must still verify a server whose
  15456. // cert it does contain.
  15457. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15459. ASSERT_TRUE(svr.is_valid());
  15460. svr.Get("/test", [&](const Request &, Response &res) {
  15461. res.set_content("test", "text/plain");
  15462. });
  15463. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15464. auto se = detail::scope_exit([&] {
  15465. svr.stop();
  15466. t.join();
  15467. ASSERT_FALSE(svr.is_running());
  15468. });
  15469. svr.wait_until_ready();
  15470. SSLClient cli("127.0.0.1", PORT);
  15471. std::string cert;
  15472. read_file(SERVER_CERT2_FILE, cert);
  15473. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15474. cli.enable_server_certificate_verification(true);
  15475. cli.set_connection_timeout(30);
  15476. auto res = cli.Get("/test");
  15477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15478. ASSERT_EQ(StatusCode::OK_200, res->status);
  15479. }
  15480. // CA certs loaded through the universal Client must be transferred to the
  15481. // client created internally for following an HTTPS redirect. Regression test:
  15482. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15483. // the CA data for redirect transfer.
  15484. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15485. auto ssl_port = PORT + 1;
  15486. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15487. ASSERT_TRUE(ssl_svr1.is_valid());
  15488. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15489. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15490. "/index");
  15491. });
  15492. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15493. ASSERT_TRUE(ssl_svr2.is_valid());
  15494. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15495. res.set_content("test", "text/plain");
  15496. });
  15497. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15498. thread t2 =
  15499. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15500. auto se = detail::scope_exit([&] {
  15501. ssl_svr2.stop();
  15502. ssl_svr1.stop();
  15503. t2.join();
  15504. t.join();
  15505. ASSERT_FALSE(ssl_svr1.is_running());
  15506. });
  15507. ssl_svr1.wait_until_ready();
  15508. ssl_svr2.wait_until_ready();
  15509. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15510. std::string cert;
  15511. read_file(SERVER_CERT2_FILE, cert);
  15512. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15513. cli.enable_server_certificate_verification(true);
  15514. cli.set_follow_location(true);
  15515. cli.set_connection_timeout(30);
  15516. auto res = cli.Get("/index");
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. ASSERT_EQ(StatusCode::OK_200, res->status);
  15519. }
  15520. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15521. // so a host signed by a system CA verifies even though a custom CA is set
  15522. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15523. std::string cert;
  15524. read_file(SERVER_CERT2_FILE, cert);
  15525. SSLClient cli("google.com");
  15526. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15527. cli.enable_system_ca(true);
  15528. cli.enable_server_certificate_verification(true);
  15529. auto res = cli.Get("/");
  15530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15531. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15532. }
  15533. // The custom CA remains effective when combined with the system CA
  15534. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15535. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15536. ASSERT_TRUE(svr.is_valid());
  15537. svr.Get("/test", [&](const Request &, Response &res) {
  15538. res.set_content("test", "text/plain");
  15539. });
  15540. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15541. auto se = detail::scope_exit([&] {
  15542. svr.stop();
  15543. t.join();
  15544. ASSERT_FALSE(svr.is_running());
  15545. });
  15546. svr.wait_until_ready();
  15547. SSLClient cli("127.0.0.1", PORT);
  15548. std::string cert;
  15549. read_file(SERVER_CERT2_FILE, cert);
  15550. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15551. cli.enable_system_ca(true);
  15552. cli.enable_server_certificate_verification(true);
  15553. cli.set_connection_timeout(30);
  15554. auto res = cli.Get("/test");
  15555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15556. ASSERT_EQ(StatusCode::OK_200, res->status);
  15557. }
  15558. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15559. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15560. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15561. static CFDictionaryRef
  15562. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15563. const SecTrustSettingsResult *result) {
  15564. auto constraint =
  15565. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15566. &kCFTypeDictionaryValueCallBacks);
  15567. if (policy) {
  15568. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15569. }
  15570. if (policy_string) {
  15571. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15572. kCFStringEncodingUTF8);
  15573. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15574. CFRelease(str);
  15575. }
  15576. if (result) {
  15577. auto number_value = static_cast<SInt32>(*result);
  15578. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15579. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15580. CFRelease(number);
  15581. }
  15582. return constraint;
  15583. }
  15584. static SecTrustSettingsResult
  15585. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15586. auto trust_settings =
  15587. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15588. for (auto constraint : constraints) {
  15589. CFArrayAppendValue(trust_settings, constraint);
  15590. CFRelease(constraint);
  15591. }
  15592. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15593. CFRelease(trust_settings);
  15594. return result;
  15595. }
  15596. // The system CA loader takes a Keychain certificate as a trusted root only
  15597. // when its Trust Settings say so for SSL, not merely because it has some.
  15598. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15599. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15600. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15601. const auto deny = kSecTrustSettingsResultDeny;
  15602. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15603. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15604. auto x509_policy = SecPolicyCreateBasicX509();
  15605. // "Always Trust", which stores no constraint at all
  15606. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15607. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15608. ssl_trust_settings_result(
  15609. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15610. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15611. ssl_trust_settings_result(
  15612. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15613. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15614. ssl_trust_settings_result(
  15615. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15616. // "Never Trust", for everything or for SSL
  15617. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15618. ssl_trust_settings_result(
  15619. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15620. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15621. ssl_trust_settings_result(
  15622. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15623. // Trusted for another policy, for one host, or not at all
  15624. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15625. ssl_trust_settings_result(
  15626. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15627. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15628. ssl_trust_settings_result({make_usage_constraint(
  15629. ssl_policy, "www.example.com", &trust_root)}));
  15630. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15631. ssl_trust_settings_result(
  15632. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15633. // The first constraint that applies to SSL decides
  15634. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15635. ssl_trust_settings_result(
  15636. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15637. make_usage_constraint(nullptr, nullptr, &deny)}));
  15638. CFRelease(x509_policy);
  15639. CFRelease(ssl_policy);
  15640. }
  15641. #endif
  15642. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15643. // skip chain verification entirely (only the certificate identity was
  15644. // checked), so a server presenting an untrusted certificate with a matching
  15645. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15646. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15647. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15648. ASSERT_TRUE(svr.is_valid());
  15649. svr.Get("/test", [&](const Request &, Response &res) {
  15650. res.set_content("test", "text/plain");
  15651. });
  15652. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15653. auto se = detail::scope_exit([&] {
  15654. svr.stop();
  15655. t.join();
  15656. ASSERT_FALSE(svr.is_running());
  15657. });
  15658. svr.wait_until_ready();
  15659. SSLClient cli("127.0.0.1", PORT);
  15660. std::string cert;
  15661. // A trusted CA that did not sign the server certificate. The server cert
  15662. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15663. // this connection.
  15664. read_file(CLIENT_CA_CERT_FILE, cert);
  15665. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15666. cli.enable_server_certificate_verification(true);
  15667. cli.set_connection_timeout(30);
  15668. auto res = cli.Get("/test");
  15669. ASSERT_FALSE(res);
  15670. }
  15671. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15672. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15673. // CA that failed to come through fails verification instead of trusting them.
  15674. // (wolfSSL does not list the system CAs it loaded.)
  15675. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15676. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15677. ASSERT_TRUE(svr.is_valid());
  15678. auto port = svr.bind_to_any_port("127.0.0.1");
  15679. ASSERT_LT(0, port);
  15680. thread t = thread([&] { svr.listen_after_bind(); });
  15681. auto se = detail::scope_exit([&] {
  15682. svr.stop();
  15683. t.join();
  15684. ASSERT_FALSE(svr.is_running());
  15685. });
  15686. svr.wait_until_ready();
  15687. // The CAs a client trusts once its first request has loaded them
  15688. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15689. Client cli("https://127.0.0.1:" + std::to_string(port));
  15690. setup(cli);
  15691. cli.Get("/");
  15692. return tls::get_ca_names(cli.tls_context()).size();
  15693. };
  15694. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15695. EXPECT_EQ(0u,
  15696. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15697. }
  15698. #endif
  15699. // A TLS setting changed between requests applies to the next one, not just to
  15700. // the next connection
  15701. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15702. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15703. ASSERT_TRUE(svr.is_valid());
  15704. svr.Get("/", [](const Request &req, Response &res) {
  15705. res.set_content(std::to_string(req.remote_port), "text/plain");
  15706. });
  15707. auto port = svr.bind_to_any_port("127.0.0.1");
  15708. ASSERT_LT(0, port);
  15709. thread t = thread([&] { svr.listen_after_bind(); });
  15710. auto se = detail::scope_exit([&] {
  15711. svr.stop();
  15712. t.join();
  15713. ASSERT_FALSE(svr.is_running());
  15714. });
  15715. svr.wait_until_ready();
  15716. SSLClient cli("127.0.0.1", port);
  15717. cli.set_keep_alive(true);
  15718. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15719. cli.enable_server_certificate_verification(false);
  15720. // The port the request went out from, so a new one means a new connection
  15721. auto client_port = [&] {
  15722. auto res = cli.Get("/");
  15723. return res ? res->body : std::string();
  15724. };
  15725. auto last = client_port();
  15726. ASSERT_FALSE(last.empty());
  15727. // Setting a value it already has keeps the connection
  15728. cli.enable_server_certificate_verification(false);
  15729. cli.enable_server_hostname_verification(true);
  15730. EXPECT_EQ(last, client_port());
  15731. cli.enable_server_certificate_verification(true);
  15732. auto res = cli.Get("/");
  15733. EXPECT_FALSE(res);
  15734. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15735. std::string ca;
  15736. read_file(SERVER_CERT2_FILE, ca);
  15737. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15738. last = client_port();
  15739. ASSERT_FALSE(last.empty());
  15740. std::vector<std::function<void()>> setters = {
  15741. [&] { cli.enable_server_hostname_verification(false); },
  15742. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15743. [&] {
  15744. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15745. },
  15746. [&] {
  15747. cli.set_server_certificate_verifier(
  15748. [](const tls::VerifyContext &) { return true; });
  15749. },
  15750. [&] {
  15751. cli.set_session_verifier(
  15752. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15753. },
  15754. };
  15755. for (const auto &setter : setters) {
  15756. setter();
  15757. auto next = client_port();
  15758. ASSERT_FALSE(next.empty());
  15759. EXPECT_NE(last, next);
  15760. last = next;
  15761. }
  15762. cli.set_session_verifier(
  15763. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15764. auto handle = cli.open_stream("GET", "/");
  15765. EXPECT_FALSE(handle.is_valid());
  15766. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15767. }
  15768. // A PEM given to create_ca_store() needs no NUL after it
  15769. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15770. std::string pem;
  15771. read_file(SERVER_CERT2_FILE, pem);
  15772. auto buf = pem + "X";
  15773. auto store = tls::create_ca_store(buf.data(), pem.size());
  15774. EXPECT_TRUE(store != nullptr);
  15775. SSLClient cli("localhost");
  15776. cli.set_ca_cert_store(store);
  15777. }
  15778. // enable_system_ca(false) prevents system CA loading entirely
  15779. TEST(SSLClientTest, DisableSystemCa_Online) {
  15780. SSLClient cli("google.com");
  15781. cli.enable_system_ca(false);
  15782. cli.enable_server_certificate_verification(true);
  15783. auto res = cli.Get("/");
  15784. ASSERT_FALSE(res);
  15785. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15786. // itself when the CA chain is empty
  15787. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15788. res.error() == Error::SSLConnection);
  15789. }
  15790. // The universal Client forwards enable_system_ca()
  15791. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15792. std::string cert;
  15793. read_file(SERVER_CERT2_FILE, cert);
  15794. Client cli("https://google.com");
  15795. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15796. cli.enable_system_ca(true);
  15797. cli.enable_server_certificate_verification(true);
  15798. auto res = cli.Get("/");
  15799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15800. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15801. }
  15802. // The system CA policy must carry over to the client created internally for
  15803. // following a cross-host HTTPS redirect
  15804. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15805. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15806. ASSERT_TRUE(svr.is_valid());
  15807. svr.Get("/index", [&](const Request &, Response &res) {
  15808. res.set_redirect("https://www.google.com/");
  15809. });
  15810. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15811. auto se = detail::scope_exit([&] {
  15812. svr.stop();
  15813. t.join();
  15814. ASSERT_FALSE(svr.is_running());
  15815. });
  15816. svr.wait_until_ready();
  15817. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15818. std::string cert;
  15819. read_file(SERVER_CERT2_FILE, cert);
  15820. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15821. cli.enable_system_ca(true);
  15822. cli.enable_server_certificate_verification(true);
  15823. cli.set_follow_location(true);
  15824. cli.set_connection_timeout(30);
  15825. // Receiving any response proves the redirect client completed the TLS
  15826. // handshake with a system-CA-signed host
  15827. auto res = cli.Get("/index");
  15828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15829. }
  15830. TEST(MultipartFormDataTest, LargeData) {
  15831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15832. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15833. const ContentReader &content_reader) {
  15834. if (req.is_multipart_form_data()) {
  15835. std::vector<FormData> items;
  15836. content_reader(
  15837. [&](const FormData &file) {
  15838. items.push_back(file);
  15839. return true;
  15840. },
  15841. [&](const char *data, size_t data_length) {
  15842. items.back().content.append(data, data_length);
  15843. return true;
  15844. });
  15845. EXPECT_TRUE(std::string(items[0].name) == "document");
  15846. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15847. EXPECT_TRUE(items[0].filename == "2MB_data");
  15848. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15849. EXPECT_TRUE(items[1].name == "hello");
  15850. EXPECT_TRUE(items[1].content == "world");
  15851. EXPECT_TRUE(items[1].filename == "");
  15852. EXPECT_TRUE(items[1].content_type == "");
  15853. } else {
  15854. std::string body;
  15855. content_reader([&](const char *data, size_t data_length) {
  15856. body.append(data, data_length);
  15857. return true;
  15858. });
  15859. }
  15860. });
  15861. auto port = svr.bind_to_any_port(HOST);
  15862. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15863. auto se = detail::scope_exit([&] {
  15864. svr.stop();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. });
  15868. svr.wait_until_ready();
  15869. {
  15870. std::string data(1024 * 1024 * 2, '.');
  15871. std::stringstream buffer;
  15872. buffer << data;
  15873. SSLClient cli(HOST, port);
  15874. cli.enable_server_certificate_verification(false);
  15875. UploadFormDataItems items{
  15876. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15877. {"hello", "world", "", ""},
  15878. };
  15879. auto res = cli.Post("/post", items);
  15880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15881. ASSERT_EQ(StatusCode::OK_200, res->status);
  15882. }
  15883. }
  15884. TEST(MultipartFormDataTest, DataProviderItems) {
  15885. std::random_device seed_gen;
  15886. std::mt19937 random(seed_gen());
  15887. std::string rand1;
  15888. rand1.resize(1000);
  15889. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15890. std::string rand2;
  15891. rand2.resize(3000);
  15892. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15894. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15895. const ContentReader &content_reader) {
  15896. ASSERT_FALSE(req.is_multipart_form_data());
  15897. std::string body;
  15898. content_reader([&](const char *data, size_t data_length) {
  15899. body.append(data, data_length);
  15900. return true;
  15901. });
  15902. EXPECT_EQ(body, "");
  15903. });
  15904. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15905. const ContentReader &content_reader) {
  15906. ASSERT_TRUE(req.is_multipart_form_data());
  15907. std::vector<FormData> items;
  15908. content_reader(
  15909. [&](const FormData &file) {
  15910. items.push_back(file);
  15911. return true;
  15912. },
  15913. [&](const char *data, size_t data_length) {
  15914. items.back().content.append(data, data_length);
  15915. return true;
  15916. });
  15917. ASSERT_TRUE(items.size() == 2);
  15918. EXPECT_EQ(std::string(items[0].name), "name1");
  15919. EXPECT_EQ(items[0].content, "Testing123");
  15920. EXPECT_EQ(items[0].filename, "filename1");
  15921. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15922. EXPECT_EQ(items[1].name, "name2");
  15923. EXPECT_EQ(items[1].content, "Testing456");
  15924. EXPECT_EQ(items[1].filename, "");
  15925. EXPECT_EQ(items[1].content_type, "");
  15926. });
  15927. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15928. const ContentReader &content_reader) {
  15929. ASSERT_TRUE(req.is_multipart_form_data());
  15930. std::vector<FormData> items;
  15931. content_reader(
  15932. [&](const FormData &file) {
  15933. items.push_back(file);
  15934. return true;
  15935. },
  15936. [&](const char *data, size_t data_length) {
  15937. items.back().content.append(data, data_length);
  15938. return true;
  15939. });
  15940. ASSERT_TRUE(items.size() == 2);
  15941. EXPECT_EQ(items[0].name, "name3");
  15942. EXPECT_EQ(items[0].content, rand1);
  15943. EXPECT_EQ(items[0].filename, "filename3");
  15944. EXPECT_EQ(items[0].content_type, "");
  15945. EXPECT_EQ(items[1].name, "name4");
  15946. EXPECT_EQ(items[1].content, rand2);
  15947. EXPECT_EQ(items[1].filename, "filename4");
  15948. EXPECT_EQ(items[1].content_type, "");
  15949. });
  15950. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15951. const ContentReader &content_reader) {
  15952. ASSERT_TRUE(req.is_multipart_form_data());
  15953. std::vector<FormData> items;
  15954. content_reader(
  15955. [&](const FormData &file) {
  15956. items.push_back(file);
  15957. return true;
  15958. },
  15959. [&](const char *data, size_t data_length) {
  15960. items.back().content.append(data, data_length);
  15961. return true;
  15962. });
  15963. ASSERT_TRUE(items.size() == 4);
  15964. EXPECT_EQ(std::string(items[0].name), "name1");
  15965. EXPECT_EQ(items[0].content, "Testing123");
  15966. EXPECT_EQ(items[0].filename, "filename1");
  15967. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15968. EXPECT_EQ(items[1].name, "name2");
  15969. EXPECT_EQ(items[1].content, "Testing456");
  15970. EXPECT_EQ(items[1].filename, "");
  15971. EXPECT_EQ(items[1].content_type, "");
  15972. EXPECT_EQ(items[2].name, "name3");
  15973. EXPECT_EQ(items[2].content, rand1);
  15974. EXPECT_EQ(items[2].filename, "filename3");
  15975. EXPECT_EQ(items[2].content_type, "");
  15976. EXPECT_EQ(items[3].name, "name4");
  15977. EXPECT_EQ(items[3].content, rand2);
  15978. EXPECT_EQ(items[3].filename, "filename4");
  15979. EXPECT_EQ(items[3].content_type, "");
  15980. });
  15981. auto port = svr.bind_to_any_port("localhost");
  15982. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15983. auto se = detail::scope_exit([&] {
  15984. svr.stop();
  15985. t.join();
  15986. ASSERT_FALSE(svr.is_running());
  15987. });
  15988. svr.wait_until_ready();
  15989. {
  15990. SSLClient cli("localhost", port);
  15991. cli.enable_server_certificate_verification(false);
  15992. UploadFormDataItems items{
  15993. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15994. {"name2", "Testing456", "", ""}, // not a file
  15995. };
  15996. {
  15997. auto res = cli.Post("/post-none", {}, {}, {});
  15998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15999. ASSERT_EQ(StatusCode::OK_200, res->status);
  16000. }
  16001. FormDataProviderItems providers;
  16002. {
  16003. auto res =
  16004. cli.Post("/post-items", {}, items, providers); // empty providers
  16005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16006. ASSERT_EQ(StatusCode::OK_200, res->status);
  16007. }
  16008. providers.push_back({"name3",
  16009. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16010. // test the offset is given correctly at each step
  16011. if (!offset)
  16012. sink.os.write(rand1.data(), 30);
  16013. else if (offset == 30)
  16014. sink.os.write(rand1.data() + 30, 300);
  16015. else if (offset == 330)
  16016. sink.os.write(rand1.data() + 330, 670);
  16017. else if (offset == rand1.size())
  16018. sink.done();
  16019. return true;
  16020. },
  16021. "filename3",
  16022. {}});
  16023. providers.push_back({"name4",
  16024. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16025. // test the offset is given correctly at each step
  16026. if (!offset)
  16027. sink.os.write(rand2.data(), 2000);
  16028. else if (offset == 2000)
  16029. sink.os.write(rand2.data() + 2000, 1);
  16030. else if (offset == 2001)
  16031. sink.os.write(rand2.data() + 2001, 999);
  16032. else if (offset == rand2.size())
  16033. sink.done();
  16034. return true;
  16035. },
  16036. "filename4",
  16037. {}});
  16038. {
  16039. auto res = cli.Post("/post-providers", {}, {}, providers);
  16040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16041. ASSERT_EQ(StatusCode::OK_200, res->status);
  16042. }
  16043. {
  16044. auto res = cli.Post("/post-both", {}, items, providers);
  16045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16046. ASSERT_EQ(StatusCode::OK_200, res->status);
  16047. }
  16048. }
  16049. }
  16050. TEST(MultipartFormDataTest, BadHeader) {
  16051. Server svr;
  16052. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16053. res.set_content("ok", "text/plain");
  16054. });
  16055. thread t = thread([&] { svr.listen(HOST, PORT); });
  16056. auto se = detail::scope_exit([&] {
  16057. svr.stop();
  16058. t.join();
  16059. ASSERT_FALSE(svr.is_running());
  16060. });
  16061. svr.wait_until_ready();
  16062. const std::string body =
  16063. "This is the preamble. It is to be ignored, though it\r\n"
  16064. "is a handy place for composition agents to include an\r\n"
  16065. "explanatory note to non-MIME conformant readers.\r\n"
  16066. "\r\n"
  16067. "\r\n"
  16068. "--simple boundary\r\n"
  16069. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16070. ": BAD...\r\n"
  16071. "\r\n"
  16072. "value1\r\n"
  16073. "--simple boundary\r\n"
  16074. "Content-Disposition: form-data; name=\"field2\"; "
  16075. "filename=\"example.txt\"\r\n"
  16076. "\r\n"
  16077. "value2\r\n"
  16078. "--simple boundary--\r\n"
  16079. "This is the epilogue. It is also to be ignored.\r\n";
  16080. std::string content_type =
  16081. R"(multipart/form-data; boundary="simple boundary")";
  16082. Client cli(HOST, PORT);
  16083. auto res = cli.Post("/post", body, content_type.c_str());
  16084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16086. }
  16087. TEST(MultipartFormDataTest, WithPreamble) {
  16088. Server svr;
  16089. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16090. res.set_content("ok", "text/plain");
  16091. });
  16092. thread t = thread([&] { svr.listen(HOST, PORT); });
  16093. auto se = detail::scope_exit([&] {
  16094. svr.stop();
  16095. t.join();
  16096. ASSERT_FALSE(svr.is_running());
  16097. });
  16098. svr.wait_until_ready();
  16099. const std::string body =
  16100. "This is the preamble. It is to be ignored, though it\r\n"
  16101. "is a handy place for composition agents to include an\r\n"
  16102. "explanatory note to non-MIME conformant readers.\r\n"
  16103. "\r\n"
  16104. "\r\n"
  16105. "--simple boundary\r\n"
  16106. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16107. "\r\n"
  16108. "value1\r\n"
  16109. "--simple boundary\r\n"
  16110. "Content-Disposition: form-data; name=\"field2\"; "
  16111. "filename=\"example.txt\"\r\n"
  16112. "\r\n"
  16113. "value2\r\n"
  16114. "--simple boundary--\r\n"
  16115. "This is the epilogue. It is also to be ignored.\r\n";
  16116. std::string content_type =
  16117. R"(multipart/form-data; boundary="simple boundary")";
  16118. Client cli(HOST, PORT);
  16119. auto res = cli.Post("/post", body, content_type.c_str());
  16120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16121. EXPECT_EQ(StatusCode::OK_200, res->status);
  16122. }
  16123. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16125. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16126. const ContentReader &content_reader) {
  16127. if (req.is_multipart_form_data()) {
  16128. std::vector<FormData> items;
  16129. content_reader(
  16130. [&](const FormData &file) {
  16131. items.push_back(file);
  16132. return true;
  16133. },
  16134. [&](const char *data, size_t data_length) {
  16135. items.back().content.append(data, data_length);
  16136. return true;
  16137. });
  16138. EXPECT_TRUE(std::string(items[0].name) == "document");
  16139. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16140. EXPECT_TRUE(items[0].filename == "2MB_data");
  16141. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16142. EXPECT_TRUE(items[1].name == "hello");
  16143. EXPECT_TRUE(items[1].content == "world");
  16144. EXPECT_TRUE(items[1].filename == "");
  16145. EXPECT_TRUE(items[1].content_type == "");
  16146. } else {
  16147. std::string body;
  16148. content_reader([&](const char *data, size_t data_length) {
  16149. body.append(data, data_length);
  16150. return true;
  16151. });
  16152. }
  16153. });
  16154. auto port = svr.bind_to_any_port("localhost");
  16155. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16156. auto se = detail::scope_exit([&] {
  16157. svr.stop();
  16158. t.join();
  16159. ASSERT_FALSE(svr.is_running());
  16160. });
  16161. svr.wait_until_ready();
  16162. {
  16163. std::string data(1024 * 1024 * 2, '.');
  16164. std::stringstream buffer;
  16165. buffer << data;
  16166. SSLClient cli("localhost", port);
  16167. cli.enable_server_certificate_verification(false);
  16168. UploadFormDataItems items{
  16169. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16170. {"hello", "world", "", ""},
  16171. };
  16172. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16174. ASSERT_EQ(StatusCode::OK_200, res->status);
  16175. }
  16176. }
  16177. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16178. std::string data(1024 * 1024 * 2, '&');
  16179. std::stringstream buffer;
  16180. buffer << data;
  16181. Client cli("https://localhost:8080");
  16182. UploadFormDataItems items{
  16183. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16184. {"hello", "world", "", ""},
  16185. };
  16186. for (const char &c : " \t\r\n") {
  16187. auto res =
  16188. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16189. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16190. ASSERT_FALSE(res);
  16191. }
  16192. }
  16193. TEST(MultipartFormDataTest, PutFormData) {
  16194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16195. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16196. const ContentReader &content_reader) {
  16197. if (req.is_multipart_form_data()) {
  16198. std::vector<FormData> items;
  16199. content_reader(
  16200. [&](const FormData &file) {
  16201. items.push_back(file);
  16202. return true;
  16203. },
  16204. [&](const char *data, size_t data_length) {
  16205. items.back().content.append(data, data_length);
  16206. return true;
  16207. });
  16208. EXPECT_TRUE(std::string(items[0].name) == "document");
  16209. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16210. EXPECT_TRUE(items[0].filename == "2MB_data");
  16211. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16212. EXPECT_TRUE(items[1].name == "hello");
  16213. EXPECT_TRUE(items[1].content == "world");
  16214. EXPECT_TRUE(items[1].filename == "");
  16215. EXPECT_TRUE(items[1].content_type == "");
  16216. } else {
  16217. std::string body;
  16218. content_reader([&](const char *data, size_t data_length) {
  16219. body.append(data, data_length);
  16220. return true;
  16221. });
  16222. }
  16223. });
  16224. auto port = svr.bind_to_any_port("localhost");
  16225. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16226. auto se = detail::scope_exit([&] {
  16227. svr.stop();
  16228. t.join();
  16229. ASSERT_FALSE(svr.is_running());
  16230. });
  16231. svr.wait_until_ready();
  16232. {
  16233. std::string data(1024 * 1024 * 2, '&');
  16234. std::stringstream buffer;
  16235. buffer << data;
  16236. SSLClient cli("localhost", port);
  16237. cli.enable_server_certificate_verification(false);
  16238. UploadFormDataItems items{
  16239. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16240. {"hello", "world", "", ""},
  16241. };
  16242. auto res = cli.Put("/put", items);
  16243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16244. ASSERT_EQ(StatusCode::OK_200, res->status);
  16245. }
  16246. }
  16247. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16249. svr.Put("/put_customboundary",
  16250. [&](const Request &req, const Response & /*res*/,
  16251. const ContentReader &content_reader) {
  16252. if (req.is_multipart_form_data()) {
  16253. std::vector<FormData> items;
  16254. content_reader(
  16255. [&](const FormData &file) {
  16256. items.push_back(file);
  16257. return true;
  16258. },
  16259. [&](const char *data, size_t data_length) {
  16260. items.back().content.append(data, data_length);
  16261. return true;
  16262. });
  16263. EXPECT_TRUE(std::string(items[0].name) == "document");
  16264. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16265. EXPECT_TRUE(items[0].filename == "2MB_data");
  16266. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16267. EXPECT_TRUE(items[1].name == "hello");
  16268. EXPECT_TRUE(items[1].content == "world");
  16269. EXPECT_TRUE(items[1].filename == "");
  16270. EXPECT_TRUE(items[1].content_type == "");
  16271. } else {
  16272. std::string body;
  16273. content_reader([&](const char *data, size_t data_length) {
  16274. body.append(data, data_length);
  16275. return true;
  16276. });
  16277. }
  16278. });
  16279. auto port = svr.bind_to_any_port("localhost");
  16280. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16281. auto se = detail::scope_exit([&] {
  16282. svr.stop();
  16283. t.join();
  16284. ASSERT_FALSE(svr.is_running());
  16285. });
  16286. svr.wait_until_ready();
  16287. {
  16288. std::string data(1024 * 1024 * 2, '&');
  16289. std::stringstream buffer;
  16290. buffer << data;
  16291. SSLClient cli("localhost", port);
  16292. cli.enable_server_certificate_verification(false);
  16293. UploadFormDataItems items{
  16294. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16295. {"hello", "world", "", ""},
  16296. };
  16297. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16299. ASSERT_EQ(StatusCode::OK_200, res->status);
  16300. }
  16301. }
  16302. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16303. std::string data(1024 * 1024 * 2, '&');
  16304. std::stringstream buffer;
  16305. buffer << data;
  16306. Client cli("https://localhost:8080");
  16307. cli.enable_server_certificate_verification(false);
  16308. UploadFormDataItems items{
  16309. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16310. {"hello", "world", "", ""},
  16311. };
  16312. for (const char &c : " \t\r\n") {
  16313. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16314. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16315. ASSERT_FALSE(res);
  16316. }
  16317. }
  16318. TEST(MultipartFormDataTest, AlternateFilename) {
  16319. auto handled = false;
  16320. Server svr;
  16321. svr.Post("/test", [&](const Request &req, Response &res) {
  16322. ASSERT_EQ(2u, req.form.files.size());
  16323. ASSERT_EQ(1u, req.form.fields.size());
  16324. // Test files
  16325. const auto &file1 = req.form.get_file("file1");
  16326. ASSERT_EQ("file1", file1.name);
  16327. ASSERT_EQ("A.txt", file1.filename);
  16328. ASSERT_EQ("text/plain", file1.content_type);
  16329. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16330. const auto &file2 = req.form.get_file("file2");
  16331. ASSERT_EQ("file2", file2.name);
  16332. ASSERT_EQ("a.html", file2.filename);
  16333. ASSERT_EQ("text/html", file2.content_type);
  16334. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16335. file2.content);
  16336. // Test text field
  16337. const auto &text = req.form.get_field("text");
  16338. ASSERT_EQ("text default", text);
  16339. res.set_content("ok", "text/plain");
  16340. handled = true;
  16341. });
  16342. thread t = thread([&] { svr.listen(HOST, PORT); });
  16343. auto se = detail::scope_exit([&] {
  16344. svr.stop();
  16345. t.join();
  16346. ASSERT_FALSE(svr.is_running());
  16347. ASSERT_TRUE(handled);
  16348. });
  16349. svr.wait_until_ready();
  16350. auto req = "POST /test HTTP/1.1\r\n"
  16351. "Host: localhost\r\n"
  16352. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16353. "Content-Length: 399\r\n"
  16354. "\r\n"
  16355. "----------\r\n"
  16356. "Content-Disposition: form-data; name=\"text\"\r\n"
  16357. "\r\n"
  16358. "text default\r\n"
  16359. "----------\r\n"
  16360. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16361. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16362. "Content-Type: text/plain\r\n"
  16363. "\r\n"
  16364. "Content of a.txt.\r\n"
  16365. "\r\n"
  16366. "----------\r\n"
  16367. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16368. "\"a.html\"\r\n"
  16369. "Content-Type: text/html\r\n"
  16370. "\r\n"
  16371. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16372. "\r\n"
  16373. "------------\r\n";
  16374. ASSERT_TRUE(send_request(1, req));
  16375. }
  16376. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16377. auto handled = false;
  16378. Server svr;
  16379. svr.Post("/test", [&](const Request &req, Response &res) {
  16380. // Case-insensitive "utf-8''" prefix with a long value
  16381. const auto &file = req.form.get_file("file1");
  16382. ASSERT_EQ("file1", file.name);
  16383. // 8000 chars exercises both the Content-Disposition parser and the
  16384. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16385. // Prior to the fix, std::regex_match on this header would cause O(N)
  16386. // stack recursion in libstdc++, leading to SIGSEGV.
  16387. std::string expected_filename(8000, 'A');
  16388. ASSERT_EQ(expected_filename, file.filename);
  16389. res.set_content("ok", "text/plain");
  16390. handled = true;
  16391. });
  16392. thread t = thread([&] { svr.listen(HOST, PORT); });
  16393. auto se = detail::scope_exit([&] {
  16394. svr.stop();
  16395. t.join();
  16396. ASSERT_FALSE(svr.is_running());
  16397. ASSERT_TRUE(handled);
  16398. });
  16399. svr.wait_until_ready();
  16400. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16401. // Regression test for GHSA-qq6v-r583-3h69
  16402. std::string long_filename(8000, 'A');
  16403. std::string body = "----------\r\n"
  16404. "Content-Disposition: form-data; name=\"file1\"; "
  16405. "filename*=\"Utf-8''" +
  16406. long_filename +
  16407. "\"\r\n"
  16408. "\r\n"
  16409. "hello\r\n"
  16410. "------------\r\n";
  16411. auto req = "POST /test HTTP/1.1\r\n"
  16412. "Host: localhost\r\n"
  16413. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16414. "Content-Length: " +
  16415. std::to_string(body.size()) + "\r\n\r\n" + body;
  16416. ASSERT_TRUE(send_request(1, req));
  16417. }
  16418. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16419. auto handled = false;
  16420. Server svr;
  16421. svr.Post("/test", [&](const Request &req, Response &) {
  16422. ASSERT_EQ(2u, req.form.fields.size());
  16423. const auto &text1 = req.form.get_field("text1");
  16424. ASSERT_EQ("text1", text1);
  16425. const auto &text2 = req.form.get_field("text2");
  16426. ASSERT_EQ("text2", text2);
  16427. handled = true;
  16428. });
  16429. thread t = thread([&] { svr.listen(HOST, PORT); });
  16430. auto se = detail::scope_exit([&] {
  16431. svr.stop();
  16432. t.join();
  16433. ASSERT_FALSE(svr.is_running());
  16434. ASSERT_TRUE(handled);
  16435. });
  16436. svr.wait_until_ready();
  16437. auto req = "POST /test HTTP/1.1\r\n"
  16438. "Host: localhost\r\n"
  16439. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16440. "Content-Length: 146\r\n"
  16441. "\r\n----------\r\n"
  16442. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16443. "\r\n"
  16444. "text1"
  16445. "\r\n----------\r\n"
  16446. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16447. "\r\n"
  16448. "text2"
  16449. "\r\n------------";
  16450. std::string response;
  16451. ASSERT_TRUE(send_request(1, req, &response));
  16452. ASSERT_EQ("200", response.substr(9, 3));
  16453. }
  16454. TEST(MultipartFormDataTest, ContentLength) {
  16455. auto handled = false;
  16456. Server svr;
  16457. svr.Post("/test", [&](const Request &req, Response &) {
  16458. ASSERT_EQ(2u, req.form.fields.size());
  16459. const auto &text1 = req.form.get_field("text1");
  16460. ASSERT_EQ("text1", text1);
  16461. const auto &text2 = req.form.get_field("text2");
  16462. ASSERT_EQ("text2", text2);
  16463. handled = true;
  16464. });
  16465. thread t = thread([&] { svr.listen(HOST, PORT); });
  16466. auto se = detail::scope_exit([&] {
  16467. svr.stop();
  16468. t.join();
  16469. ASSERT_FALSE(svr.is_running());
  16470. ASSERT_TRUE(handled);
  16471. });
  16472. svr.wait_until_ready();
  16473. auto req = "POST /test HTTP/1.1\r\n"
  16474. "Host: localhost\r\n"
  16475. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16476. "Content-Length: 167\r\n"
  16477. "\r\n----------\r\n"
  16478. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16479. "Content-Length: 5\r\n"
  16480. "\r\n"
  16481. "text1"
  16482. "\r\n----------\r\n"
  16483. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16484. "\r\n"
  16485. "text2"
  16486. "\r\n------------\r\n";
  16487. std::string response;
  16488. ASSERT_TRUE(send_request(1, req, &response));
  16489. ASSERT_EQ("200", response.substr(9, 3));
  16490. }
  16491. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16492. auto handled = false;
  16493. Server svr;
  16494. svr.Post("/test", [&](const Request &req, Response &) {
  16495. ASSERT_EQ(2u, req.form.fields.size());
  16496. const auto &text1 = req.form.get_field("text1");
  16497. ASSERT_EQ("text1", text1);
  16498. // TODO: Add header access for text fields if needed
  16499. const auto &text2 = req.form.get_field("text2");
  16500. ASSERT_EQ("text2", text2);
  16501. // TODO: Header access for text fields needs to be implemented
  16502. // auto &headers = it->second.headers;
  16503. // ASSERT_EQ(3U, headers.size());
  16504. // auto custom_header = headers.find("x-whatever");
  16505. // ASSERT_TRUE(custom_header != headers.end());
  16506. // ASSERT_NE("customvalue", custom_header->second);
  16507. // ASSERT_EQ("CustomValue", custom_header->second);
  16508. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16509. handled = true;
  16510. });
  16511. thread t = thread([&] { svr.listen(HOST, PORT); });
  16512. auto se = detail::scope_exit([&] {
  16513. svr.stop();
  16514. t.join();
  16515. ASSERT_FALSE(svr.is_running());
  16516. ASSERT_TRUE(handled);
  16517. });
  16518. svr.wait_until_ready();
  16519. auto req = "POST /test HTTP/1.1\r\n"
  16520. "Host: localhost\r\n"
  16521. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16522. "Content-Length: 232\r\n"
  16523. "\r\n----------\r\n"
  16524. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16525. "Content-Length: 5\r\n"
  16526. "X-Test: 1\r\n"
  16527. "\r\n"
  16528. "text1"
  16529. "\r\n----------\r\n"
  16530. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16531. "Content-Type: text/plain\r\n"
  16532. "X-Whatever: CustomValue\r\n"
  16533. "\r\n"
  16534. "text2"
  16535. "\r\n------------\r\n"
  16536. "That should be disregarded. Not even read";
  16537. std::string response;
  16538. ASSERT_TRUE(send_request(1, req, &response));
  16539. ASSERT_EQ("200", response.substr(9, 3));
  16540. }
  16541. TEST(MultipartFormDataTest, LargeHeader) {
  16542. auto handled = false;
  16543. Server svr;
  16544. svr.Post("/test", [&](const Request &req, Response &) {
  16545. ASSERT_EQ(1u, req.form.fields.size());
  16546. const auto &text = req.form.get_field("name1");
  16547. ASSERT_EQ("text1", text);
  16548. handled = true;
  16549. });
  16550. thread t = thread([&] { svr.listen(HOST, PORT); });
  16551. auto se = detail::scope_exit([&] {
  16552. svr.stop();
  16553. t.join();
  16554. ASSERT_FALSE(svr.is_running());
  16555. ASSERT_TRUE(handled);
  16556. });
  16557. svr.wait_until_ready();
  16558. auto boundary = std::string("cpp-httplib-multipart-data");
  16559. std::string content = "--" + boundary +
  16560. "\r\n"
  16561. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16562. "\r\n"
  16563. "text1\r\n"
  16564. "--" +
  16565. boundary + "--\r\n";
  16566. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16567. "Host: localhost\r\n"
  16568. "Content-Type: multipart/form-data;boundary=" +
  16569. boundary +
  16570. "\r\n"
  16571. "Content-Length: " +
  16572. std::to_string(content.size()) +
  16573. "\r\n"
  16574. "Dummy-Header: ";
  16575. std::string header_suffix = "\r\n"
  16576. "\r\n";
  16577. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16578. size_t header_dummy_size =
  16579. read_buff_size -
  16580. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16581. auto header_dummy = std::string(header_dummy_size, '@');
  16582. auto req = header_prefix + header_dummy + header_suffix + content;
  16583. std::string response;
  16584. ASSERT_TRUE(send_request(1, req, &response));
  16585. ASSERT_EQ("200", response.substr(9, 3));
  16586. }
  16587. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16588. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16589. // (not chunked Transfer-Encoding) after the streaming refactor.
  16590. auto handled = false;
  16591. Server svr;
  16592. svr.Post("/upload", [&](const Request &req, Response &res) {
  16593. auto cl_it = req.headers.find("Content-Length");
  16594. EXPECT_TRUE(cl_it != req.headers.end());
  16595. auto te_it = req.headers.find("Transfer-Encoding");
  16596. EXPECT_TRUE(te_it == req.headers.end());
  16597. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16598. res.set_content("ok", "text/plain");
  16599. handled = true;
  16600. });
  16601. auto port = svr.bind_to_any_port(HOST);
  16602. auto t = thread([&] { svr.listen_after_bind(); });
  16603. auto se = detail::scope_exit([&] {
  16604. svr.stop();
  16605. t.join();
  16606. ASSERT_FALSE(svr.is_running());
  16607. ASSERT_TRUE(handled);
  16608. });
  16609. svr.wait_until_ready();
  16610. UploadFormDataItems items = {
  16611. {"field1", "hello", "", "text/plain"},
  16612. {"file1", "world", "test.txt", "application/octet-stream"},
  16613. };
  16614. Client cli(HOST, port);
  16615. auto res = cli.Post("/upload", {}, items);
  16616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16617. EXPECT_EQ(StatusCode::OK_200, res->status);
  16618. }
  16619. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16620. // Verify that make_multipart_content_provider coalesces many small segments
  16621. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16622. constexpr size_t kItemCount = 1000;
  16623. UploadFormDataItems items;
  16624. items.reserve(kItemCount);
  16625. for (size_t i = 0; i < kItemCount; i++) {
  16626. items.push_back(
  16627. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16628. }
  16629. const std::string boundary = "----test-boundary";
  16630. auto content_length = detail::get_multipart_content_length(items, boundary);
  16631. auto provider = detail::make_multipart_content_provider(items, boundary);
  16632. // Drive the provider the same way write_content_with_progress does
  16633. size_t write_count = 0;
  16634. size_t total_bytes = 0;
  16635. DataSink sink;
  16636. size_t offset = 0;
  16637. sink.write = [&](const char *d, size_t l) -> bool {
  16638. (void)d;
  16639. write_count++;
  16640. total_bytes += l;
  16641. offset += l;
  16642. return true;
  16643. };
  16644. sink.is_writable = []() -> bool { return true; };
  16645. while (offset < content_length) {
  16646. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16647. }
  16648. EXPECT_EQ(content_length, total_bytes);
  16649. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16650. // With buffering into 64KB blocks, write_count should be much smaller.
  16651. auto segment_count = 3 * kItemCount + 1;
  16652. EXPECT_LT(write_count, segment_count / 10);
  16653. }
  16654. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16655. // Integration test: send many UploadFormDataItems and verify the server
  16656. // receives all of them correctly (#2410).
  16657. constexpr size_t kItemCount = 500;
  16658. auto handled = false;
  16659. Server svr;
  16660. svr.Post("/upload", [&](const Request &req, Response &res) {
  16661. EXPECT_EQ(kItemCount, req.form.fields.size());
  16662. for (size_t i = 0; i < kItemCount; i++) {
  16663. auto key = "field" + std::to_string(i);
  16664. auto val = "value" + std::to_string(i);
  16665. auto it = req.form.fields.find(key);
  16666. if (it != req.form.fields.end()) {
  16667. EXPECT_EQ(val, it->second.content);
  16668. } else {
  16669. ADD_FAILURE() << "Missing field: " << key;
  16670. }
  16671. }
  16672. res.set_content("ok", "text/plain");
  16673. handled = true;
  16674. });
  16675. auto port = svr.bind_to_any_port(HOST);
  16676. auto t = thread([&] { svr.listen_after_bind(); });
  16677. auto se = detail::scope_exit([&] {
  16678. svr.stop();
  16679. t.join();
  16680. ASSERT_FALSE(svr.is_running());
  16681. ASSERT_TRUE(handled);
  16682. });
  16683. svr.wait_until_ready();
  16684. UploadFormDataItems items;
  16685. items.reserve(kItemCount);
  16686. for (size_t i = 0; i < kItemCount; i++) {
  16687. items.push_back(
  16688. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16689. }
  16690. Client cli(HOST, port);
  16691. auto res = cli.Post("/upload", items);
  16692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16693. EXPECT_EQ(StatusCode::OK_200, res->status);
  16694. }
  16695. TEST(MultipartFormDataTest, MakeFileProvider) {
  16696. // Verify make_file_provider sends a file's contents correctly.
  16697. const std::string file_content(4096, 'Z');
  16698. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16699. {
  16700. std::ofstream ofs(tmp_path, std::ios::binary);
  16701. ofs.write(file_content.data(),
  16702. static_cast<std::streamsize>(file_content.size()));
  16703. }
  16704. auto handled = false;
  16705. Server svr;
  16706. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16707. const ContentReader &content_reader) {
  16708. ASSERT_TRUE(req.is_multipart_form_data());
  16709. std::vector<FormData> items;
  16710. content_reader(
  16711. [&](const FormData &file) {
  16712. items.push_back(file);
  16713. return true;
  16714. },
  16715. [&](const char *data, size_t data_length) {
  16716. items.back().content.append(data, data_length);
  16717. return true;
  16718. });
  16719. ASSERT_EQ(1u, items.size());
  16720. EXPECT_EQ("myfile", items[0].name);
  16721. EXPECT_EQ("data.bin", items[0].filename);
  16722. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16723. EXPECT_EQ(file_content, items[0].content);
  16724. handled = true;
  16725. });
  16726. auto port = svr.bind_to_any_port(HOST);
  16727. auto t = thread([&] { svr.listen_after_bind(); });
  16728. auto se = detail::scope_exit([&] {
  16729. svr.stop();
  16730. t.join();
  16731. ASSERT_FALSE(svr.is_running());
  16732. ASSERT_TRUE(handled);
  16733. std::remove(tmp_path.c_str());
  16734. });
  16735. svr.wait_until_ready();
  16736. FormDataProviderItems providers;
  16737. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16738. "application/octet-stream"));
  16739. Client cli(HOST, port);
  16740. auto res = cli.Post("/upload", {}, {}, providers);
  16741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16742. EXPECT_EQ(StatusCode::OK_200, res->status);
  16743. }
  16744. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16745. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16746. // (100) headers is rejected with a 400 Bad Request response.
  16747. Server svr;
  16748. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16749. res.set_content("ok", "text/plain");
  16750. });
  16751. thread t = thread([&] { svr.listen(HOST, PORT); });
  16752. auto se = detail::scope_exit([&] {
  16753. svr.stop();
  16754. t.join();
  16755. ASSERT_FALSE(svr.is_running());
  16756. });
  16757. svr.wait_until_ready();
  16758. // Build a multipart part with 101 custom headers (exceeding
  16759. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16760. std::stringstream body;
  16761. body << "--simpleboundary\r\n"
  16762. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16763. for (int i = 0; i < 101; i++) {
  16764. body << "X-Custom-Header-" << i << ": value\r\n";
  16765. }
  16766. body << "\r\n"
  16767. << "value1\r\n"
  16768. << "--simpleboundary--\r\n";
  16769. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16770. Client cli(HOST, PORT);
  16771. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16773. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16774. }
  16775. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16776. // A body that never contains the declared boundary must not be accumulated
  16777. // while the parser waits for it. Buffering it would also make every read
  16778. // rescan everything seen so far, which is quadratic in the body size.
  16779. Server svr;
  16780. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16781. res.set_content("ok", "text/plain");
  16782. });
  16783. auto port = svr.bind_to_any_port(HOST);
  16784. thread t = thread([&] { svr.listen_after_bind(); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. t.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. Client cli(HOST, port);
  16792. cli.set_read_timeout(60, 0);
  16793. cli.set_write_timeout(60, 0);
  16794. // '-' is the worst case: it matches the first character of the boundary, so
  16795. // every position has to be checked against it.
  16796. auto post_dashes = [&](size_t size) {
  16797. const std::string body(size, '-');
  16798. auto start = std::chrono::steady_clock::now();
  16799. auto res =
  16800. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16801. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16802. std::chrono::steady_clock::now() - start)
  16803. .count();
  16804. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16805. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16806. return ms;
  16807. };
  16808. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16809. // Windows.
  16810. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16811. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16812. // Comparing the two sizes rather than checking an absolute duration keeps
  16813. // this meaningful across build types and CI load, both of which move the
  16814. // absolute numbers by more than an order of magnitude. Four times the bytes
  16815. // costs about four times the time when parsing is linear, and about sixteen
  16816. // times when the body is buffered and rescanned.
  16817. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16818. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16819. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16820. << "ms, which suggests the body is being buffered and rescanned";
  16821. }
  16822. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16823. // A boundary can only be followed by CRLF or by "--", so anything else is
  16824. // malformed no matter what comes next. The parser must say so right away
  16825. // instead of buffering the rest of the declared body.
  16826. Server svr;
  16827. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16828. res.set_content("ok", "text/plain");
  16829. });
  16830. auto port = svr.bind_to_any_port(HOST);
  16831. thread t = thread([&] { svr.listen_after_bind(); });
  16832. auto se = detail::scope_exit([&] {
  16833. svr.stop();
  16834. t.join();
  16835. ASSERT_FALSE(svr.is_running());
  16836. });
  16837. svr.wait_until_ready();
  16838. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16839. // buffers instead of failing would still be waiting for the remaining bytes.
  16840. const std::string body = "--zzzz\r\n"
  16841. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16842. "\r\n"
  16843. "text1"
  16844. "\r\n--zzzzXX";
  16845. const std::string req = "POST /post HTTP/1.1\r\n"
  16846. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16847. "Content-Length: 1048576\r\n"
  16848. "\r\n" +
  16849. body;
  16850. std::string response;
  16851. ASSERT_TRUE(send_request(3, req, &response, port));
  16852. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16853. EXPECT_EQ("400", response.substr(9, 3));
  16854. }
  16855. // Posts a multipart body split into two writes, so that the server sees the
  16856. // split at whatever offset the caller chose, and expects the single "text1"
  16857. // field to come through.
  16858. static void expect_split_multipart_ok(const std::string &body1,
  16859. const std::string &body2) {
  16860. auto handled = false;
  16861. Server svr;
  16862. svr.Post("/post", [&](const Request &req, Response &) {
  16863. EXPECT_EQ(1u, req.form.fields.size());
  16864. EXPECT_EQ("text1", req.form.get_field("text1"));
  16865. handled = true;
  16866. });
  16867. auto port = svr.bind_to_any_port(HOST);
  16868. thread t = thread([&] { svr.listen_after_bind(); });
  16869. auto se = detail::scope_exit([&] {
  16870. svr.stop();
  16871. t.join();
  16872. ASSERT_FALSE(svr.is_running());
  16873. ASSERT_TRUE(handled);
  16874. });
  16875. svr.wait_until_ready();
  16876. // "Connection: close" makes the server close once it has answered, so the
  16877. // response drain ends immediately instead of idling until the read timeout.
  16878. const std::string head =
  16879. "POST /post HTTP/1.1\r\n"
  16880. "Host: localhost\r\n"
  16881. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16882. "Connection: close\r\n"
  16883. "Content-Length: " +
  16884. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16885. std::string response;
  16886. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16887. ASSERT_GE(response.size(), 12u) << "no response";
  16888. EXPECT_EQ("200", response.substr(9, 3));
  16889. }
  16890. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16891. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16892. // ignored, including when it does not arrive in the same read as the
  16893. // close-delimiter itself.
  16894. expect_split_multipart_ok("--zzzz\r\n"
  16895. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16896. "\r\n"
  16897. "text1"
  16898. "\r\n--zzzz--",
  16899. "\r\nthis epilogue must be ignored\r\n");
  16900. }
  16901. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16902. // The initial boundary may be preceded by a preamble of any length and may
  16903. // straddle a read boundary. Discarding data while waiting for it must not
  16904. // throw away a partial boundary sitting at the end of the buffer.
  16905. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16906. "zz\r\n"
  16907. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16908. "\r\n"
  16909. "text1"
  16910. "\r\n--zzzz--\r\n");
  16911. }
  16912. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16913. // The received boundary was only checked for being non-empty, so it could be
  16914. // as long as a header is allowed to be. The parser scans the body for
  16915. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16916. // costs a nearly full comparison at nearly every position, making the
  16917. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16918. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16919. Server svr;
  16920. svr.Post("/post", [](const Request &req, Response &res) {
  16921. EXPECT_EQ(1u, req.form.fields.size());
  16922. EXPECT_EQ("text1", req.form.get_field("text1"));
  16923. res.set_content("ok", "text/plain");
  16924. });
  16925. auto port = svr.bind_to_any_port(HOST);
  16926. thread t = thread([&] { svr.listen_after_bind(); });
  16927. auto se = detail::scope_exit([&] {
  16928. svr.stop();
  16929. t.join();
  16930. ASSERT_FALSE(svr.is_running());
  16931. });
  16932. svr.wait_until_ready();
  16933. Client cli(HOST, port);
  16934. auto post_with_boundary_of_length = [&](size_t len) {
  16935. const std::string boundary(len, 'a');
  16936. const std::string body =
  16937. "--" + boundary +
  16938. "\r\n"
  16939. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16940. "\r\n"
  16941. "text1"
  16942. "\r\n--" +
  16943. boundary + "--\r\n";
  16944. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16945. };
  16946. auto res = post_with_boundary_of_length(70);
  16947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16948. EXPECT_EQ(StatusCode::OK_200, res->status);
  16949. res = post_with_boundary_of_length(71);
  16950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16951. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16952. }
  16953. TEST(MakeFileBodyTest, Basic) {
  16954. const std::string file_content(4096, 'Z');
  16955. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16956. {
  16957. std::ofstream ofs(tmp_path, std::ios::binary);
  16958. ofs.write(file_content.data(),
  16959. static_cast<std::streamsize>(file_content.size()));
  16960. }
  16961. auto handled = false;
  16962. Server svr;
  16963. svr.Post("/upload", [&](const Request &req, Response &res) {
  16964. EXPECT_EQ(file_content, req.body);
  16965. handled = true;
  16966. res.status = StatusCode::OK_200;
  16967. });
  16968. auto port = svr.bind_to_any_port(HOST);
  16969. auto t = thread([&] { svr.listen_after_bind(); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. t.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. ASSERT_TRUE(handled);
  16975. std::remove(tmp_path.c_str());
  16976. });
  16977. svr.wait_until_ready();
  16978. auto fb = make_file_body(tmp_path);
  16979. ASSERT_GT(fb.first, 0u);
  16980. Client cli(HOST, port);
  16981. auto res =
  16982. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16984. EXPECT_EQ(StatusCode::OK_200, res->status);
  16985. }
  16986. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16987. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16988. {
  16989. std::ofstream ofs(path, std::ios::binary);
  16990. const std::string content(100, 'A');
  16991. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16992. }
  16993. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16994. auto body = make_file_body(path);
  16995. ASSERT_EQ(100u, body.first);
  16996. ASSERT_TRUE(static_cast<bool>(body.second));
  16997. // Rewritten shorter after its length was measured - and, on a server, after
  16998. // that length has already gone out as Content-Length.
  16999. {
  17000. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17001. const std::string content(10, 'A');
  17002. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17003. }
  17004. std::string written;
  17005. DataSink sink;
  17006. sink.write = [&](const char *d, size_t l) {
  17007. written.append(d, l);
  17008. return true;
  17009. };
  17010. // The provider has to report failure. write_content_with_progress() advances
  17011. // its offset only by what was written, so a provider that returns true
  17012. // without completing the length it promised is called again straight away,
  17013. // and again.
  17014. EXPECT_FALSE(body.second(0, body.first, sink));
  17015. EXPECT_EQ(std::string(10, 'A'), written);
  17016. }
  17017. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17018. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17019. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17020. {
  17021. std::ofstream ofs(path, std::ios::binary);
  17022. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17023. }
  17024. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17025. auto body = make_file_body(path);
  17026. ASSERT_EQ(content.size(), body.first);
  17027. ASSERT_TRUE(static_cast<bool>(body.second));
  17028. std::string written;
  17029. DataSink sink;
  17030. sink.write = [&](const char *d, size_t l) {
  17031. written.append(d, l);
  17032. return true;
  17033. };
  17034. EXPECT_TRUE(body.second(0, body.first, sink));
  17035. EXPECT_EQ(content, written);
  17036. }
  17037. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17038. static constexpr unsigned int number_of_tasks{1000000};
  17039. std::atomic_uint count{0};
  17040. std::unique_ptr<TaskQueue> task_queue{
  17041. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17042. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17043. auto queued = task_queue->enqueue(
  17044. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17045. EXPECT_TRUE(queued);
  17046. }
  17047. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17048. task_queue->shutdown();
  17049. #else
  17050. EXPECT_NO_THROW(task_queue->shutdown());
  17051. #endif
  17052. EXPECT_EQ(number_of_tasks, count.load());
  17053. }
  17054. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17055. static constexpr unsigned int number_of_tasks{1000000};
  17056. static constexpr unsigned int qlimit{2};
  17057. unsigned int queued_count{0};
  17058. std::atomic_uint count{0};
  17059. std::unique_ptr<TaskQueue> task_queue{
  17060. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17061. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17062. if (task_queue->enqueue(
  17063. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17064. queued_count++;
  17065. }
  17066. }
  17067. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17068. task_queue->shutdown();
  17069. #else
  17070. EXPECT_NO_THROW(task_queue->shutdown());
  17071. #endif
  17072. EXPECT_EQ(queued_count, count.load());
  17073. EXPECT_TRUE(queued_count <= number_of_tasks);
  17074. EXPECT_TRUE(queued_count >= qlimit);
  17075. }
  17076. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17077. // Use a short idle timeout so a dynamic thread spawns, times out and
  17078. // exits during the test, and the pool keeps working afterwards.
  17079. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17080. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17081. /*idle_timeout_sec=*/1}};
  17082. std::atomic_uint count{0};
  17083. std::condition_variable cv;
  17084. std::mutex mtx;
  17085. bool release = false;
  17086. // Block the base thread so the second task spawns a dynamic thread.
  17087. EXPECT_TRUE(task_queue->enqueue([&] {
  17088. std::unique_lock<std::mutex> lock(mtx);
  17089. while (!release) {
  17090. cv.wait(lock);
  17091. }
  17092. count++;
  17093. }));
  17094. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17095. // Let the dynamic thread finish its task and exceed the idle timeout.
  17096. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17097. {
  17098. std::unique_lock<std::mutex> lock(mtx);
  17099. release = true;
  17100. }
  17101. cv.notify_all();
  17102. // The pool must still accept and run tasks after the dynamic thread exited.
  17103. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17104. task_queue->shutdown();
  17105. EXPECT_EQ(3u, count.load());
  17106. }
  17107. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17108. static constexpr size_t number_of_tasks{32};
  17109. std::unique_ptr<TaskQueue> task_queue{
  17110. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17111. // Let the base threads go idle so the burst below finds them waiting.
  17112. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17113. std::mutex mtx;
  17114. std::condition_variable cv;
  17115. size_t running = 0;
  17116. bool release = false;
  17117. for (size_t i = 0; i < number_of_tasks; i++) {
  17118. EXPECT_TRUE(task_queue->enqueue([&] {
  17119. std::unique_lock<std::mutex> lock(mtx);
  17120. running++;
  17121. cv.notify_all();
  17122. cv.wait(lock, [&] { return release; });
  17123. }));
  17124. }
  17125. {
  17126. std::unique_lock<std::mutex> lock(mtx);
  17127. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17128. [&] { return running == number_of_tasks; }));
  17129. release = true;
  17130. }
  17131. cv.notify_all();
  17132. task_queue->shutdown();
  17133. }
  17134. TEST(TaskQueueTest, MaxQueuedRequests) {
  17135. static constexpr unsigned int qlimit{3};
  17136. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17137. std::condition_variable sem_cv;
  17138. std::mutex sem_mtx;
  17139. int credits = 0;
  17140. bool queued;
  17141. /* Fill up the queue with tasks that will block until we give them credits to
  17142. * complete. */
  17143. for (unsigned int n = 0; n <= qlimit;) {
  17144. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17145. std::unique_lock<std::mutex> lock(sem_mtx);
  17146. while (credits <= 0) {
  17147. sem_cv.wait(lock);
  17148. }
  17149. /* Consume the credit and signal the test code if they are all gone. */
  17150. if (--credits == 0) { sem_cv.notify_one(); }
  17151. });
  17152. if (n < qlimit) {
  17153. /* The first qlimit enqueues must succeed. */
  17154. EXPECT_TRUE(queued);
  17155. } else {
  17156. /* The last one will succeed only when the worker thread
  17157. * starts and dequeues the first blocking task. Although
  17158. * not necessary for the correctness of this test, we sleep for
  17159. * a short while to avoid busy waiting. */
  17160. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17161. }
  17162. if (queued) { n++; }
  17163. }
  17164. /* Further enqueues must fail since the queue is full. */
  17165. for (auto i = 0; i < 4; i++) {
  17166. queued = task_queue->enqueue([] {});
  17167. EXPECT_FALSE(queued);
  17168. }
  17169. /* Give the credits to allow the previous tasks to complete. */
  17170. {
  17171. std::unique_lock<std::mutex> lock(sem_mtx);
  17172. credits += qlimit + 1;
  17173. }
  17174. sem_cv.notify_all();
  17175. /* Wait for all the credits to be consumed. */
  17176. {
  17177. std::unique_lock<std::mutex> lock(sem_mtx);
  17178. while (credits > 0) {
  17179. sem_cv.wait(lock);
  17180. }
  17181. }
  17182. /* Check that we are able again to enqueue at least qlimit tasks. */
  17183. for (unsigned int i = 0; i < qlimit; i++) {
  17184. queued = task_queue->enqueue([] {});
  17185. EXPECT_TRUE(queued);
  17186. }
  17187. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17188. task_queue->shutdown();
  17189. #else
  17190. EXPECT_NO_THROW(task_queue->shutdown());
  17191. #endif
  17192. }
  17193. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17194. Server svr;
  17195. std::string method;
  17196. std::string body;
  17197. auto has_content_length = false;
  17198. auto has_transfer_encoding = false;
  17199. std::atomic<int> bad_requests{0};
  17200. // Leftover body bytes get parsed as a malformed request and answered with
  17201. // 400
  17202. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17203. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17204. });
  17205. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17206. res.set_redirect("/down", StatusCode::SeeOther_303);
  17207. });
  17208. svr.Get("/down", [&](const Request &req, Response &res) {
  17209. method = req.method;
  17210. body = req.body;
  17211. has_content_length = req.has_header("Content-Length");
  17212. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17213. res.set_content("ok", "text/plain");
  17214. });
  17215. auto port = svr.bind_to_any_port(HOST);
  17216. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17217. auto se = detail::scope_exit([&] {
  17218. svr.stop();
  17219. thread.join();
  17220. ASSERT_FALSE(svr.is_running());
  17221. });
  17222. svr.wait_until_ready();
  17223. const std::string payload = "SECRET-BODY";
  17224. auto check = [&](Client &cli, const Result &res) {
  17225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17226. EXPECT_EQ(StatusCode::OK_200, res->status);
  17227. EXPECT_EQ("ok", res->body);
  17228. EXPECT_EQ("GET", method);
  17229. EXPECT_TRUE(body.empty());
  17230. EXPECT_FALSE(has_content_length);
  17231. EXPECT_FALSE(has_transfer_encoding);
  17232. // Nothing of the original body may be left on the connection
  17233. auto res2 = cli.Get("/down");
  17234. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17235. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17236. EXPECT_EQ("ok", res2->body);
  17237. EXPECT_EQ(0, bad_requests);
  17238. };
  17239. // With content length
  17240. {
  17241. Client cli(HOST, port);
  17242. cli.set_keep_alive(true);
  17243. cli.set_follow_location(true);
  17244. auto res = cli.Post(
  17245. "/up", payload.size(),
  17246. [&](size_t offset, size_t length, DataSink &sink) {
  17247. return sink.write(payload.data() + offset, length);
  17248. },
  17249. "text/plain");
  17250. check(cli, res);
  17251. }
  17252. // Without content length (chunked)
  17253. {
  17254. Client cli(HOST, port);
  17255. cli.set_keep_alive(true);
  17256. cli.set_follow_location(true);
  17257. auto res = cli.Post(
  17258. "/up",
  17259. [&](size_t /*offset*/, DataSink &sink) {
  17260. sink.write(payload.data(), payload.size());
  17261. sink.done();
  17262. return true;
  17263. },
  17264. "text/plain");
  17265. check(cli, res);
  17266. }
  17267. }
  17268. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17269. Server svr;
  17270. std::string target;
  17271. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17272. // Echo the still-encoded name back in the Location
  17273. const std::string prefix = "/start/";
  17274. res.status = StatusCode::Found_302;
  17275. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17276. });
  17277. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17278. target = req.target;
  17279. res.set_content("ok", "text/plain");
  17280. });
  17281. auto port = svr.bind_to_any_port(HOST);
  17282. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17283. auto se = detail::scope_exit([&] {
  17284. svr.stop();
  17285. thread.join();
  17286. ASSERT_FALSE(svr.is_running());
  17287. });
  17288. svr.wait_until_ready();
  17289. // Decoding the Location path would turn the first four into a path
  17290. // separator, a query delimiter, a fragment delimiter and a different
  17291. // percent-encoded octet. The rest must keep reaching the server as they are.
  17292. const std::vector<std::string> names = {
  17293. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17294. };
  17295. for (auto path_encode : {true, false}) {
  17296. Client cli(HOST, port);
  17297. cli.set_follow_location(true);
  17298. cli.set_path_encode(path_encode);
  17299. for (const auto &name : names) {
  17300. target.clear();
  17301. auto res = cli.Get("/start/" + name);
  17302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17303. EXPECT_EQ(StatusCode::OK_200, res->status);
  17304. EXPECT_EQ("/dest/" + name, target);
  17305. }
  17306. }
  17307. }
  17308. TEST(RedirectTest, NotModifiedIsReturned) {
  17309. Server svr;
  17310. svr.Get("/cached", [](const Request &, Response &res) {
  17311. res.status = StatusCode::NotModified_304;
  17312. });
  17313. auto port = svr.bind_to_any_port(HOST);
  17314. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17315. auto se = detail::scope_exit([&] {
  17316. svr.stop();
  17317. thread.join();
  17318. ASSERT_FALSE(svr.is_running());
  17319. });
  17320. svr.wait_until_ready();
  17321. Client cli(HOST, port);
  17322. cli.set_follow_location(true);
  17323. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17325. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17326. }
  17327. TEST(RedirectTest, NoLocationIsReturned) {
  17328. Server svr;
  17329. svr.Get("/no-location", [](const Request &, Response &res) {
  17330. res.status = StatusCode::Found_302;
  17331. res.set_content("no location", "text/plain");
  17332. });
  17333. auto port = svr.bind_to_any_port(HOST);
  17334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17335. auto se = detail::scope_exit([&] {
  17336. svr.stop();
  17337. thread.join();
  17338. ASSERT_FALSE(svr.is_running());
  17339. });
  17340. svr.wait_until_ready();
  17341. Client cli(HOST, port);
  17342. cli.set_follow_location(true);
  17343. auto res = cli.Get("/no-location");
  17344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17345. EXPECT_EQ(StatusCode::Found_302, res->status);
  17346. EXPECT_EQ("no location", res->body);
  17347. // The callbacks see the body of the response that is returned
  17348. auto handler_called = false;
  17349. auto progress_called = false;
  17350. std::string body;
  17351. auto res2 = cli.Get(
  17352. "/no-location",
  17353. [&](const Response &) {
  17354. handler_called = true;
  17355. return true;
  17356. },
  17357. [&](const char *data, size_t data_length) {
  17358. body.append(data, data_length);
  17359. return true;
  17360. },
  17361. [&](size_t, size_t) {
  17362. progress_called = true;
  17363. return true;
  17364. });
  17365. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17366. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17367. EXPECT_TRUE(handler_called);
  17368. EXPECT_TRUE(progress_called);
  17369. EXPECT_EQ("no location", body);
  17370. }
  17371. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17372. Server svr;
  17373. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17374. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17375. });
  17376. svr.Get("/hello", [](const Request &req, Response &res) {
  17377. res.set_content(req.get_param_value("key"), "text/plain");
  17378. });
  17379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17380. auto se = detail::scope_exit([&] {
  17381. svr.stop();
  17382. thread.join();
  17383. ASSERT_FALSE(svr.is_running());
  17384. });
  17385. svr.wait_until_ready();
  17386. {
  17387. Client cli(HOST, PORT);
  17388. cli.set_follow_location(true);
  17389. auto res = cli.Get("/");
  17390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17391. EXPECT_EQ(StatusCode::OK_200, res->status);
  17392. EXPECT_EQ("val&key2=val2", res->body);
  17393. }
  17394. }
  17395. #endif
  17396. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17397. Server svr;
  17398. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17399. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17400. });
  17401. svr.Get("/hello", [](const Request &req, Response &res) {
  17402. res.set_content(req.get_param_value("key"), "text/plain");
  17403. });
  17404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17405. auto se = detail::scope_exit([&] {
  17406. svr.stop();
  17407. thread.join();
  17408. ASSERT_FALSE(svr.is_running());
  17409. });
  17410. svr.wait_until_ready();
  17411. {
  17412. Client cli(HOST, PORT);
  17413. cli.set_follow_location(true);
  17414. auto res = cli.Get("/");
  17415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17416. EXPECT_EQ(StatusCode::OK_200, res->status);
  17417. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17418. }
  17419. }
  17420. TEST(RedirectTest, RedirectWithPlusInPath) {
  17421. Server svr;
  17422. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17423. res.set_redirect("/a+b");
  17424. });
  17425. // Route pattern uses regex; escape + as \\+
  17426. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17427. res.set_content(req.path, "text/plain");
  17428. });
  17429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17430. auto se = detail::scope_exit([&] {
  17431. svr.stop();
  17432. thread.join();
  17433. ASSERT_FALSE(svr.is_running());
  17434. });
  17435. svr.wait_until_ready();
  17436. {
  17437. Client cli(HOST, PORT);
  17438. cli.set_follow_location(true);
  17439. auto res = cli.Get("/");
  17440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17441. EXPECT_EQ(StatusCode::OK_200, res->status);
  17442. EXPECT_EQ("/a+b", res->body);
  17443. }
  17444. }
  17445. TEST(RedirectTest, ResolveRelativeLocation) {
  17446. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17447. const std::vector<std::pair<std::string, std::string>> cases = {
  17448. {"g", "/b/c/g"},
  17449. {"./g", "/b/c/g"},
  17450. {"g/", "/b/c/g/"},
  17451. {"?y", "/b/c/d;p?y"},
  17452. {"g?y", "/b/c/g?y"},
  17453. {"#s", "/b/c/d;p?q#s"},
  17454. {"g#s", "/b/c/g#s"},
  17455. {"g?y#s", "/b/c/g?y#s"},
  17456. {";x", "/b/c/;x"},
  17457. {"g;x", "/b/c/g;x"},
  17458. {".", "/b/c/"},
  17459. {"./", "/b/c/"},
  17460. {"..", "/b/"},
  17461. {"../", "/b/"},
  17462. {"../g", "/b/g"},
  17463. {"../..", "/"},
  17464. {"../../", "/"},
  17465. {"../../g", "/g"},
  17466. {"../../../g", "/g"},
  17467. {"g.", "/b/c/g."},
  17468. {".g", "/b/c/.g"},
  17469. {"g..", "/b/c/g.."},
  17470. {"..g", "/b/c/..g"},
  17471. {"./../g", "/b/g"},
  17472. {"./g/.", "/b/c/g/"},
  17473. {"g/./h", "/b/c/g/h"},
  17474. {"g/../h", "/b/c/h"},
  17475. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17476. {"g;x=1/../y", "/b/c/y"},
  17477. {"g?y/./x", "/b/c/g?y/./x"},
  17478. {"g#s/../x", "/b/c/g#s/../x"},
  17479. // Not relative-path references, so left for parse_url.
  17480. {"/g", "/g"},
  17481. {"//g", "//g"},
  17482. {"http://g/x", "http://g/x"},
  17483. {"g:h", "g:h"},
  17484. };
  17485. for (const auto &c : cases) {
  17486. EXPECT_EQ(c.second,
  17487. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17488. << c.first;
  17489. }
  17490. // A result starting with "//" is still a path, not a network-path reference
  17491. EXPECT_EQ("/.//g",
  17492. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17493. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17494. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17495. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17496. }
  17497. TEST(RedirectTest, RemoveDotSegments) {
  17498. // RFC 3986 section 5.2.4
  17499. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17500. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17501. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17502. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17503. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17504. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17505. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17506. }
  17507. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17508. Server svr;
  17509. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17510. res.set_redirect("/dir/../target?x=1");
  17511. });
  17512. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17513. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17514. "/dir/./../target");
  17515. });
  17516. svr.Get("/target", [](const Request &req, Response &res) {
  17517. res.set_content(req.path, "text/plain");
  17518. });
  17519. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17520. auto se = detail::scope_exit([&] {
  17521. svr.stop();
  17522. th.join();
  17523. ASSERT_FALSE(svr.is_running());
  17524. });
  17525. svr.wait_until_ready();
  17526. Client cli("localhost", PORT);
  17527. cli.set_follow_location(true);
  17528. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17529. auto res = cli.Get(path);
  17530. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17531. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17532. EXPECT_EQ("/target", res->body) << path;
  17533. }
  17534. }
  17535. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17536. Server svr;
  17537. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17538. res.set_redirect(req.get_param_value("to"));
  17539. });
  17540. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17541. res.set_content(req.target, "text/plain");
  17542. });
  17543. svr.Get("/other", [](const Request &req, Response &res) {
  17544. res.set_content(req.target, "text/plain");
  17545. });
  17546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17547. auto se = detail::scope_exit([&] {
  17548. svr.stop();
  17549. thread.join();
  17550. ASSERT_FALSE(svr.is_running());
  17551. });
  17552. svr.wait_until_ready();
  17553. const std::vector<std::pair<std::string, std::string>> cases = {
  17554. {"next", "/dir/next"},
  17555. {"./next?x=1", "/dir/next?x=1"},
  17556. {"../other", "/other"},
  17557. };
  17558. for (const auto &c : cases) {
  17559. Client cli(HOST, PORT);
  17560. cli.set_follow_location(true);
  17561. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17562. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17563. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17564. EXPECT_EQ(c.second, res->body) << c.first;
  17565. }
  17566. }
  17567. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17568. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17569. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17570. Server other;
  17571. std::atomic<int> other_hits{0};
  17572. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17573. other_hits++;
  17574. res.set_content("other", "text/plain");
  17575. });
  17576. auto other_port = other.bind_to_any_port("127.0.0.1");
  17577. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17578. Server svr;
  17579. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17580. res.set_redirect(req.get_param_value("to"));
  17581. });
  17582. svr.Get(".*", [](const Request &req, Response &res) {
  17583. res.set_content(req.path, "text/plain");
  17584. });
  17585. auto port = svr.bind_to_any_port(HOST);
  17586. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17587. auto se = detail::scope_exit([&] {
  17588. svr.stop();
  17589. thread.join();
  17590. other.stop();
  17591. other_thread.join();
  17592. ASSERT_FALSE(svr.is_running());
  17593. ASSERT_FALSE(other.is_running());
  17594. });
  17595. svr.wait_until_ready();
  17596. other.wait_until_ready();
  17597. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17598. for (const auto &to :
  17599. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17600. Client cli(HOST, port);
  17601. cli.set_follow_location(true);
  17602. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17603. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17604. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17605. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17606. }
  17607. EXPECT_EQ(0, other_hits.load());
  17608. }
  17609. #ifdef CPPHTTPLIB_SSL_ENABLED
  17610. TEST(RedirectTest, Issue2185_Online) {
  17611. SSLClient client("github.com");
  17612. client.set_follow_location(true);
  17613. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17614. "Coollab-Windows.zip");
  17615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17616. EXPECT_EQ(StatusCode::OK_200, res->status);
  17617. EXPECT_EQ(9920427U, res->body.size());
  17618. }
  17619. #endif
  17620. TEST(VulnerabilityTest, CRLFInjection) {
  17621. Server svr;
  17622. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17623. res.set_content("Hello 1", "text/plain");
  17624. });
  17625. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17626. res.set_content("Hello 2", "text/plain");
  17627. });
  17628. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17629. res.set_content("Hello 3", "text/plain");
  17630. });
  17631. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17632. res.set_content("Hello 4", "text/plain");
  17633. });
  17634. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17635. for (const auto &x : req.headers) {
  17636. auto key = x.first;
  17637. EXPECT_STRNE("evil", key.c_str());
  17638. }
  17639. });
  17640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17641. auto se = detail::scope_exit([&] {
  17642. svr.stop();
  17643. thread.join();
  17644. ASSERT_FALSE(svr.is_running());
  17645. });
  17646. svr.wait_until_ready();
  17647. {
  17648. Client cli(HOST, PORT);
  17649. cli.Post("/test1", "A=B",
  17650. "application/x-www-form-urlencoded\r\nevil: hello1");
  17651. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17652. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17653. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17654. }
  17655. }
  17656. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17657. auto server_thread = std::thread([] {
  17658. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17659. default_socket_options(srv);
  17660. sockaddr_in addr{};
  17661. addr.sin_family = AF_INET;
  17662. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17663. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17664. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17665. ::listen(srv, 1);
  17666. sockaddr_in cli_addr{};
  17667. socklen_t cli_len = sizeof(cli_addr);
  17668. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17669. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17670. std::string buf_all;
  17671. char buf[2048];
  17672. ssize_t n;
  17673. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17674. buf_all.append(buf, static_cast<size_t>(n));
  17675. size_t pos;
  17676. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17677. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17678. auto e = request_block.find("\r\n");
  17679. if (e != std::string::npos) {
  17680. auto request_line = request_block.substr(0, e);
  17681. std::string msg =
  17682. "CRLF injection detected in request line: '" + request_line + "'";
  17683. EXPECT_FALSE(true) << msg;
  17684. }
  17685. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17686. ::send(cli,
  17687. #ifdef _WIN32
  17688. static_cast<const char *>(resp.c_str()),
  17689. static_cast<int>(resp.size()),
  17690. #else
  17691. resp.c_str(), resp.size(),
  17692. #endif
  17693. 0);
  17694. buf_all.erase(0, pos + 4);
  17695. }
  17696. }
  17697. detail::close_socket(cli);
  17698. detail::close_socket(srv);
  17699. });
  17700. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17701. auto cli = Client("127.0.0.1", PORT + 1);
  17702. auto headers = Headers{
  17703. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17704. {"Connection", "keep-alive"}};
  17705. auto res = cli.Get("/hi", headers);
  17706. EXPECT_FALSE(res);
  17707. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17708. server_thread.join();
  17709. }
  17710. // A request rejected before any byte reaches the socket must fail right away
  17711. // instead of waiting for a response the server will never send.
  17712. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17713. // The kernel completes the TCP handshake from the listen backlog, so the
  17714. // client connects, but nothing ever reads, responds or closes.
  17715. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17716. default_socket_options(srv);
  17717. sockaddr_in addr{};
  17718. addr.sin_family = AF_INET;
  17719. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17720. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17721. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17722. ASSERT_EQ(0, ::listen(srv, 8));
  17723. auto cli = Client("127.0.0.1", PORT + 1);
  17724. cli.set_read_timeout(10, 0);
  17725. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17726. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17727. std::chrono::steady_clock::now() - start)
  17728. .count();
  17729. };
  17730. {
  17731. Request req;
  17732. req.method = "GE T";
  17733. req.path = "/";
  17734. auto start = std::chrono::steady_clock::now();
  17735. auto res = cli.send(req);
  17736. EXPECT_FALSE(res);
  17737. EXPECT_EQ(Error::Write, res.error());
  17738. EXPECT_LT(elapsed_ms(start), 1000);
  17739. }
  17740. {
  17741. auto start = std::chrono::steady_clock::now();
  17742. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17743. EXPECT_FALSE(res);
  17744. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17745. EXPECT_LT(elapsed_ms(start), 1000);
  17746. }
  17747. EXPECT_FALSE(cli.is_socket_open());
  17748. detail::close_socket(srv);
  17749. }
  17750. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17751. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17752. default_socket_options(srv);
  17753. sockaddr_in addr{};
  17754. addr.sin_family = AF_INET;
  17755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17757. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17758. ASSERT_EQ(0, ::listen(srv, 1));
  17759. std::string received;
  17760. auto server_thread = std::thread([&] {
  17761. auto sock = ::accept(srv, nullptr, nullptr);
  17762. if (sock == INVALID_SOCKET) { return; }
  17763. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17764. char buf[2048];
  17765. ssize_t n;
  17766. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17767. received.append(buf, static_cast<size_t>(n));
  17768. }
  17769. detail::close_socket(sock);
  17770. });
  17771. {
  17772. auto cli = Client("127.0.0.1", PORT + 1);
  17773. // "Z" sorts after the default headers, so writing straight to the socket
  17774. // would have sent the request line and those headers before the rejection.
  17775. auto handle =
  17776. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17777. EXPECT_FALSE(handle.is_valid());
  17778. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17779. }
  17780. server_thread.join();
  17781. detail::close_socket(srv);
  17782. EXPECT_TRUE(received.empty()) << received;
  17783. }
  17784. TEST(PathParamsTest, StaticMatch) {
  17785. const auto pattern = "/users/all";
  17786. detail::PathParamsMatcher matcher(pattern);
  17787. Request request;
  17788. request.path = "/users/all";
  17789. ASSERT_TRUE(matcher.match(request));
  17790. std::unordered_map<std::string, std::string> expected_params = {};
  17791. EXPECT_EQ(request.path_params, expected_params);
  17792. }
  17793. TEST(PathParamsTest, StaticMismatch) {
  17794. const auto pattern = "/users/all";
  17795. detail::PathParamsMatcher matcher(pattern);
  17796. Request request;
  17797. request.path = "/users/1";
  17798. ASSERT_FALSE(matcher.match(request));
  17799. }
  17800. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17801. const auto pattern = "/users/:id/subscriptions";
  17802. detail::PathParamsMatcher matcher(pattern);
  17803. Request request;
  17804. request.path = "/users/42/subscriptions";
  17805. ASSERT_TRUE(matcher.match(request));
  17806. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17807. EXPECT_EQ(request.path_params, expected_params);
  17808. }
  17809. TEST(PathParamsTest, SingleParamInTheEnd) {
  17810. const auto pattern = "/users/:id";
  17811. detail::PathParamsMatcher matcher(pattern);
  17812. Request request;
  17813. request.path = "/users/24";
  17814. ASSERT_TRUE(matcher.match(request));
  17815. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17816. EXPECT_EQ(request.path_params, expected_params);
  17817. }
  17818. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17819. const auto pattern = "/users/:id/";
  17820. detail::PathParamsMatcher matcher(pattern);
  17821. Request request;
  17822. request.path = "/users/42/";
  17823. ASSERT_TRUE(matcher.match(request));
  17824. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17825. EXPECT_EQ(request.path_params, expected_params);
  17826. }
  17827. TEST(PathParamsTest, EmptyParam) {
  17828. const auto pattern = "/users/:id/";
  17829. detail::PathParamsMatcher matcher(pattern);
  17830. Request request;
  17831. request.path = "/users//";
  17832. ASSERT_TRUE(matcher.match(request));
  17833. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17834. EXPECT_EQ(request.path_params, expected_params);
  17835. }
  17836. TEST(PathParamsTest, FragmentMismatch) {
  17837. const auto pattern = "/users/:id/";
  17838. detail::PathParamsMatcher matcher(pattern);
  17839. Request request;
  17840. request.path = "/admins/24/";
  17841. ASSERT_FALSE(matcher.match(request));
  17842. }
  17843. TEST(PathParamsTest, ExtraFragments) {
  17844. const auto pattern = "/users/:id";
  17845. detail::PathParamsMatcher matcher(pattern);
  17846. Request request;
  17847. request.path = "/users/42/subscriptions";
  17848. ASSERT_FALSE(matcher.match(request));
  17849. }
  17850. TEST(PathParamsTest, MissingTrailingParam) {
  17851. const auto pattern = "/users/:id";
  17852. detail::PathParamsMatcher matcher(pattern);
  17853. Request request;
  17854. request.path = "/users";
  17855. ASSERT_FALSE(matcher.match(request));
  17856. }
  17857. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17858. const auto pattern = "/users/:id/subscriptions";
  17859. detail::PathParamsMatcher matcher(pattern);
  17860. Request request;
  17861. request.path = "/users/subscriptions";
  17862. ASSERT_FALSE(matcher.match(request));
  17863. }
  17864. TEST(PathParamsTest, MultipleParams) {
  17865. const auto pattern = "/users/:userid/subscriptions/:subid";
  17866. detail::PathParamsMatcher matcher(pattern);
  17867. Request request;
  17868. request.path = "/users/42/subscriptions/2";
  17869. ASSERT_TRUE(matcher.match(request));
  17870. std::unordered_map<std::string, std::string> expected_params = {
  17871. {"userid", "42"}, {"subid", "2"}};
  17872. EXPECT_EQ(request.path_params, expected_params);
  17873. }
  17874. TEST(PathParamsTest, SequenceOfParams) {
  17875. const auto pattern = "/values/:x/:y/:z";
  17876. detail::PathParamsMatcher matcher(pattern);
  17877. Request request;
  17878. request.path = "/values/1/2/3";
  17879. ASSERT_TRUE(matcher.match(request));
  17880. std::unordered_map<std::string, std::string> expected_params = {
  17881. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17882. EXPECT_EQ(request.path_params, expected_params);
  17883. }
  17884. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17885. const auto pattern = "/prefix:suffix";
  17886. detail::PathParamsMatcher matcher(pattern);
  17887. Request request;
  17888. request.path = "/prefix:suffix";
  17889. ASSERT_TRUE(matcher.match(request));
  17890. const std::unordered_map<std::string, std::string> expected_params = {};
  17891. EXPECT_EQ(request.path_params, expected_params);
  17892. }
  17893. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17894. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17895. // calling thread's stack on a long enough path for a quantified pattern;
  17896. // RegexMatcher must refuse to run regex matching on paths beyond
  17897. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17898. detail::RegexMatcher matcher("/files/(.*)");
  17899. Request within_limit;
  17900. within_limit.path = "/files/" + std::string(10, 'A');
  17901. EXPECT_TRUE(matcher.match(within_limit));
  17902. Request over_limit;
  17903. over_limit.path =
  17904. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17905. EXPECT_FALSE(matcher.match(over_limit));
  17906. }
  17907. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17908. Server svr;
  17909. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17910. res.set_content("ok", "text/plain");
  17911. });
  17912. auto port = svr.bind_to_any_port(HOST);
  17913. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17914. auto se = detail::scope_exit([&] {
  17915. svr.stop();
  17916. thread.join();
  17917. ASSERT_FALSE(svr.is_running());
  17918. });
  17919. svr.wait_until_ready();
  17920. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17921. // request URI limit; this used to be able to crash the process.
  17922. std::string path =
  17923. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17924. std::string req = "GET " + path +
  17925. " HTTP/1.1\r\n"
  17926. "Host: " +
  17927. std::string(HOST) + ":" + std::to_string(port) +
  17928. "\r\n"
  17929. "Connection: close\r\n"
  17930. "\r\n";
  17931. std::string response;
  17932. ASSERT_TRUE(send_request(5, req, &response, port));
  17933. EXPECT_NE(std::string::npos, response.find("404"));
  17934. }
  17935. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17936. Server svr;
  17937. auto handler = [](const Request & /*req*/, Response &res) {
  17938. res.set_content("hit", "text/plain");
  17939. };
  17940. // No regex metacharacter, so this one is compared literally
  17941. svr.Get("/literal/route", handler);
  17942. // '.' is a regex metacharacter, so this one must keep regex semantics
  17943. svr.Get("/a.c", handler);
  17944. auto port = svr.bind_to_any_port(HOST);
  17945. std::thread t([&]() { svr.listen_after_bind(); });
  17946. auto se = detail::scope_exit([&] {
  17947. svr.stop();
  17948. t.join();
  17949. ASSERT_FALSE(svr.is_running());
  17950. });
  17951. svr.wait_until_ready();
  17952. Client cli(HOST, port);
  17953. struct {
  17954. const char *path;
  17955. int status;
  17956. } cases[] = {
  17957. {"/literal/route", StatusCode::OK_200},
  17958. {"/literal/routes", StatusCode::NotFound_404},
  17959. {"/literal/rout", StatusCode::NotFound_404},
  17960. {"/abc", StatusCode::OK_200},
  17961. {"/a.c", StatusCode::OK_200},
  17962. };
  17963. for (const auto &x : cases) {
  17964. auto res = cli.Get(x.path);
  17965. ASSERT_TRUE(res) << x.path;
  17966. EXPECT_EQ(x.status, res->status) << x.path;
  17967. }
  17968. }
  17969. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17970. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17971. // from exhausting the stack, so it must only constrain routes that actually
  17972. // run a regular expression. A literal route is matched by comparison and
  17973. // stays usable at any length.
  17974. Server svr;
  17975. const std::string pattern =
  17976. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17977. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17978. res.set_content("hit", "text/plain");
  17979. });
  17980. auto port = svr.bind_to_any_port(HOST);
  17981. std::thread t([&]() { svr.listen_after_bind(); });
  17982. auto se = detail::scope_exit([&] {
  17983. svr.stop();
  17984. t.join();
  17985. ASSERT_FALSE(svr.is_running());
  17986. });
  17987. svr.wait_until_ready();
  17988. Client cli(HOST, port);
  17989. auto res = cli.Get(pattern);
  17990. ASSERT_TRUE(res);
  17991. EXPECT_EQ(StatusCode::OK_200, res->status);
  17992. }
  17993. TEST(ParseUrlTest, VariousPatterns) {
  17994. {
  17995. detail::UrlComponents uc;
  17996. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17997. EXPECT_EQ("http", uc.scheme);
  17998. EXPECT_EQ("example.com", uc.host);
  17999. EXPECT_EQ("8080", uc.port);
  18000. EXPECT_EQ("/path", uc.path);
  18001. EXPECT_EQ("?q=1", uc.query);
  18002. }
  18003. {
  18004. detail::UrlComponents uc;
  18005. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18006. EXPECT_EQ("https", uc.scheme);
  18007. EXPECT_EQ("example.com", uc.host);
  18008. EXPECT_TRUE(uc.port.empty());
  18009. EXPECT_EQ("/path", uc.path);
  18010. }
  18011. {
  18012. detail::UrlComponents uc;
  18013. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18014. EXPECT_EQ("::1", uc.host);
  18015. EXPECT_EQ("8080", uc.port);
  18016. EXPECT_EQ("/path", uc.path);
  18017. }
  18018. {
  18019. detail::UrlComponents uc;
  18020. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18021. }
  18022. {
  18023. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18024. // the path while the connection still targets the bracketed host.
  18025. detail::UrlComponents uc;
  18026. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18027. }
  18028. {
  18029. detail::UrlComponents uc;
  18030. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18031. }
  18032. {
  18033. detail::UrlComponents uc;
  18034. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18035. EXPECT_EQ("::1", uc.host);
  18036. EXPECT_TRUE(uc.port.empty());
  18037. EXPECT_EQ("/path", uc.path);
  18038. }
  18039. {
  18040. detail::UrlComponents uc;
  18041. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18042. EXPECT_TRUE(uc.scheme.empty());
  18043. EXPECT_EQ("example.com", uc.host);
  18044. EXPECT_EQ("/path", uc.path);
  18045. EXPECT_EQ("?q=1", uc.query);
  18046. }
  18047. {
  18048. detail::UrlComponents uc;
  18049. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18050. EXPECT_TRUE(uc.host.empty());
  18051. EXPECT_EQ("/path", uc.path);
  18052. EXPECT_EQ("?q=1", uc.query);
  18053. }
  18054. {
  18055. detail::UrlComponents uc;
  18056. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18057. EXPECT_EQ("example.com", uc.host);
  18058. EXPECT_EQ("8080", uc.port);
  18059. }
  18060. {
  18061. // Unix socket path — must not be parsed as host
  18062. detail::UrlComponents uc;
  18063. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18064. EXPECT_TRUE(uc.host.empty());
  18065. }
  18066. {
  18067. detail::UrlComponents uc;
  18068. ASSERT_TRUE(detail::parse_url("", uc));
  18069. EXPECT_TRUE(uc.host.empty());
  18070. EXPECT_TRUE(uc.path.empty());
  18071. }
  18072. {
  18073. detail::UrlComponents uc;
  18074. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18075. }
  18076. {
  18077. detail::UrlComponents uc;
  18078. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18079. }
  18080. {
  18081. // Accepted by parse_url; callers restrict to http/https
  18082. detail::UrlComponents uc;
  18083. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18084. EXPECT_EQ("ftp", uc.scheme);
  18085. }
  18086. {
  18087. detail::UrlComponents uc;
  18088. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18089. }
  18090. {
  18091. detail::UrlComponents uc;
  18092. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18093. }
  18094. }
  18095. TEST(ParseUrlTest, FragmentHandling) {
  18096. {
  18097. detail::UrlComponents uc;
  18098. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18099. EXPECT_EQ("/path", uc.path);
  18100. EXPECT_TRUE(uc.query.empty());
  18101. }
  18102. {
  18103. detail::UrlComponents uc;
  18104. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18105. EXPECT_TRUE(uc.path.empty());
  18106. EXPECT_TRUE(uc.query.empty());
  18107. }
  18108. }
  18109. TEST(ParseUrlTest, UserinfoHandling) {
  18110. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18111. // parsers would see evil.com as the host.
  18112. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18113. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18114. for (auto url : urls) {
  18115. detail::UrlComponents uc;
  18116. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18117. }
  18118. }
  18119. TEST(ParseUrlTest, IPv6EdgeCases) {
  18120. {
  18121. detail::UrlComponents uc;
  18122. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18123. EXPECT_TRUE(uc.scheme.empty());
  18124. EXPECT_EQ("::1", uc.host);
  18125. EXPECT_EQ("8080", uc.port);
  18126. }
  18127. {
  18128. // Zone ID '%25' is not in [a-fA-F0-9:]
  18129. detail::UrlComponents uc;
  18130. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18131. }
  18132. }
  18133. TEST(ParseUrlTest, SchemeEdgeCases) {
  18134. {
  18135. detail::UrlComponents uc;
  18136. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18137. }
  18138. {
  18139. detail::UrlComponents uc;
  18140. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18141. }
  18142. {
  18143. detail::UrlComponents uc;
  18144. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18145. }
  18146. }
  18147. TEST(ParseUrlTest, PortEdgeCases) {
  18148. {
  18149. detail::UrlComponents uc;
  18150. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18151. EXPECT_TRUE(uc.port.empty());
  18152. EXPECT_EQ("/path", uc.path);
  18153. }
  18154. {
  18155. // parse_url accepts any port string; validation is done by parse_port
  18156. detail::UrlComponents uc;
  18157. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18158. EXPECT_EQ("abc", uc.port);
  18159. }
  18160. }
  18161. TEST(ParseUrlTest, WebSocketPatterns) {
  18162. {
  18163. detail::UrlComponents uc;
  18164. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18165. EXPECT_EQ("ws", uc.scheme);
  18166. EXPECT_EQ("echo.example.com", uc.host);
  18167. EXPECT_EQ("8080", uc.port);
  18168. EXPECT_EQ("/ws", uc.path);
  18169. }
  18170. {
  18171. detail::UrlComponents uc;
  18172. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18173. EXPECT_EQ("wss", uc.scheme);
  18174. EXPECT_EQ("echo.example.com", uc.host);
  18175. EXPECT_TRUE(uc.port.empty());
  18176. EXPECT_EQ("/ws", uc.path);
  18177. }
  18178. }
  18179. TEST(ParseUrlTest, QueryOnly) {
  18180. detail::UrlComponents uc;
  18181. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18182. EXPECT_TRUE(uc.host.empty());
  18183. EXPECT_TRUE(uc.path.empty());
  18184. EXPECT_EQ("?q=1&r=2", uc.query);
  18185. }
  18186. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18187. detail::UrlComponents uc;
  18188. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18189. EXPECT_TRUE(uc.scheme.empty());
  18190. EXPECT_EQ("example.com", uc.host);
  18191. EXPECT_EQ("443", uc.port);
  18192. EXPECT_EQ("/path", uc.path);
  18193. }
  18194. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18195. // If ipv6 regex working, regex match codepath is taken.
  18196. // else port will default to 80 in Client impl
  18197. int clientImplMagicPort = 80;
  18198. int port = 4321;
  18199. // above ports must be different to avoid false negative
  18200. EXPECT_NE(clientImplMagicPort, port);
  18201. std::string ipV6TestURL = "http://[ff06::c3]";
  18202. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18203. CLIENT_PRIVATE_KEY_FILE);
  18204. EXPECT_EQ(cli.port(), port);
  18205. }
  18206. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18207. auto file_path = "./www/dir/index.html";
  18208. auto dir_path = "./www/dir";
  18209. detail::FileStat stat_file(file_path);
  18210. EXPECT_TRUE(stat_file.is_file());
  18211. EXPECT_FALSE(stat_file.is_dir());
  18212. detail::FileStat stat_dir(dir_path);
  18213. EXPECT_FALSE(stat_dir.is_file());
  18214. EXPECT_TRUE(stat_dir.is_dir());
  18215. }
  18216. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18217. // IPv4 with default HTTP port (80)
  18218. EXPECT_EQ("example.com",
  18219. detail::make_host_and_port_string("example.com", 80, false));
  18220. // IPv4 with default HTTPS port (443)
  18221. EXPECT_EQ("example.com",
  18222. detail::make_host_and_port_string("example.com", 443, true));
  18223. // IPv4 with non-default HTTP port
  18224. EXPECT_EQ("example.com:8080",
  18225. detail::make_host_and_port_string("example.com", 8080, false));
  18226. // IPv4 with non-default HTTPS port
  18227. EXPECT_EQ("example.com:8443",
  18228. detail::make_host_and_port_string("example.com", 8443, true));
  18229. // IPv6 with default HTTP port (80)
  18230. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18231. // IPv6 with default HTTPS port (443)
  18232. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18233. // IPv6 with non-default HTTP port
  18234. EXPECT_EQ("[::1]:8080",
  18235. detail::make_host_and_port_string("::1", 8080, false));
  18236. // IPv6 with non-default HTTPS port
  18237. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18238. // IPv6 full address with default port
  18239. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18240. detail::make_host_and_port_string(
  18241. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18242. // IPv6 full address with non-default port
  18243. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18244. detail::make_host_and_port_string(
  18245. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18246. // IPv6 localhost with non-default port
  18247. EXPECT_EQ("[::1]:3000",
  18248. detail::make_host_and_port_string("::1", 3000, false));
  18249. // IPv6 with zone ID (link-local address) with default port
  18250. EXPECT_EQ("[fe80::1%eth0]",
  18251. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18252. // IPv6 with zone ID (link-local address) with non-default port
  18253. EXPECT_EQ("[fe80::1%eth0]:8080",
  18254. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18255. // Edge case: Port 443 with is_ssl=false (should add port)
  18256. EXPECT_EQ("example.com:443",
  18257. detail::make_host_and_port_string("example.com", 443, false));
  18258. // Edge case: Port 80 with is_ssl=true (should add port)
  18259. EXPECT_EQ("example.com:80",
  18260. detail::make_host_and_port_string("example.com", 80, true));
  18261. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18262. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18263. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18264. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18265. // Security fix: Already bracketed IPv6 should not get double brackets
  18266. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18267. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18268. EXPECT_EQ("[::1]:8080",
  18269. detail::make_host_and_port_string("[::1]", 8080, false));
  18270. EXPECT_EQ("[2001:db8::1]:8080",
  18271. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18272. EXPECT_EQ("[fe80::1%eth0]",
  18273. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18274. EXPECT_EQ("[fe80::1%eth0]:8080",
  18275. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18276. // Edge case: Empty host (should return as-is)
  18277. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18278. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18279. // This is a known limitation but shouldn't crash
  18280. EXPECT_EQ("[host:name]",
  18281. detail::make_host_and_port_string("host:name", 80, false));
  18282. // Port number edge cases (no validation, but should not crash)
  18283. EXPECT_EQ("example.com:0",
  18284. detail::make_host_and_port_string("example.com", 0, false));
  18285. EXPECT_EQ("example.com:-1",
  18286. detail::make_host_and_port_string("example.com", -1, false));
  18287. EXPECT_EQ("example.com:65535",
  18288. detail::make_host_and_port_string("example.com", 65535, false));
  18289. EXPECT_EQ("example.com:65536",
  18290. detail::make_host_and_port_string("example.com", 65536, false));
  18291. }
  18292. namespace httplib {
  18293. namespace detail {
  18294. std::string
  18295. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18296. const std::string &host, int port);
  18297. } // namespace detail
  18298. } // namespace httplib
  18299. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18300. std::map<std::string, std::string> addr_map = {
  18301. {"ipv4.example", "192.0.2.10"},
  18302. {"ipv6.example", "2001:db8::1"},
  18303. {"name.example", "internal.example.lan"},
  18304. {"empty.example", ""}};
  18305. EXPECT_EQ("192.0.2.10:443",
  18306. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18307. EXPECT_EQ("[2001:db8::1]:443",
  18308. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18309. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18310. addr_map, "name.example", 8443));
  18311. // An empty or absent mapping keeps the hostname as the target
  18312. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18313. addr_map, "empty.example", 443));
  18314. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18315. addr_map, "other.example", 443));
  18316. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18317. }
  18318. #ifdef CPPHTTPLIB_SSL_ENABLED
  18319. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18320. httplib::SSLClient cli("roblox.com", 443);
  18321. cli.set_follow_location(true);
  18322. auto res = cli.Get("/");
  18323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18324. EXPECT_EQ(StatusCode::OK_200, res->status);
  18325. }
  18326. #endif
  18327. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18328. Server svr;
  18329. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18330. EXPECT_EQ(res.status, 400);
  18331. });
  18332. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18333. auto se = detail::scope_exit([&] {
  18334. svr.stop();
  18335. thread.join();
  18336. ASSERT_FALSE(svr.is_running());
  18337. });
  18338. svr.wait_until_ready();
  18339. Client cli(HOST, PORT);
  18340. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18341. }
  18342. TEST(InvalidHeaderCharsTest, is_field_name) {
  18343. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18344. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18345. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18346. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18347. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18348. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18349. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18350. EXPECT_FALSE(detail::fields::is_field_name(""));
  18351. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18352. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18353. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18354. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18355. }
  18356. TEST(InvalidHeaderCharsTest, is_field_value) {
  18357. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18358. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18359. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18360. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18361. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18362. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18363. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18364. EXPECT_TRUE(detail::fields::is_field_value(""));
  18365. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18366. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18367. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18368. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18369. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18370. }
  18371. TEST(InvalidHeaderCharsTest, OnServer) {
  18372. Server svr;
  18373. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18374. std::string header = "Not Set";
  18375. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18376. res.set_header(header, "value");
  18377. res.set_content("Page Content Page Content", "text/plain");
  18378. });
  18379. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18380. std::string header = "Not Set";
  18381. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18382. res.set_header("X-Test", header);
  18383. res.set_content("Page Content Page Content", "text/plain");
  18384. });
  18385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18386. auto se = detail::scope_exit([&] {
  18387. svr.stop();
  18388. thread.join();
  18389. ASSERT_FALSE(svr.is_running());
  18390. });
  18391. svr.wait_until_ready();
  18392. Client cli(HOST, PORT);
  18393. {
  18394. auto res = cli.Get(
  18395. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18397. EXPECT_EQ("Page Content Page Content", res->body);
  18398. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18399. }
  18400. {
  18401. auto res = cli.Get(
  18402. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18404. EXPECT_EQ("Page Content Page Content", res->body);
  18405. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18406. }
  18407. }
  18408. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18409. auto handled = false;
  18410. Server svr;
  18411. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18412. thread t = thread([&] { svr.listen(HOST, PORT); });
  18413. auto se = detail::scope_exit([&] {
  18414. svr.stop();
  18415. t.join();
  18416. ASSERT_FALSE(svr.is_running());
  18417. ASSERT_FALSE(handled);
  18418. });
  18419. svr.wait_until_ready();
  18420. auto req = "POST /test HTTP/1.1\r\n"
  18421. "Content-Length: x\r\n"
  18422. "\r\n";
  18423. std::string response;
  18424. ASSERT_TRUE(send_request(1, req, &response));
  18425. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18426. response.substr(0, response.find("\r\n")));
  18427. }
  18428. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18429. // case-insensitive, and a server that receives a 100-continue expectation in
  18430. // an HTTP/1.0 request MUST ignore it.
  18431. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18432. std::string response;
  18433. ASSERT_TRUE(send_request(1, req, &response, port));
  18434. *got_100 = response.find("100 Continue") != std::string::npos;
  18435. }
  18436. class ExpectTokenTest : public ::testing::Test {
  18437. protected:
  18438. void SetUp() override {
  18439. svr_.Post("/p", [](const Request &, Response &res) {
  18440. res.set_content("ok", "text/plain");
  18441. });
  18442. port_ = svr_.bind_to_any_port(HOST);
  18443. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18444. svr_.wait_until_ready();
  18445. }
  18446. void TearDown() override {
  18447. svr_.stop();
  18448. if (thread_.joinable()) { thread_.join(); }
  18449. }
  18450. std::string request(const char *version, const char *expect_value) const {
  18451. return std::string("POST /p ") + version +
  18452. "\r\n"
  18453. "Host: localhost\r\n"
  18454. "Content-Length: 2\r\n"
  18455. "Connection: close\r\n"
  18456. "Expect: " +
  18457. expect_value +
  18458. "\r\n"
  18459. "\r\n"
  18460. "hi";
  18461. }
  18462. Server svr_;
  18463. int port_ = 0;
  18464. thread thread_;
  18465. };
  18466. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18467. bool got_100 = false;
  18468. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18469. EXPECT_TRUE(got_100);
  18470. }
  18471. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18472. bool got_100 = true;
  18473. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18474. EXPECT_FALSE(got_100);
  18475. }
  18476. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18477. bool got_100 = false;
  18478. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18479. EXPECT_TRUE(got_100);
  18480. }
  18481. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18482. bool got_100 = false;
  18483. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18484. EXPECT_TRUE(got_100);
  18485. }
  18486. // `100 Continue` is sent only when the server starts reading the body, so a
  18487. // request rejected before that never invites the client to send it. The
  18488. // requests below carry the expectation but withhold the body, as a client
  18489. // waiting for `100 Continue` would.
  18490. // A POST that expects `100 Continue` and withholds its two-byte body.
  18491. static std::string expect_headers_only(const std::string &path) {
  18492. return "POST " + path +
  18493. " HTTP/1.1\r\n"
  18494. "Host: localhost\r\n"
  18495. "Content-Length: 2\r\n"
  18496. "Expect: 100-continue\r\n"
  18497. "\r\n";
  18498. }
  18499. class ExpectLazyContinueTest : public ::testing::Test {
  18500. protected:
  18501. void SetUp() override {
  18502. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18503. if (req.path == "/pre-routing") {
  18504. res.status = StatusCode::Unauthorized_401;
  18505. return Server::HandlerResponse::Handled;
  18506. }
  18507. return Server::HandlerResponse::Unhandled;
  18508. });
  18509. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18510. if (req.matched_route == "/pre-request") {
  18511. res.status = StatusCode::Forbidden_403;
  18512. return Server::HandlerResponse::Handled;
  18513. }
  18514. return Server::HandlerResponse::Unhandled;
  18515. });
  18516. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18517. res.set_content("ok", "text/plain");
  18518. });
  18519. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18520. res.set_content("ok", "text/plain");
  18521. });
  18522. svr_.Post("/reader-used", [](const Request &, Response &res,
  18523. const ContentReader &content_reader) {
  18524. std::string body;
  18525. content_reader([&](const char *data, size_t len) {
  18526. body.append(data, len);
  18527. return true;
  18528. });
  18529. res.set_content(body, "text/plain");
  18530. });
  18531. svr_.Post("/reader-unused",
  18532. [](const Request &, Response &res, const ContentReader &) {
  18533. res.set_content("ignored", "text/plain");
  18534. });
  18535. port_ = svr_.bind_to_any_port(HOST);
  18536. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18537. svr_.wait_until_ready();
  18538. }
  18539. void TearDown() override {
  18540. svr_.stop();
  18541. if (thread_.joinable()) { thread_.join(); }
  18542. }
  18543. // Sends `req` and reads until the server closes the connection. Returns
  18544. // false if the read had to wait for the client-side timeout instead.
  18545. bool send_until_closed(const std::string &req, std::string *resp) const {
  18546. auto start = std::chrono::steady_clock::now();
  18547. if (!send_request(3, req, resp, port_)) { return false; }
  18548. auto elapsed = std::chrono::steady_clock::now() - start;
  18549. return elapsed < std::chrono::seconds(2);
  18550. }
  18551. // The final response comes without `100 Continue`, and the server closes
  18552. // the connection since the body may or may not follow.
  18553. void expect_final_without_interim(const std::string &path,
  18554. const char *status_line) const {
  18555. std::string resp;
  18556. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18557. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18558. EXPECT_EQ(0u, resp.find(status_line));
  18559. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18560. }
  18561. Server svr_;
  18562. int port_ = 0;
  18563. thread thread_;
  18564. };
  18565. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18566. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18567. }
  18568. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18569. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18570. }
  18571. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18572. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18573. }
  18574. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18575. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18576. }
  18577. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18578. // The body follows once `100 Continue` has had time to arrive.
  18579. auto req = expect_headers_only("/reader-used");
  18580. req.insert(req.size() - 2, "Connection: close\r\n");
  18581. std::string resp;
  18582. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18583. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18584. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18585. EXPECT_NE(std::string::npos, resp.find("hi"));
  18586. }
  18587. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18588. // Large enough for the client to add `Expect: 100-continue` itself.
  18589. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18590. std::atomic<bool> body_sent{false};
  18591. Client cli(HOST, port_);
  18592. auto res = cli.Post(
  18593. "/pre-request", length,
  18594. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18595. body_sent = true;
  18596. std::string chunk(len, 'x');
  18597. sink.write(chunk.data(), chunk.size());
  18598. return true;
  18599. },
  18600. "application/octet-stream");
  18601. ASSERT_TRUE(res);
  18602. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18603. EXPECT_FALSE(body_sent);
  18604. }
  18605. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18606. Server svr;
  18607. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18608. return StatusCode::ExpectationFailed_417;
  18609. });
  18610. svr.Post("/p", [](const Request &, Response &res) {
  18611. res.set_content("ok", "text/plain");
  18612. });
  18613. auto port = svr.bind_to_any_port(HOST);
  18614. thread t = thread([&] { svr.listen_after_bind(); });
  18615. auto se = detail::scope_exit([&] {
  18616. svr.stop();
  18617. t.join();
  18618. });
  18619. svr.wait_until_ready();
  18620. std::string resp;
  18621. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18622. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18623. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18624. // Exactly one response: the route handler must not run after the 417.
  18625. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18626. }
  18627. #ifndef _WIN32
  18628. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18629. static constexpr char reject[] = "Unauthorized";
  18630. static constexpr char accept[] = "Upload accepted";
  18631. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18632. Server svr;
  18633. svr.set_expect_100_continue_handler(
  18634. [](const Request & /*req*/, Response &res) {
  18635. res.status = StatusCode::Unauthorized_401;
  18636. res.set_content(reject, "text/plain");
  18637. return res.status;
  18638. });
  18639. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18640. res.set_content(accept, "text/plain");
  18641. });
  18642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18643. auto se = detail::scope_exit([&] {
  18644. svr.stop();
  18645. thread.join();
  18646. ASSERT_FALSE(svr.is_running());
  18647. });
  18648. svr.wait_until_ready();
  18649. {
  18650. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18651. curl_easy_init(), &curl_easy_cleanup};
  18652. ASSERT_NE(curl, nullptr);
  18653. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18654. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18655. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18656. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18657. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18658. &curl_slist_free_all};
  18659. ASSERT_NE(list, nullptr);
  18660. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18661. struct read_data {
  18662. uint64_t read_size;
  18663. uint64_t total_size;
  18664. } data = {0, total_size};
  18665. using read_callback_t =
  18666. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18667. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18668. void *userdata) -> size_t {
  18669. read_data *d = (read_data *)userdata;
  18670. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18671. std::fill_n(ptr, size * nmemb, 'A');
  18672. d->read_size += size * nmemb;
  18673. return size * nmemb;
  18674. };
  18675. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18676. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18677. std::vector<char> buffer;
  18678. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18679. using write_callback_t =
  18680. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18681. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18682. void *userdata) -> size_t {
  18683. std::vector<char> *buf = (std::vector<char> *)userdata;
  18684. buf->reserve(buf->size() + size * nmemb + 1);
  18685. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18686. return size * nmemb;
  18687. };
  18688. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18689. {
  18690. const auto res = curl_easy_perform(curl.get());
  18691. ASSERT_EQ(res, CURLE_OK);
  18692. }
  18693. {
  18694. auto response_code = long{};
  18695. const auto res =
  18696. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18697. ASSERT_EQ(res, CURLE_OK);
  18698. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18699. }
  18700. {
  18701. auto dl = curl_off_t{};
  18702. const auto res =
  18703. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18704. ASSERT_EQ(res, CURLE_OK);
  18705. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18706. }
  18707. {
  18708. buffer.push_back('\0');
  18709. ASSERT_STRCASEEQ(buffer.data(), reject);
  18710. }
  18711. }
  18712. }
  18713. #endif
  18714. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18715. // Regression test for #2458.
  18716. //
  18717. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18718. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18719. // ticket can make the client socket spuriously readable during the
  18720. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18721. // the client withholds the body and then blocks reading a response that never
  18722. // comes, failing with `Failed to read connection`.
  18723. //
  18724. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18725. // within the timeout. This raw OpenSSL server deliberately never sends
  18726. // `100 Continue`; the client must still deliver the body and receive 200.
  18727. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18728. signal(SIGPIPE, SIG_IGN);
  18729. const auto port = PORT + 4;
  18730. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18731. ASSERT_NE(srv, INVALID_SOCKET);
  18732. int opt = 1;
  18733. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18734. sockaddr_in addr{};
  18735. addr.sin_family = AF_INET;
  18736. addr.sin_port = htons(static_cast<uint16_t>(port));
  18737. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18738. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18739. ASSERT_EQ(0, ::listen(srv, 1));
  18740. std::atomic<size_t> server_body_bytes{0};
  18741. auto server_thread = std::thread([&] {
  18742. sockaddr_in cli_addr{};
  18743. socklen_t cli_len = sizeof(cli_addr);
  18744. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18745. if (cli == INVALID_SOCKET) { return; }
  18746. // Bound the lifetime of the server side so a buggy client (which never
  18747. // sends the body) cannot make this thread block forever on join.
  18748. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18749. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18750. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18751. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18752. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18753. SSL *ssl = SSL_new(ctx);
  18754. SSL_set_fd(ssl, static_cast<int>(cli));
  18755. if (SSL_accept(ssl) > 0) {
  18756. // Read the request headers. Reading here also flushes the TLS 1.3
  18757. // session tickets to the client. Deliberately do NOT send
  18758. // `100 Continue`.
  18759. std::string buf;
  18760. char tmp[1024];
  18761. while (buf.find("\r\n\r\n") == std::string::npos) {
  18762. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18763. if (n <= 0) { break; }
  18764. buf.append(tmp, static_cast<size_t>(n));
  18765. }
  18766. // A correct client sends the body now; count what arrives.
  18767. auto pos = buf.find("\r\n\r\n");
  18768. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18769. while (body < 4096) {
  18770. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18771. if (n <= 0) { break; }
  18772. body += static_cast<size_t>(n);
  18773. }
  18774. server_body_bytes = body;
  18775. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18776. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18777. SSL_shutdown(ssl);
  18778. }
  18779. SSL_free(ssl);
  18780. detail::close_socket(cli);
  18781. SSL_CTX_free(ctx);
  18782. });
  18783. auto se = detail::scope_exit([&] {
  18784. server_thread.join();
  18785. detail::close_socket(srv);
  18786. });
  18787. SSLClient cli("127.0.0.1", port);
  18788. cli.enable_server_certificate_verification(false);
  18789. cli.set_connection_timeout(5, 0);
  18790. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18791. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18792. std::string body(4096, 'A');
  18793. auto res = cli.Put("/api/test", body, "application/json");
  18794. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18795. EXPECT_EQ(StatusCode::OK_200, res->status);
  18796. EXPECT_EQ(body.size(), server_body_bytes.load());
  18797. }
  18798. #endif
  18799. template <typename S, typename C>
  18800. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18801. svr.Get("/stream", [&](const Request &, Response &res) {
  18802. auto data = new std::string("01234567890123456789");
  18803. res.set_content_provider(
  18804. data->size(), "text/plain",
  18805. [&, data](size_t offset, size_t length, DataSink &sink) {
  18806. const size_t DATA_CHUNK_SIZE = 4;
  18807. const auto &d = *data;
  18808. std::this_thread::sleep_for(std::chrono::seconds(1));
  18809. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18810. return true;
  18811. },
  18812. [data](bool success) {
  18813. EXPECT_FALSE(success);
  18814. delete data;
  18815. });
  18816. });
  18817. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18818. auto i = new size_t(0);
  18819. res.set_content_provider(
  18820. "text/plain",
  18821. [i](size_t, DataSink &sink) {
  18822. if (*i < 5) {
  18823. std::this_thread::sleep_for(std::chrono::seconds(1));
  18824. sink.write("abcd", 4);
  18825. (*i)++;
  18826. } else {
  18827. sink.done();
  18828. }
  18829. return true;
  18830. },
  18831. [i](bool success) {
  18832. EXPECT_FALSE(success);
  18833. delete i;
  18834. });
  18835. });
  18836. svr.Get("/chunked", [&](const Request &, Response &res) {
  18837. auto i = new size_t(0);
  18838. res.set_chunked_content_provider(
  18839. "text/plain",
  18840. [i](size_t, DataSink &sink) {
  18841. if (*i < 5) {
  18842. std::this_thread::sleep_for(std::chrono::seconds(1));
  18843. sink.os << "abcd";
  18844. (*i)++;
  18845. } else {
  18846. sink.done();
  18847. }
  18848. return true;
  18849. },
  18850. [i](bool success) {
  18851. EXPECT_FALSE(success);
  18852. delete i;
  18853. });
  18854. });
  18855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18856. auto se = detail::scope_exit([&] {
  18857. svr.stop();
  18858. listen_thread.join();
  18859. ASSERT_FALSE(svr.is_running());
  18860. });
  18861. svr.wait_until_ready();
  18862. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18863. {
  18864. auto start = std::chrono::steady_clock::now();
  18865. auto res = cli.Get("/stream");
  18866. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18867. std::chrono::steady_clock::now() - start)
  18868. .count();
  18869. ASSERT_FALSE(res);
  18870. EXPECT_EQ(Error::Read, res.error());
  18871. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18872. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18873. }
  18874. {
  18875. auto start = std::chrono::steady_clock::now();
  18876. auto res = cli.Get("/stream_without_length");
  18877. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18878. std::chrono::steady_clock::now() - start)
  18879. .count();
  18880. ASSERT_FALSE(res);
  18881. EXPECT_EQ(Error::Read, res.error());
  18882. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18883. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18884. }
  18885. {
  18886. auto start = std::chrono::steady_clock::now();
  18887. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18888. EXPECT_EQ("abcd", string(data, data_length));
  18889. return true;
  18890. });
  18891. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18892. std::chrono::steady_clock::now() - start)
  18893. .count();
  18894. ASSERT_FALSE(res);
  18895. EXPECT_EQ(Error::Read, res.error());
  18896. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18897. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18898. }
  18899. }
  18900. TEST(MaxTimeoutTest, ContentStream) {
  18901. time_t timeout = 2000;
  18902. time_t threshold = 200;
  18903. Server svr;
  18904. Client cli("localhost", PORT);
  18905. max_timeout_test(svr, cli, timeout, threshold);
  18906. }
  18907. #ifdef CPPHTTPLIB_SSL_ENABLED
  18908. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18909. time_t timeout = 2000;
  18910. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18912. SSLClient cli("localhost", PORT);
  18913. cli.enable_server_certificate_verification(false);
  18914. max_timeout_test(svr, cli, timeout, threshold);
  18915. }
  18916. #endif
  18917. class EventDispatcher {
  18918. public:
  18919. EventDispatcher() {}
  18920. bool wait_event(DataSink *sink) {
  18921. unique_lock<mutex> lk(m_);
  18922. int id = id_;
  18923. // Wait with timeout to prevent hanging if client disconnects
  18924. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18925. [&] { return cid_ == id; })) {
  18926. return false; // Timeout occurred
  18927. }
  18928. sink->write(message_.data(), message_.size());
  18929. return true;
  18930. }
  18931. void send_event(const string &message) {
  18932. lock_guard<mutex> lk(m_);
  18933. cid_ = id_++;
  18934. message_ = message;
  18935. cv_.notify_all();
  18936. }
  18937. private:
  18938. mutex m_;
  18939. condition_variable cv_;
  18940. atomic_int id_{0};
  18941. atomic_int cid_{-1};
  18942. string message_;
  18943. };
  18944. TEST(ClientInThreadTest, Issue2068) {
  18945. EventDispatcher ed;
  18946. Server svr;
  18947. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18948. res.set_chunked_content_provider("text/event-stream",
  18949. [&](size_t /*offset*/, DataSink &sink) {
  18950. return ed.wait_event(&sink);
  18951. });
  18952. });
  18953. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18954. svr.wait_until_ready();
  18955. thread event_thread([&] {
  18956. int id = 0;
  18957. while (svr.is_running()) {
  18958. this_thread::sleep_for(chrono::milliseconds(500));
  18959. std::stringstream ss;
  18960. ss << "data: " << id << "\n\n";
  18961. ed.send_event(ss.str());
  18962. id++;
  18963. }
  18964. });
  18965. auto se = detail::scope_exit([&] {
  18966. svr.stop();
  18967. listen_thread.join();
  18968. event_thread.join();
  18969. ASSERT_FALSE(svr.is_running());
  18970. });
  18971. {
  18972. auto client = detail::make_unique<Client>(HOST, PORT);
  18973. client->set_read_timeout(std::chrono::minutes(10));
  18974. std::atomic<bool> stop{false};
  18975. std::thread t([&] {
  18976. client->Get("/event1",
  18977. [&](const char *, size_t) -> bool { return !stop; });
  18978. });
  18979. std::this_thread::sleep_for(std::chrono::seconds(2));
  18980. stop = true;
  18981. client->stop();
  18982. t.join();
  18983. // Reset client after thread has finished
  18984. client.reset();
  18985. }
  18986. }
  18987. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18988. auto handled = false;
  18989. Server svr;
  18990. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18992. auto se = detail::scope_exit([&] {
  18993. svr.stop();
  18994. t.join();
  18995. ASSERT_FALSE(svr.is_running());
  18996. ASSERT_FALSE(handled);
  18997. });
  18998. svr.wait_until_ready();
  18999. // Two Content-Length headers with different values — must be rejected
  19000. auto req = "POST /test HTTP/1.1\r\n"
  19001. "Content-Length: 5\r\n"
  19002. "Content-Length: 10\r\n"
  19003. "\r\n"
  19004. "hello";
  19005. std::string response;
  19006. ASSERT_TRUE(send_request(1, req, &response));
  19007. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19008. response.substr(0, response.find("\r\n")));
  19009. }
  19010. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19011. auto handled = false;
  19012. Server svr;
  19013. svr.Post("/test", [&](const Request &, Response &res) {
  19014. handled = true;
  19015. res.set_content("ok", "text/plain");
  19016. });
  19017. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19018. auto se = detail::scope_exit([&] {
  19019. svr.stop();
  19020. t.join();
  19021. ASSERT_FALSE(svr.is_running());
  19022. ASSERT_TRUE(handled);
  19023. });
  19024. svr.wait_until_ready();
  19025. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19026. auto req = "POST /test HTTP/1.1\r\n"
  19027. "Host: localhost\r\n"
  19028. "Content-Length: 5\r\n"
  19029. "Content-Length: 5\r\n"
  19030. "\r\n"
  19031. "hello";
  19032. std::string response;
  19033. ASSERT_TRUE(send_request(1, req, &response));
  19034. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19035. }
  19036. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19037. Server svr;
  19038. svr.Get("/test", [](const Request &, Response &res) {
  19039. res.set_content("ok", "text/plain");
  19040. });
  19041. auto port = svr.bind_to_any_port(HOST);
  19042. thread t = thread([&] { svr.listen_after_bind(); });
  19043. auto se = detail::scope_exit([&] {
  19044. svr.stop();
  19045. t.join();
  19046. ASSERT_FALSE(svr.is_running());
  19047. });
  19048. svr.wait_until_ready();
  19049. auto status_line = [&](const std::string &host_lines) {
  19050. std::string res;
  19051. send_request(
  19052. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19053. &res, port);
  19054. return res.substr(0, res.find("\r\n"));
  19055. };
  19056. const char *accepted[] = {
  19057. "Host: localhost\r\n",
  19058. "Host: a.example:8080\r\n",
  19059. "Host: my_service\r\n",
  19060. "Host: [::1]:8080\r\n",
  19061. "Host: [fe80::1%25eth0]\r\n",
  19062. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19063. };
  19064. for (auto host_lines : accepted) {
  19065. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19066. }
  19067. const char *rejected[] = {
  19068. "Host: a.example\r\nHost: b.example\r\n",
  19069. "Host: a.example\r\nHost: a.example\r\n",
  19070. "Host: a@b.example\r\n",
  19071. "Host: a.example/b\r\n",
  19072. "Host: a.example\\b\r\n",
  19073. "Host: a.example?b\r\n",
  19074. "Host: a.example#b\r\n",
  19075. "Host: a.example b.example\r\n",
  19076. };
  19077. for (auto host_lines : rejected) {
  19078. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19079. << host_lines;
  19080. }
  19081. }
  19082. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19083. Server svr;
  19084. svr.Get("/", [](const Request &req, Response &res) {
  19085. EXPECT_EQ(2U, req.trailers.size());
  19086. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19087. // Denied
  19088. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19089. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19090. // Accepted
  19091. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19092. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19093. EXPECT_TRUE(req.has_trailer("X-World"));
  19094. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19095. res.set_content("ok", "text/plain");
  19096. });
  19097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19098. auto se = detail::scope_exit([&] {
  19099. svr.stop();
  19100. t.join();
  19101. ASSERT_FALSE(svr.is_running());
  19102. });
  19103. svr.wait_until_ready();
  19104. const std::string req = "GET / HTTP/1.1\r\n"
  19105. "Transfer-Encoding: chunked\r\n"
  19106. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19107. "\r\n"
  19108. "0\r\n"
  19109. "Content-Length: 10\r\n"
  19110. "Host: internal.local\r\n"
  19111. "Content-Type: malicious/content\r\n"
  19112. "Cookie: any\r\n"
  19113. "Set-Cookie: any\r\n"
  19114. "X-Forwarded-For: attacker.com\r\n"
  19115. "X-Real-Ip: 1.1.1.1\r\n"
  19116. "X-Hello: hello\r\n"
  19117. "X-World: world\r\n"
  19118. "\r\n";
  19119. std::string res;
  19120. ASSERT_TRUE(send_request(1, req, &res));
  19121. }
  19122. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19123. // several field lines, and the combined value is what has to be parsed. A
  19124. // Trailer field split across lines therefore declares every name it lists;
  19125. // reading only the first line silently drops the trailers the later lines
  19126. // declare. The prohibited-trailer filter still applies to every line.
  19127. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19128. Server svr;
  19129. size_t observed_trailer_count = 0;
  19130. std::string observed_hello;
  19131. std::string observed_world;
  19132. bool observed_content_length = true;
  19133. svr.Get("/", [&](const Request &req, Response &res) {
  19134. observed_trailer_count = req.trailers.size();
  19135. observed_hello = req.get_trailer_value("X-Hello");
  19136. observed_world = req.get_trailer_value("X-World");
  19137. observed_content_length = req.has_trailer("Content-Length");
  19138. res.set_content("ok", "text/plain");
  19139. });
  19140. auto port = svr.bind_to_any_port(HOST);
  19141. thread t = thread([&]() { svr.listen_after_bind(); });
  19142. auto se = detail::scope_exit([&] {
  19143. svr.stop();
  19144. t.join();
  19145. ASSERT_FALSE(svr.is_running());
  19146. });
  19147. svr.wait_until_ready();
  19148. const std::string req = "GET / HTTP/1.1\r\n"
  19149. "Host: localhost\r\n"
  19150. "Transfer-Encoding: chunked\r\n"
  19151. "Trailer: X-Hello\r\n"
  19152. "Trailer: X-World, Content-Length\r\n"
  19153. "\r\n"
  19154. "0\r\n"
  19155. "X-Hello: hello\r\n"
  19156. "X-World: world\r\n"
  19157. "Content-Length: 10\r\n"
  19158. "\r\n";
  19159. std::string res;
  19160. ASSERT_TRUE(send_request(1, req, &res, port));
  19161. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19162. // Accepted: both field lines contribute to the declared set
  19163. EXPECT_EQ(2U, observed_trailer_count);
  19164. EXPECT_EQ(observed_hello, "hello");
  19165. EXPECT_EQ(observed_world, "world");
  19166. // Denied: a prohibited name stays prohibited on a later field line
  19167. EXPECT_FALSE(observed_content_length);
  19168. }
  19169. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19170. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19171. // unbounded run of fields that are never declared, because the counter would
  19172. // only advance for declared fields.
  19173. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19174. Server svr;
  19175. bool handler_called = false;
  19176. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19177. handler_called = true;
  19178. res.set_content("ok", "text/plain");
  19179. });
  19180. auto port = svr.bind_to_any_port(HOST);
  19181. thread t = thread([&]() { svr.listen_after_bind(); });
  19182. auto se = detail::scope_exit([&] {
  19183. svr.stop();
  19184. t.join();
  19185. ASSERT_FALSE(svr.is_running());
  19186. });
  19187. svr.wait_until_ready();
  19188. // Declare nothing, then send far more undeclared trailer fields than the
  19189. // header-count limit. Parsing must stop and reject the request rather than
  19190. // read every line.
  19191. std::string req = "GET / HTTP/1.1\r\n"
  19192. "Transfer-Encoding: chunked\r\n"
  19193. "\r\n"
  19194. "0\r\n";
  19195. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19196. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19197. }
  19198. req += "\r\n";
  19199. std::string res;
  19200. ASSERT_TRUE(send_request(1, req, &res, port));
  19201. // The request is rejected before the handler runs.
  19202. EXPECT_FALSE(handler_called);
  19203. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19204. }
  19205. // The set of declared trailer names is capped so a peer cannot grow it without
  19206. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19207. // declared past the cap is not honored, even if the field is actually sent.
  19208. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19209. Server svr;
  19210. // One name inside the cap and one past it, so the test tracks the cap rather
  19211. // than a fixed count.
  19212. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19213. const std::string within_cap_name = "X-T-0";
  19214. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19215. bool observed_within_cap = false;
  19216. bool observed_past_cap = false;
  19217. svr.Get("/", [&](const Request &req, Response &res) {
  19218. observed_within_cap = req.has_trailer(within_cap_name);
  19219. observed_past_cap = req.has_trailer(past_cap_name);
  19220. res.set_content("ok", "text/plain");
  19221. });
  19222. auto port = svr.bind_to_any_port(HOST);
  19223. thread t = thread([&]() { svr.listen_after_bind(); });
  19224. auto se = detail::scope_exit([&] {
  19225. svr.stop();
  19226. t.join();
  19227. ASSERT_FALSE(svr.is_running());
  19228. });
  19229. svr.wait_until_ready();
  19230. // Declare more trailer names than the cap in a single Trailer field, then
  19231. // actually send the first (within the cap) and the last (past it).
  19232. std::string trailer_decl = "Trailer: ";
  19233. for (int i = 0; i < declared_count; i++) {
  19234. if (i != 0) { trailer_decl += ", "; }
  19235. trailer_decl += "X-T-" + std::to_string(i);
  19236. }
  19237. trailer_decl += "\r\n";
  19238. const std::string req = "GET / HTTP/1.1\r\n"
  19239. "Host: localhost\r\n"
  19240. "Transfer-Encoding: chunked\r\n" +
  19241. trailer_decl +
  19242. "\r\n"
  19243. "0\r\n" +
  19244. within_cap_name + ": a\r\n" + past_cap_name +
  19245. ": b\r\n"
  19246. "\r\n";
  19247. std::string res;
  19248. ASSERT_TRUE(send_request(1, req, &res, port));
  19249. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19250. // A name within the cap is honored; one declared past the cap is dropped.
  19251. EXPECT_TRUE(observed_within_cap);
  19252. EXPECT_FALSE(observed_past_cap);
  19253. }
  19254. // A direct client that is not listed in trusted_proxies must not be able to
  19255. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19256. // the peer address on the actual TCP connection determines whether the
  19257. // header is honored.
  19258. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19259. Server svr;
  19260. // Deliberately does NOT include the loopback address the test client
  19261. // actually connects from, so the direct connection is not a trusted proxy.
  19262. svr.set_trusted_proxies({"203.0.113.66"});
  19263. std::string observed_remote_addr;
  19264. svr.Get("/ip", [&](const Request &req, Response &res) {
  19265. observed_remote_addr = req.remote_addr;
  19266. res.set_content("ok", "text/plain");
  19267. });
  19268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19269. auto se = detail::scope_exit([&] {
  19270. svr.stop();
  19271. t.join();
  19272. ASSERT_FALSE(svr.is_running());
  19273. });
  19274. svr.wait_until_ready();
  19275. Client cli(HOST, PORT);
  19276. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19278. EXPECT_EQ(StatusCode::OK_200, res->status);
  19279. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19280. // ignored entirely and the real connection-level address retained.
  19281. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19282. observed_remote_addr == "127.0.0.1");
  19283. }
  19284. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19285. Server svr;
  19286. std::string observed_remote_addr;
  19287. std::string observed_xff;
  19288. svr.Get("/ip", [&](const Request &req, Response &res) {
  19289. observed_remote_addr = req.remote_addr;
  19290. observed_xff = req.get_header_value("X-Forwarded-For");
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19294. auto se = detail::scope_exit([&] {
  19295. svr.stop();
  19296. t.join();
  19297. ASSERT_FALSE(svr.is_running());
  19298. });
  19299. svr.wait_until_ready();
  19300. Client cli(HOST, PORT);
  19301. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19303. EXPECT_EQ(StatusCode::OK_200, res->status);
  19304. EXPECT_EQ(observed_xff, "203.0.113.66");
  19305. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19306. observed_remote_addr == "127.0.0.1");
  19307. }
  19308. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19309. Server svr;
  19310. svr.set_trusted_proxies({"203.0.113.66"});
  19311. std::string observed_remote_addr;
  19312. std::string observed_xff;
  19313. svr.Get("/ip", [&](const Request &req, Response &res) {
  19314. observed_remote_addr = req.remote_addr;
  19315. observed_xff = req.get_header_value("X-Forwarded-For");
  19316. res.set_content("ok", "text/plain");
  19317. });
  19318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19319. auto se = detail::scope_exit([&] {
  19320. svr.stop();
  19321. t.join();
  19322. ASSERT_FALSE(svr.is_running());
  19323. });
  19324. svr.wait_until_ready();
  19325. Client cli(HOST, PORT);
  19326. auto res = cli.Get("/ip");
  19327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19328. EXPECT_EQ(StatusCode::OK_200, res->status);
  19329. EXPECT_EQ(observed_xff, "");
  19330. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19331. observed_remote_addr == "127.0.0.1");
  19332. }
  19333. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19334. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19335. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19336. Server svr;
  19337. svr.set_trusted_proxies({"127.0.0.1"});
  19338. svr.Get("/ip", [](const Request &req, Response &res) {
  19339. res.set_content(req.remote_addr, "text/plain");
  19340. });
  19341. auto port = svr.bind_to_any_port("::");
  19342. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19343. thread t = thread([&] { svr.listen_after_bind(); });
  19344. auto se = detail::scope_exit([&] {
  19345. svr.stop();
  19346. t.join();
  19347. ASSERT_FALSE(svr.is_running());
  19348. });
  19349. svr.wait_until_ready();
  19350. Client cli("127.0.0.1", port);
  19351. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19353. EXPECT_EQ("198.51.100.23", res->body);
  19354. }
  19355. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19356. Server svr;
  19357. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19358. svr.Get("/ip", [](const Request &req, Response &res) {
  19359. res.set_content(req.remote_addr, "text/plain");
  19360. });
  19361. auto port = svr.bind_to_any_port(HOST);
  19362. ASSERT_GT(port, 0);
  19363. thread t = thread([&] { svr.listen_after_bind(); });
  19364. auto se = detail::scope_exit([&] {
  19365. svr.stop();
  19366. t.join();
  19367. ASSERT_FALSE(svr.is_running());
  19368. });
  19369. svr.wait_until_ready();
  19370. Client cli(HOST, port);
  19371. auto res = cli.Get(
  19372. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19374. EXPECT_EQ("198.51.100.23", res->body);
  19375. }
  19376. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19377. Server svr;
  19378. // Include the loopback address the test client actually connects from, so
  19379. // the direct connection itself is recognized as the trusted proxy hop.
  19380. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19381. std::string observed_remote_addr;
  19382. std::string observed_xff;
  19383. svr.Get("/ip", [&](const Request &req, Response &res) {
  19384. observed_remote_addr = req.remote_addr;
  19385. observed_xff = req.get_header_value("X-Forwarded-For");
  19386. res.set_content("ok", "text/plain");
  19387. });
  19388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19389. auto se = detail::scope_exit([&] {
  19390. svr.stop();
  19391. t.join();
  19392. ASSERT_FALSE(svr.is_running());
  19393. });
  19394. svr.wait_until_ready();
  19395. Client cli(HOST, PORT);
  19396. auto res = cli.Get(
  19397. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19399. EXPECT_EQ(StatusCode::OK_200, res->status);
  19400. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19401. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19402. }
  19403. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19404. Server svr;
  19405. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19406. std::string observed_remote_addr;
  19407. std::string observed_xff;
  19408. svr.Get("/ip", [&](const Request &req, Response &res) {
  19409. observed_remote_addr = req.remote_addr;
  19410. observed_xff = req.get_header_value("X-Forwarded-For");
  19411. res.set_content("ok", "text/plain");
  19412. });
  19413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19414. auto se = detail::scope_exit([&] {
  19415. svr.stop();
  19416. t.join();
  19417. ASSERT_FALSE(svr.is_running());
  19418. });
  19419. svr.wait_until_ready();
  19420. Client cli(HOST, PORT);
  19421. auto res = cli.Get(
  19422. "/ip",
  19423. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19425. EXPECT_EQ(StatusCode::OK_200, res->status);
  19426. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19427. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19428. }
  19429. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19430. Server svr;
  19431. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19432. std::string observed_remote_addr;
  19433. std::string observed_xff;
  19434. svr.Get("/ip", [&](const Request &req, Response &res) {
  19435. observed_remote_addr = req.remote_addr;
  19436. observed_xff = req.get_header_value("X-Forwarded-For");
  19437. res.set_content("ok", "text/plain");
  19438. });
  19439. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19440. auto se = detail::scope_exit([&] {
  19441. svr.stop();
  19442. t.join();
  19443. ASSERT_FALSE(svr.is_running());
  19444. });
  19445. svr.wait_until_ready();
  19446. Client cli(HOST, PORT);
  19447. auto res = cli.Get(
  19448. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19450. EXPECT_EQ(StatusCode::OK_200, res->status);
  19451. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19452. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19453. // and must not be selected.
  19454. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19455. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19456. }
  19457. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19458. Server svr;
  19459. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19460. std::string observed_remote_addr;
  19461. svr.Get("/ip", [&](const Request &req, Response &res) {
  19462. observed_remote_addr = req.remote_addr;
  19463. res.set_content("ok", "text/plain");
  19464. });
  19465. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19466. auto se = detail::scope_exit([&] {
  19467. svr.stop();
  19468. t.join();
  19469. ASSERT_FALSE(svr.is_running());
  19470. });
  19471. svr.wait_until_ready();
  19472. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19473. // a forged address and the trusted proxy's own address; the forged value must
  19474. // not win over the address the trusted proxy actually recorded.
  19475. Client cli(HOST, PORT);
  19476. auto res = cli.Get(
  19477. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19479. EXPECT_EQ(StatusCode::OK_200, res->status);
  19480. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19481. }
  19482. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19483. Server svr;
  19484. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19485. std::string observed_remote_addr;
  19486. std::string observed_xff;
  19487. svr.Get("/ip", [&](const Request &req, Response &res) {
  19488. observed_remote_addr = req.remote_addr;
  19489. observed_xff = req.get_header_value("X-Forwarded-For");
  19490. res.set_content("ok", "text/plain");
  19491. });
  19492. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19493. auto se = detail::scope_exit([&] {
  19494. svr.stop();
  19495. t.join();
  19496. ASSERT_FALSE(svr.is_running());
  19497. });
  19498. svr.wait_until_ready();
  19499. Client cli(HOST, PORT);
  19500. auto res = cli.Get(
  19501. "/ip",
  19502. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19504. EXPECT_EQ(StatusCode::OK_200, res->status);
  19505. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19506. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19507. }
  19508. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19509. Server svr;
  19510. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19511. std::string observed_remote_addr;
  19512. std::string observed_xff;
  19513. svr.Get("/ip", [&](const Request &req, Response &res) {
  19514. observed_remote_addr = req.remote_addr;
  19515. observed_xff = req.get_header_value("X-Forwarded-For");
  19516. res.set_content("ok", "text/plain");
  19517. });
  19518. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19519. auto se = detail::scope_exit([&] {
  19520. svr.stop();
  19521. t.join();
  19522. ASSERT_FALSE(svr.is_running());
  19523. });
  19524. svr.wait_until_ready();
  19525. std::string raw_req =
  19526. "GET /ip HTTP/1.1\r\n"
  19527. "Host: localhost\r\n"
  19528. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19529. "Connection: close\r\n"
  19530. "\r\n";
  19531. std::string out;
  19532. ASSERT_TRUE(send_request(5, raw_req, &out));
  19533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19534. // Header parser trims surrounding whitespace of the header value
  19535. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19536. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19537. }
  19538. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19539. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19540. // their own X-Forwarded-For as a separate field line rather than extending the
  19541. // one the client sent, so every occurrence has to be taken into account.
  19542. // Reading only the first one hands back the address the client chose.
  19543. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19544. Server svr;
  19545. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19546. std::string observed_remote_addr;
  19547. size_t observed_xff_count = 0;
  19548. svr.Get("/ip", [&](const Request &req, Response &res) {
  19549. observed_remote_addr = req.remote_addr;
  19550. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19551. res.set_content("ok", "text/plain");
  19552. });
  19553. auto port = svr.bind_to_any_port(HOST);
  19554. thread t = thread([&]() { svr.listen_after_bind(); });
  19555. auto se = detail::scope_exit([&] {
  19556. svr.stop();
  19557. t.join();
  19558. ASSERT_FALSE(svr.is_running());
  19559. });
  19560. svr.wait_until_ready();
  19561. // The client supplies the first field line; the trusted proxy appends the
  19562. // address it observed as a second one.
  19563. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19564. "Host: localhost\r\n"
  19565. "X-Forwarded-For: 1.2.3.4\r\n"
  19566. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19567. "Connection: close\r\n"
  19568. "\r\n";
  19569. std::string out;
  19570. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19571. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19572. EXPECT_EQ(observed_xff_count, 2U);
  19573. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19574. // The same chain spread over one field line per hop derives the same client
  19575. // address, i.e. the split and the comma-joined representations agree.
  19576. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19577. "Host: localhost\r\n"
  19578. "X-Forwarded-For: 1.2.3.4\r\n"
  19579. "X-Forwarded-For: 198.51.100.23\r\n"
  19580. "X-Forwarded-For: 192.0.2.45\r\n"
  19581. "Connection: close\r\n"
  19582. "\r\n";
  19583. out.clear();
  19584. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19585. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19586. EXPECT_EQ(observed_xff_count, 3U);
  19587. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19588. }
  19589. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19590. // crash the server (it used to call front() on an empty vector inside
  19591. // get_client_ip). The connection-level remote address must be retained instead.
  19592. static void run_malformed_xff_test(const std::string &xff_value) {
  19593. Server svr;
  19594. svr.set_trusted_proxies({"192.0.2.45"});
  19595. std::string observed_remote_addr;
  19596. svr.Get("/ip", [&](const Request &req, Response &res) {
  19597. observed_remote_addr = req.remote_addr;
  19598. res.set_content("ok", "text/plain");
  19599. });
  19600. int port = 0;
  19601. thread t = thread([&]() {
  19602. port = svr.bind_to_any_port(HOST);
  19603. svr.listen_after_bind();
  19604. });
  19605. auto se = detail::scope_exit([&] {
  19606. svr.stop();
  19607. t.join();
  19608. ASSERT_FALSE(svr.is_running());
  19609. });
  19610. svr.wait_until_ready();
  19611. Client cli(HOST, port);
  19612. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19614. EXPECT_EQ(StatusCode::OK_200, res->status);
  19615. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19616. observed_remote_addr == "127.0.0.1");
  19617. }
  19618. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19619. run_malformed_xff_test("");
  19620. }
  19621. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19622. run_malformed_xff_test(",");
  19623. }
  19624. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19625. run_malformed_xff_test(", , ,");
  19626. }
  19627. // The same rule applies to Accept: a request whose acceptable types are spread
  19628. // over several field lines must be negotiated against all of them.
  19629. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19630. // case-insensitive connection options. Comparing the whole field value against
  19631. // one option misses a client that sends several of them, and misses every
  19632. // casing but the one written in the comparison.
  19633. //
  19634. // Sends req, reads the response, then reuses the same socket for a second
  19635. // request to find out whether the server kept the connection.
  19636. static void probe_connection_reuse(int port, const std::string &req,
  19637. bool *announced_close, bool *reusable) {
  19638. auto error = Error::Success;
  19639. auto sock = detail::create_client_socket(
  19640. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19641. /*connection_timeout_sec=*/5, 0,
  19642. /*read_timeout_sec=*/1, 0,
  19643. /*write_timeout_sec=*/5, 0, std::string(), error);
  19644. ASSERT_NE(sock, INVALID_SOCKET);
  19645. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19646. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19647. "Host: localhost\r\n"
  19648. "Connection: close\r\n"
  19649. "\r\n";
  19650. std::string first_response;
  19651. std::string second_response;
  19652. detail::process_client_socket(
  19653. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19654. [&](Stream &strm) {
  19655. if (strm.write(req.data(), req.size()) !=
  19656. static_cast<ssize_t>(req.size())) {
  19657. return false;
  19658. }
  19659. char buf[512];
  19660. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19661. // Headers plus the two-byte body of the handler below
  19662. while (reader.getline()) {
  19663. first_response += reader.ptr();
  19664. if (first_response.find("ok") != std::string::npos) { break; }
  19665. }
  19666. if (strm.write(second.data(), second.size()) !=
  19667. static_cast<ssize_t>(second.size())) {
  19668. return true;
  19669. }
  19670. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19671. while (reader2.getline()) {
  19672. second_response += reader2.ptr();
  19673. if (second_response.find("ok") != std::string::npos) { break; }
  19674. }
  19675. return true;
  19676. });
  19677. *announced_close =
  19678. first_response.find("Connection: close") != std::string::npos;
  19679. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19680. }
  19681. class ConnectionTokenTest : public ::testing::Test {
  19682. protected:
  19683. void SetUp() override {
  19684. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19685. res.set_content("ok", "text/plain");
  19686. });
  19687. port_ = svr_.bind_to_any_port(HOST);
  19688. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19689. svr_.wait_until_ready();
  19690. }
  19691. void TearDown() override {
  19692. svr_.stop();
  19693. if (thread_.joinable()) { thread_.join(); }
  19694. }
  19695. Server svr_;
  19696. int port_ = 0;
  19697. thread thread_;
  19698. };
  19699. // "close" alongside another option still closes the connection, and the
  19700. // response says so rather than leaving the peer to discover it.
  19701. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19702. bool announced_close = false;
  19703. bool reusable = true;
  19704. probe_connection_reuse(port_,
  19705. "GET /keepalive HTTP/1.1\r\n"
  19706. "Host: localhost\r\n"
  19707. "Connection: keep-alive, close\r\n"
  19708. "\r\n",
  19709. &announced_close, &reusable);
  19710. EXPECT_TRUE(announced_close);
  19711. EXPECT_FALSE(reusable);
  19712. }
  19713. // "close" split over two field lines is the same list, so it is honored too.
  19714. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19715. bool announced_close = false;
  19716. bool reusable = true;
  19717. probe_connection_reuse(port_,
  19718. "GET /keepalive HTTP/1.1\r\n"
  19719. "Host: localhost\r\n"
  19720. "Connection: keep-alive\r\n"
  19721. "Connection: close\r\n"
  19722. "\r\n",
  19723. &announced_close, &reusable);
  19724. EXPECT_TRUE(announced_close);
  19725. EXPECT_FALSE(reusable);
  19726. }
  19727. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19728. // keep-alive in the spelling everyone actually sends keeps its connection.
  19729. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19730. bool announced_close = false;
  19731. bool reusable = false;
  19732. probe_connection_reuse(port_,
  19733. "GET /keepalive HTTP/1.0\r\n"
  19734. "Host: localhost\r\n"
  19735. "Connection: keep-alive\r\n"
  19736. "\r\n",
  19737. &announced_close, &reusable);
  19738. EXPECT_FALSE(announced_close);
  19739. EXPECT_TRUE(reusable);
  19740. }
  19741. // A token the value merely contains is not the token itself.
  19742. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19743. bool announced_close = false;
  19744. bool reusable = false;
  19745. probe_connection_reuse(port_,
  19746. "GET /keepalive HTTP/1.1\r\n"
  19747. "Host: localhost\r\n"
  19748. "Connection: notclose\r\n"
  19749. "\r\n",
  19750. &announced_close, &reusable);
  19751. EXPECT_FALSE(announced_close);
  19752. EXPECT_TRUE(reusable);
  19753. }
  19754. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19755. Server svr;
  19756. std::vector<std::string> observed_types;
  19757. svr.Get("/", [&](const Request &req, Response &res) {
  19758. observed_types = req.accept_content_types;
  19759. res.set_content("ok", "text/plain");
  19760. });
  19761. auto port = svr.bind_to_any_port(HOST);
  19762. thread t = thread([&]() { svr.listen_after_bind(); });
  19763. auto se = detail::scope_exit([&] {
  19764. svr.stop();
  19765. t.join();
  19766. ASSERT_FALSE(svr.is_running());
  19767. });
  19768. svr.wait_until_ready();
  19769. Client cli(HOST, port);
  19770. Headers headers;
  19771. headers.emplace("Accept", "text/plain;q=0.5");
  19772. headers.emplace("Accept", "application/json");
  19773. auto res = cli.Get("/", headers);
  19774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19775. EXPECT_EQ(StatusCode::OK_200, res->status);
  19776. // Sorted by q-value, so the second field line's type comes first
  19777. ASSERT_EQ(2U, observed_types.size());
  19778. EXPECT_EQ("application/json", observed_types[0]);
  19779. EXPECT_EQ("text/plain", observed_types[1]);
  19780. }
  19781. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19782. // empty field line must not contribute a bare comma to the combined value.
  19783. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19784. Server svr;
  19785. std::vector<std::string> observed_types;
  19786. svr.Get("/", [&](const Request &req, Response &res) {
  19787. observed_types = req.accept_content_types;
  19788. res.set_content("ok", "text/plain");
  19789. });
  19790. auto port = svr.bind_to_any_port(HOST);
  19791. thread t = thread([&]() { svr.listen_after_bind(); });
  19792. auto se = detail::scope_exit([&] {
  19793. svr.stop();
  19794. t.join();
  19795. ASSERT_FALSE(svr.is_running());
  19796. });
  19797. svr.wait_until_ready();
  19798. // Empty first field line, then a real one
  19799. std::string raw_req = "GET / HTTP/1.1\r\n"
  19800. "Host: localhost\r\n"
  19801. "Accept:\r\n"
  19802. "Accept: application/json\r\n"
  19803. "Connection: close\r\n"
  19804. "\r\n";
  19805. std::string out;
  19806. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19807. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19808. ASSERT_EQ(1U, observed_types.size());
  19809. EXPECT_EQ("application/json", observed_types[0]);
  19810. }
  19811. // The skip in get_combined_header_value() is what keeps an empty field line
  19812. // from contributing a bare comma. Only a trailing empty field line exercises
  19813. // it: a leading one is already covered by the "combined is still empty" check,
  19814. // and parse_accept_header() now ignores the empty element either way, so the
  19815. // request-level test above can no longer tell the two apart.
  19816. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19817. Headers headers;
  19818. headers.emplace("Accept", "text/html");
  19819. headers.emplace("Accept", "");
  19820. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19821. headers.clear();
  19822. headers.emplace("Accept", "");
  19823. headers.emplace("Accept", "application/json");
  19824. EXPECT_EQ("application/json",
  19825. detail::get_combined_header_value(headers, "Accept"));
  19826. }
  19827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19828. // An encoding offered on a later Accept-Encoding field line is still offered.
  19829. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19830. Server svr;
  19831. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19832. res.set_content(std::string(1024, 'x'), "text/plain");
  19833. });
  19834. auto port = svr.bind_to_any_port(HOST);
  19835. thread t = thread([&]() { svr.listen_after_bind(); });
  19836. auto se = detail::scope_exit([&] {
  19837. svr.stop();
  19838. t.join();
  19839. ASSERT_FALSE(svr.is_running());
  19840. });
  19841. svr.wait_until_ready();
  19842. Client cli(HOST, port);
  19843. cli.set_decompress(false);
  19844. Headers headers;
  19845. headers.emplace("Accept-Encoding", "identity");
  19846. headers.emplace("Accept-Encoding", "gzip");
  19847. auto res = cli.Get("/", headers);
  19848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19849. EXPECT_EQ(StatusCode::OK_200, res->status);
  19850. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19851. }
  19852. #endif
  19853. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19854. // Transfer-Encoding is not its body.
  19855. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19856. Server svr;
  19857. svr.set_payload_max_length(8);
  19858. svr.Post("/test", [](const Request &, Response &res) {
  19859. res.set_content("ok", "text/plain");
  19860. });
  19861. auto port = svr.bind_to_any_port(HOST);
  19862. ASSERT_GT(port, 0);
  19863. thread t = thread([&] { svr.listen_after_bind(); });
  19864. auto se = detail::scope_exit([&] {
  19865. svr.stop();
  19866. t.join();
  19867. ASSERT_FALSE(svr.is_running());
  19868. });
  19869. svr.wait_until_ready();
  19870. std::string resp;
  19871. ASSERT_TRUE(send_request(1,
  19872. "POST /test HTTP/1.1\r\n"
  19873. "Host: localhost\r\n"
  19874. "Connection: close\r\n"
  19875. "\r\n" +
  19876. std::string(16, 'X'),
  19877. &resp, port));
  19878. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19879. }
  19880. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19881. Server svr;
  19882. svr.Post("/post", [&](const Request &req, Response &res) {
  19883. res.set_content(req.body, "text/plain");
  19884. });
  19885. svr.Put("/put", [&](const Request &req, Response &res) {
  19886. res.set_content(req.body, "text/plain");
  19887. });
  19888. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19889. res.set_content(req.body, "text/plain");
  19890. });
  19891. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19892. res.set_content(req.body, "text/plain");
  19893. });
  19894. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19895. auto se = detail::scope_exit([&] {
  19896. svr.stop();
  19897. t.join();
  19898. ASSERT_FALSE(svr.is_running());
  19899. });
  19900. svr.wait_until_ready();
  19901. std::string resp;
  19902. // POST without Content-Length
  19903. ASSERT_TRUE(send_request(5,
  19904. "POST /post HTTP/1.1\r\n"
  19905. "Host: localhost\r\n"
  19906. "Connection: close\r\n"
  19907. "\r\n",
  19908. &resp));
  19909. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19910. // PUT without Content-Length
  19911. resp.clear();
  19912. ASSERT_TRUE(send_request(5,
  19913. "PUT /put HTTP/1.1\r\n"
  19914. "Host: localhost\r\n"
  19915. "Connection: close\r\n"
  19916. "\r\n",
  19917. &resp));
  19918. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19919. // PATCH without Content-Length
  19920. resp.clear();
  19921. ASSERT_TRUE(send_request(5,
  19922. "PATCH /patch HTTP/1.1\r\n"
  19923. "Host: localhost\r\n"
  19924. "Connection: close\r\n"
  19925. "\r\n",
  19926. &resp));
  19927. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19928. // DELETE without Content-Length
  19929. resp.clear();
  19930. ASSERT_TRUE(send_request(5,
  19931. "DELETE /delete HTTP/1.1\r\n"
  19932. "Host: localhost\r\n"
  19933. "Connection: close\r\n"
  19934. "\r\n",
  19935. &resp));
  19936. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19937. }
  19938. //==============================================================================
  19939. // open_stream() Tests
  19940. //==============================================================================
  19941. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19942. std::string result;
  19943. char buf[8192];
  19944. ssize_t n;
  19945. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19946. result.append(buf, static_cast<size_t>(n));
  19947. }
  19948. return result;
  19949. }
  19950. // Mock stream for unit tests
  19951. class MockStream : public Stream {
  19952. public:
  19953. std::string data;
  19954. size_t pos = 0;
  19955. ssize_t error_after = -1; // -1 = no error
  19956. explicit MockStream(const std::string &d, ssize_t err = -1)
  19957. : data(d), error_after(err) {}
  19958. bool is_readable() const override { return true; }
  19959. bool wait_readable() const override { return true; }
  19960. bool wait_writable() const override { return true; }
  19961. ssize_t read(char *ptr, size_t size) override {
  19962. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19963. if (pos >= data.size()) return 0;
  19964. size_t limit =
  19965. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19966. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19967. std::memcpy(ptr, data.data() + pos, to_read);
  19968. pos += to_read;
  19969. return static_cast<ssize_t>(to_read);
  19970. }
  19971. ssize_t write(const char *, size_t) override { return -1; }
  19972. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19973. ip = "127.0.0.1";
  19974. port = 0;
  19975. }
  19976. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19977. ip = "127.0.0.1";
  19978. port = 0;
  19979. }
  19980. socket_t socket() const override { return INVALID_SOCKET; }
  19981. time_t duration() const override { return 0; }
  19982. };
  19983. TEST(StreamHandleTest, Basic) {
  19984. ClientImpl::StreamHandle handle;
  19985. EXPECT_FALSE(handle.is_valid());
  19986. handle.response = detail::make_unique<Response>();
  19987. handle.error = Error::Connection;
  19988. EXPECT_FALSE(handle.is_valid());
  19989. handle.error = Error::Success;
  19990. EXPECT_TRUE(handle.is_valid());
  19991. }
  19992. TEST(BodyReaderTest, Basic) {
  19993. MockStream stream("Hello, World!");
  19994. detail::BodyReader reader;
  19995. reader.stream = &stream;
  19996. reader.content_length = 13;
  19997. char buf[32];
  19998. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19999. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20000. EXPECT_TRUE(reader.eof);
  20001. }
  20002. TEST(BodyReaderTest, NoStream) {
  20003. detail::BodyReader reader;
  20004. char buf[32];
  20005. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20006. EXPECT_EQ(Error::Connection, reader.last_error);
  20007. }
  20008. TEST(BodyReaderTest, Error) {
  20009. MockStream stream("Hello, World!", 5);
  20010. detail::BodyReader reader;
  20011. reader.stream = &stream;
  20012. reader.content_length = 13;
  20013. char buf[32];
  20014. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20015. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20016. EXPECT_EQ(Error::Read, reader.last_error);
  20017. }
  20018. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20019. // Mock-based StreamHandle tests relying on private internals are removed.
  20020. class OpenStreamTest : public ::testing::Test {
  20021. protected:
  20022. void SetUp() override {
  20023. svr_.Get("/hello", [](const Request &, Response &res) {
  20024. res.set_content("Hello World!", "text/plain");
  20025. });
  20026. svr_.Get("/large", [](const Request &, Response &res) {
  20027. res.set_content(std::string(10000, 'X'), "text/plain");
  20028. });
  20029. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20030. res.set_content("Hello World!", "image/jpeg");
  20031. res.set_header("Content-Encoding", "UTF-8");
  20032. });
  20033. svr_.Get("/chunked", [](const Request &, Response &res) {
  20034. res.set_chunked_content_provider("text/plain",
  20035. [](size_t offset, DataSink &sink) {
  20036. if (offset < 15) {
  20037. sink.write("chunk", 5);
  20038. return true;
  20039. }
  20040. sink.done();
  20041. return true;
  20042. });
  20043. });
  20044. svr_.Get("/compressible", [](const Request &, Response &res) {
  20045. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20046. DataSink &sink) {
  20047. if (offset < 100 * 1024) {
  20048. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20049. sink.write(chunk.data(), chunk.size());
  20050. return true;
  20051. }
  20052. sink.done();
  20053. return true;
  20054. });
  20055. });
  20056. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20057. [](const Request & /*req*/, Response &res) {
  20058. auto i = new int(0);
  20059. res.set_header("Trailer", "Content-Length, X-Allowed");
  20060. res.set_chunked_content_provider(
  20061. "text/plain",
  20062. [i](size_t /*offset*/, DataSink &sink) {
  20063. switch (*i) {
  20064. case 0: sink.os << "123"; break;
  20065. case 1: sink.os << "456"; break;
  20066. case 2: sink.os << "789"; break;
  20067. case 3: {
  20068. sink.done_with_trailer(
  20069. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20070. } break;
  20071. }
  20072. (*i)++;
  20073. return true;
  20074. },
  20075. [i](bool success) {
  20076. EXPECT_TRUE(success);
  20077. delete i;
  20078. });
  20079. });
  20080. // Echo headers endpoint for header-related tests
  20081. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20082. std::string body;
  20083. for (const auto &h : req.headers) {
  20084. body.append(h.first);
  20085. body.push_back(':');
  20086. body.append(h.second);
  20087. body.push_back('\n');
  20088. }
  20089. res.set_content(body, "text/plain");
  20090. });
  20091. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20092. std::string body;
  20093. for (const auto &h : req.headers) {
  20094. body.append(h.first);
  20095. body.push_back(':');
  20096. body.append(h.second);
  20097. body.push_back('\n');
  20098. }
  20099. res.set_content(body, "text/plain");
  20100. });
  20101. port_ = svr_.bind_to_any_port("127.0.0.1");
  20102. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20103. svr_.wait_until_ready();
  20104. }
  20105. void TearDown() override {
  20106. svr_.stop();
  20107. if (thread_.joinable()) thread_.join();
  20108. }
  20109. Server svr_;
  20110. std::thread thread_;
  20111. int port_ = 0;
  20112. };
  20113. TEST_F(OpenStreamTest, Basic) {
  20114. Client cli("127.0.0.1", port_);
  20115. auto handle = cli.open_stream("GET", "/hello");
  20116. EXPECT_TRUE(handle.is_valid());
  20117. EXPECT_EQ("Hello World!", read_all(handle));
  20118. }
  20119. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20120. Client cli("127.0.0.1", port_);
  20121. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20122. ASSERT_TRUE(handle.is_valid());
  20123. EXPECT_EQ("Hello World!", read_all(handle));
  20124. }
  20125. TEST_F(OpenStreamTest, SmallBuffer) {
  20126. Client cli("127.0.0.1", port_);
  20127. auto handle = cli.open_stream("GET", "/hello");
  20128. std::string result;
  20129. char buf[4];
  20130. ssize_t n;
  20131. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20132. result.append(buf, static_cast<size_t>(n));
  20133. EXPECT_EQ("Hello World!", result);
  20134. }
  20135. TEST_F(OpenStreamTest, DefaultHeaders) {
  20136. Client cli("127.0.0.1", port_);
  20137. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20138. {
  20139. auto handle = cli.open_stream("GET", "/echo-headers");
  20140. ASSERT_TRUE(handle.is_valid());
  20141. auto body = read_all(handle);
  20142. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20143. std::string::npos);
  20144. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20145. std::string::npos);
  20146. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20147. }
  20148. // open_stream POST with body and no explicit content_type should NOT add
  20149. // text/plain Content-Type (behavior differs from non-streaming path), but
  20150. // should include Content-Length
  20151. {
  20152. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20153. ASSERT_TRUE(handle.is_valid());
  20154. auto body = read_all(handle);
  20155. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20156. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20157. }
  20158. // open_stream POST with explicit Content-Type should preserve it
  20159. {
  20160. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20161. {{"Content-Type", "application/custom"}},
  20162. "{}", "application/custom");
  20163. ASSERT_TRUE(handle.is_valid());
  20164. auto body = read_all(handle);
  20165. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20166. }
  20167. // User-specified User-Agent must not be overwritten for stream API
  20168. {
  20169. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20170. {{"User-Agent", "MyAgent/1.2"}});
  20171. ASSERT_TRUE(handle.is_valid());
  20172. auto body = read_all(handle);
  20173. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20174. }
  20175. }
  20176. TEST_F(OpenStreamTest, Large) {
  20177. Client cli("127.0.0.1", port_);
  20178. auto handle = cli.open_stream("GET", "/large");
  20179. EXPECT_EQ(10000u, read_all(handle).size());
  20180. }
  20181. TEST_F(OpenStreamTest, ConnectionError) {
  20182. Client cli("127.0.0.1", 9999);
  20183. auto handle = cli.open_stream("GET", "/hello");
  20184. EXPECT_FALSE(handle.is_valid());
  20185. }
  20186. TEST_F(OpenStreamTest, Chunked) {
  20187. Client cli("127.0.0.1", port_);
  20188. auto handle = cli.open_stream("GET", "/chunked");
  20189. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20190. "Transfer-Encoding") == "chunked");
  20191. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20192. }
  20193. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20194. Client cli("127.0.0.1", port_);
  20195. auto handle =
  20196. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20197. ASSERT_TRUE(handle.is_valid());
  20198. // Consume body to allow trailers to be received/parsed
  20199. auto body = read_all(handle);
  20200. // Explicitly parse trailers (ensure trailers are available for assertion)
  20201. handle.parse_trailers_if_needed();
  20202. EXPECT_EQ(std::string("123456789"), body);
  20203. // The response should include a Trailer header declaring both names
  20204. ASSERT_TRUE(handle.response);
  20205. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20206. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20207. handle.response->get_header_value("Trailer"));
  20208. // Prohibited trailer must not be present
  20209. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20210. // Allowed trailer should be present
  20211. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20212. EXPECT_EQ(std::string("yes"),
  20213. handle.response->get_trailer_value("X-Allowed"));
  20214. // Verify trailers are NOT present as regular headers
  20215. EXPECT_EQ(std::string(""),
  20216. handle.response->get_header_value("Content-Length"));
  20217. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20218. }
  20219. // Accepts one connection on an OS-assigned port, which it hands over through
  20220. // port_promise, reads the request head and sends back response. after_send,
  20221. // if given, runs on the connection before it is closed.
  20222. static std::thread
  20223. serve_single_response(std::promise<int> &port_promise,
  20224. const std::string &response,
  20225. std::function<void(socket_t)> after_send = nullptr) {
  20226. return std::thread([&port_promise, response, after_send] {
  20227. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20228. default_socket_options(srv);
  20229. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20230. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20231. sockaddr_in addr{};
  20232. addr.sin_family = AF_INET;
  20233. addr.sin_port = htons(0); // Let OS assign a free port
  20234. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20235. int opt = 1;
  20236. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20237. #ifdef _WIN32
  20238. reinterpret_cast<const char *>(&opt),
  20239. #else
  20240. &opt,
  20241. #endif
  20242. sizeof(opt));
  20243. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20244. ::listen(srv, 1) != 0) {
  20245. port_promise.set_value(-1);
  20246. detail::close_socket(srv);
  20247. return;
  20248. }
  20249. socklen_t addr_len = sizeof(addr);
  20250. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20251. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20252. sockaddr_in cli_addr{};
  20253. socklen_t cli_len = sizeof(cli_addr);
  20254. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20255. if (cli != INVALID_SOCKET) {
  20256. // Read the complete HTTP request (until the blank line that terminates
  20257. // headers) before sending the response. If the server closes the socket
  20258. // while the client's request data is still unread in the kernel receive
  20259. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20260. // connection on both sides: it discards the client's receive buffer
  20261. // (which already holds our response) and causes any in-progress write on
  20262. // the client to fail with ECONNRESET. Reading all request data first
  20263. // ensures close() emits a graceful FIN.
  20264. {
  20265. char rbuf[256];
  20266. std::string req;
  20267. while (req.find("\r\n\r\n") == std::string::npos) {
  20268. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20269. if (n <= 0) { break; }
  20270. req.append(rbuf, static_cast<size_t>(n));
  20271. }
  20272. }
  20273. ::send(cli,
  20274. #ifdef _WIN32
  20275. static_cast<const char *>(response.c_str()),
  20276. static_cast<int>(response.size()),
  20277. #else
  20278. response.c_str(), response.size(),
  20279. #endif
  20280. 0);
  20281. if (after_send) { after_send(cli); }
  20282. detail::close_socket(cli);
  20283. }
  20284. detail::close_socket(srv);
  20285. });
  20286. }
  20287. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20288. #ifndef _WIN32
  20289. signal(SIGPIPE, SIG_IGN);
  20290. #endif
  20291. std::promise<int> port_promise;
  20292. auto port_future = port_promise.get_future();
  20293. auto server_thread =
  20294. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20295. "Content-Type: text/plain\r\n"
  20296. "Content-Length: not-a-number\r\n"
  20297. "Connection: close\r\n"
  20298. "\r\n"
  20299. "hello");
  20300. auto port = port_future.get();
  20301. ASSERT_GT(port, 0);
  20302. Client cli("127.0.0.1", port);
  20303. auto handle = cli.open_stream("GET", "/");
  20304. EXPECT_FALSE(handle.is_valid());
  20305. server_thread.join();
  20306. }
  20307. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20308. #ifndef _WIN32
  20309. signal(SIGPIPE, SIG_IGN);
  20310. #endif
  20311. std::promise<int> port_promise;
  20312. auto port_future = port_promise.get_future();
  20313. auto server_thread = serve_single_response(
  20314. port_promise, "HTTP/1.1 200 OK\r\n"
  20315. "Content-Type: text/plain\r\n"
  20316. "Content-Length: 99999999999999999999999999\r\n"
  20317. "Connection: close\r\n"
  20318. "\r\n"
  20319. "hello");
  20320. auto port = port_future.get();
  20321. ASSERT_GT(port, 0);
  20322. // Historically std::stoull would throw std::out_of_range here and crash
  20323. // the process, then parsing silently clamped to a bogus framing length and
  20324. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20325. // so the stream fails to open, matching the not-a-number case above. The
  20326. // process still must NOT terminate.
  20327. Client cli("127.0.0.1", port);
  20328. auto handle = cli.open_stream("GET", "/");
  20329. EXPECT_FALSE(handle.is_valid());
  20330. server_thread.join();
  20331. }
  20332. #ifndef _WIN32
  20333. // As above for the body of a streamed request: a send() cut short by the write
  20334. // timeout must not leave the rest of the body unsent.
  20335. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20336. signal(SIGPIPE, SIG_IGN);
  20337. Server svr;
  20338. svr.set_socket_options([](socket_t sock) {
  20339. int size = 8192;
  20340. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20341. reinterpret_cast<const char *>(&size), sizeof(size));
  20342. });
  20343. svr.Post("/size", [](const Request &, Response &res,
  20344. const ContentReader &content_reader) {
  20345. // Outlast the client's write timeout before reading the body.
  20346. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20347. size_t received = 0;
  20348. content_reader([&](const char *, size_t len) {
  20349. received += len;
  20350. return true;
  20351. });
  20352. res.set_content(std::to_string(received), "text/plain");
  20353. });
  20354. auto port = svr.bind_to_any_port(HOST);
  20355. std::thread t([&]() { svr.listen_after_bind(); });
  20356. auto se = detail::scope_exit([&] {
  20357. svr.stop();
  20358. t.join();
  20359. });
  20360. svr.wait_until_ready();
  20361. Client cli(HOST, port);
  20362. cli.set_write_timeout(0, 500000);
  20363. cli.set_socket_options([](socket_t sock) {
  20364. int size = 8192;
  20365. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20366. reinterpret_cast<const char *>(&size), sizeof(size));
  20367. });
  20368. const std::string body(4 * 1024 * 1024, 'A');
  20369. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20370. "application/octet-stream");
  20371. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20372. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20373. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20374. }
  20375. #endif
  20376. // Serves `response` to the single request `fn` makes with a fresh client.
  20377. template <typename Fn>
  20378. static void with_single_response(const std::string &response, Fn fn) {
  20379. #ifndef _WIN32
  20380. signal(SIGPIPE, SIG_IGN);
  20381. #endif
  20382. std::promise<int> port_promise;
  20383. auto port_future = port_promise.get_future();
  20384. auto server_thread = serve_single_response(port_promise, response);
  20385. auto se = detail::scope_exit([&] { server_thread.join(); });
  20386. auto port = port_future.get();
  20387. ASSERT_GT(port, 0);
  20388. Client cli("127.0.0.1", port);
  20389. fn(cli);
  20390. }
  20391. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20392. // too, also in a build without the decoder for the advertised coding.
  20393. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20394. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20395. const auto response = "HTTP/1.1 200 OK\r\n"
  20396. "Content-Encoding: gzip\r\n"
  20397. "Content-Length: " +
  20398. std::to_string(gzipped.size()) +
  20399. "\r\n"
  20400. "Connection: close\r\n\r\n" +
  20401. gzipped;
  20402. with_single_response(response, [&](Client &cli) {
  20403. cli.set_decompress(false);
  20404. auto handle = cli.open_stream("GET", "/");
  20405. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20406. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20407. EXPECT_EQ(gzipped, read_all(handle));
  20408. EXPECT_FALSE(handle.has_read_error());
  20409. });
  20410. with_single_response(response, [&](Client &cli) {
  20411. cli.set_decompress(false);
  20412. auto res = stream::Get(cli, "/", 7);
  20413. ASSERT_TRUE(res) << to_string(res.error());
  20414. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20415. EXPECT_EQ(gzipped, res.read_all());
  20416. EXPECT_FALSE(res.has_read_error());
  20417. });
  20418. }
  20419. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20420. // Neither Content-Length nor chunked: the body ends at the close
  20421. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20422. "Connection: close\r\n"
  20423. "\r\n"
  20424. "hello";
  20425. with_single_response(close_delimited, [](Client &cli) {
  20426. auto handle = cli.open_stream("GET", "/");
  20427. ASSERT_TRUE(handle.is_valid());
  20428. EXPECT_EQ("hello", read_all(handle));
  20429. EXPECT_FALSE(handle.has_read_error());
  20430. });
  20431. // A close before the end of the Content-Length is still an error
  20432. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20433. "Content-Length: 10\r\n"
  20434. "\r\n"
  20435. "hello";
  20436. with_single_response(short_content_length, [](Client &cli) {
  20437. auto handle = cli.open_stream("GET", "/");
  20438. ASSERT_TRUE(handle.is_valid());
  20439. read_all(handle);
  20440. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20441. });
  20442. // So is a close before the last chunk
  20443. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20444. "Transfer-Encoding: chunked\r\n"
  20445. "\r\n"
  20446. "5\r\nhello\r\n";
  20447. with_single_response(short_chunked, [](Client &cli) {
  20448. auto handle = cli.open_stream("GET", "/");
  20449. ASSERT_TRUE(handle.is_valid());
  20450. read_all(handle);
  20451. EXPECT_TRUE(handle.has_read_error());
  20452. });
  20453. }
  20454. #ifdef CPPHTTPLIB_SSL_ENABLED
  20455. // Serves `response` to one request, then closes with or without a close_notify
  20456. template <typename Fn>
  20457. static void with_single_tls_response(const std::string &response,
  20458. bool close_notify, Fn fn) {
  20459. #ifndef _WIN32
  20460. signal(SIGPIPE, SIG_IGN);
  20461. #endif
  20462. std::promise<int> port_promise;
  20463. auto port_future = port_promise.get_future();
  20464. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20465. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20466. default_socket_options(srv);
  20467. sockaddr_in addr{};
  20468. addr.sin_family = AF_INET;
  20469. addr.sin_port = htons(0);
  20470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20471. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20472. ::listen(srv, 1) != 0) {
  20473. port_promise.set_value(-1);
  20474. detail::close_socket(srv);
  20475. return;
  20476. }
  20477. socklen_t addr_len = sizeof(addr);
  20478. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20479. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20480. auto cli = ::accept(srv, nullptr, nullptr);
  20481. if (cli != INVALID_SOCKET) {
  20482. auto ctx = tls::create_server_context();
  20483. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20484. nullptr);
  20485. auto session = tls::create_session(ctx, cli);
  20486. tls::TlsError err;
  20487. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20488. // The request head first, so that closing the socket sends a FIN
  20489. // rather than an RST for the unread bytes.
  20490. std::string req;
  20491. char buf[256];
  20492. while (req.find("\r\n\r\n") == std::string::npos) {
  20493. auto n = tls::read(session, buf, sizeof(buf), err);
  20494. if (n <= 0) { break; }
  20495. req.append(buf, static_cast<size_t>(n));
  20496. }
  20497. size_t sent = 0;
  20498. while (sent < response.size()) {
  20499. auto n = tls::write(session, response.data() + sent,
  20500. response.size() - sent, err);
  20501. if (n <= 0) { break; }
  20502. sent += static_cast<size_t>(n);
  20503. }
  20504. if (close_notify) { tls::shutdown(session, true); }
  20505. }
  20506. tls::free_session(session);
  20507. detail::close_socket(cli);
  20508. tls::free_context(ctx);
  20509. }
  20510. detail::close_socket(srv);
  20511. });
  20512. auto se = detail::scope_exit([&] { server_thread.join(); });
  20513. auto port = port_future.get();
  20514. ASSERT_GT(port, 0);
  20515. SSLClient cli("127.0.0.1", port);
  20516. cli.enable_server_certificate_verification(false);
  20517. fn(cli);
  20518. }
  20519. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20520. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20521. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20522. "Connection: close\r\n"
  20523. "\r\n"
  20524. "hello";
  20525. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20526. auto res = cli.Get("/");
  20527. ASSERT_TRUE(res) << to_string(res.error());
  20528. EXPECT_EQ("hello", res->body);
  20529. });
  20530. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20531. auto res = cli.Get("/");
  20532. ASSERT_FALSE(res);
  20533. EXPECT_EQ(Error::Read, res.error());
  20534. });
  20535. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20536. auto handle = cli.open_stream("GET", "/");
  20537. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20538. read_all(handle);
  20539. EXPECT_TRUE(handle.has_read_error());
  20540. });
  20541. // A framed body ends where its framing says, with or without the alert
  20542. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20543. "Content-Length: 5\r\n"
  20544. "Connection: close\r\n"
  20545. "\r\n"
  20546. "hello";
  20547. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20548. auto res = cli.Get("/");
  20549. ASSERT_TRUE(res) << to_string(res.error());
  20550. EXPECT_EQ("hello", res->body);
  20551. });
  20552. }
  20553. #endif
  20554. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20555. const char *responses[] = {
  20556. "HTTP/1.1 103 Early Hints\r\n"
  20557. "Link: </style.css>; rel=preload\r\n"
  20558. "\r\n"
  20559. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20560. "HTTP/1.1 100 Continue\r\n"
  20561. "X-Note: interim\r\n"
  20562. "\r\n"
  20563. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20564. };
  20565. for (auto response : responses) {
  20566. with_single_response(response, [](Client &cli) {
  20567. auto res = cli.Get("/");
  20568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20569. EXPECT_EQ(StatusCode::OK_200, res->status);
  20570. EXPECT_EQ("ok", res->body);
  20571. });
  20572. }
  20573. }
  20574. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20575. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20576. const std::string final_response =
  20577. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20578. std::string interims;
  20579. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20580. interims += interim;
  20581. }
  20582. with_single_response(interims + final_response, [](Client &cli) {
  20583. auto res = cli.Get("/");
  20584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20585. EXPECT_EQ("ok", res->body);
  20586. });
  20587. with_single_response(interims + interim + final_response, [](Client &cli) {
  20588. auto res = cli.Get("/");
  20589. ASSERT_FALSE(res);
  20590. EXPECT_EQ(Error::Read, res.error());
  20591. });
  20592. }
  20593. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20594. #ifndef _WIN32
  20595. signal(SIGPIPE, SIG_IGN);
  20596. #endif
  20597. // The server answers the head without asking for the body. Bytes it then
  20598. // reads on the connection would be taken for the body the request declared.
  20599. auto closed_by_client = false;
  20600. std::promise<int> port_promise;
  20601. auto server_thread = serve_single_response(
  20602. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20603. [&](socket_t sock) {
  20604. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20605. char buf[256];
  20606. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20607. });
  20608. Client cli("127.0.0.1", port_promise.get_future().get());
  20609. cli.set_keep_alive(true);
  20610. cli.set_read_timeout(1, 0);
  20611. // Long enough for the client to send Expect: 100-continue.
  20612. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20615. cli.Get("/second");
  20616. server_thread.join();
  20617. EXPECT_TRUE(closed_by_client);
  20618. }
  20619. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20620. // Long enough for the client to send Expect: 100-continue
  20621. with_single_response(
  20622. "HTTP/1.1 103 Early Hints\r\n"
  20623. "Link: </style.css>; rel=preload\r\n"
  20624. "\r\n"
  20625. "HTTP/1.1 401 Unauthorized\r\n"
  20626. "Content-Length: 0\r\n\r\n",
  20627. [](Client &cli) {
  20628. cli.set_read_timeout(2, 0);
  20629. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20631. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20632. });
  20633. }
  20634. #ifdef CPPHTTPLIB_SSL_ENABLED
  20635. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20636. #ifndef _WIN32
  20637. signal(SIGPIPE, SIG_IGN);
  20638. #endif
  20639. auto reused = false;
  20640. std::promise<int> port_promise;
  20641. auto server_thread = serve_single_response(
  20642. port_promise,
  20643. "HTTP/1.1 401 Unauthorized\r\n"
  20644. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20645. "Content-Length: 0\r\n\r\n",
  20646. [&](socket_t sock) {
  20647. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20648. char buf[256];
  20649. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20650. });
  20651. Client cli("127.0.0.1", port_promise.get_future().get());
  20652. cli.set_keep_alive(true);
  20653. cli.set_digest_auth("user", "pass");
  20654. cli.set_read_timeout(1, 0);
  20655. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20656. server_thread.join();
  20657. EXPECT_FALSE(reused);
  20658. }
  20659. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20660. // Any other answer to CONNECT would read as the origin's response.
  20661. struct {
  20662. const char *response;
  20663. bool passed_on;
  20664. } cases[] = {
  20665. {"HTTP/1.1 201 Created\r\n"
  20666. "Set-Cookie: session=from-proxy\r\n"
  20667. "Content-Length: 0\r\n\r\n",
  20668. false},
  20669. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20670. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20671. "Content-Length: 0\r\n\r\n",
  20672. true},
  20673. };
  20674. for (const auto &c : cases) {
  20675. std::promise<int> port_promise;
  20676. auto server_thread = serve_single_response(port_promise, c.response);
  20677. SSLClient cli("example.com", 443);
  20678. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20679. auto res = cli.Get("/");
  20680. server_thread.join();
  20681. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20682. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20683. if (res) {
  20684. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20685. }
  20686. }
  20687. }
  20688. #endif
  20689. // Records the client's error logger calls as "error METHOD path", or
  20690. // "error null" for a call without a request
  20691. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20692. return [&log](const Error &err, const Request *req) {
  20693. log.push_back(to_string(err) + " " +
  20694. (req ? req->method + " " + req->path : "null"));
  20695. };
  20696. }
  20697. // A failed request is reported once, with the request the caller made
  20698. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20699. Server svr;
  20700. svr.Get("/big", [](const Request &, Response &res) {
  20701. res.set_content(std::string(100000, 'b'), "text/plain");
  20702. });
  20703. auto port = svr.bind_to_any_port(HOST);
  20704. std::thread t([&]() { svr.listen_after_bind(); });
  20705. auto se = detail::scope_exit([&] {
  20706. svr.stop();
  20707. t.join();
  20708. });
  20709. svr.wait_until_ready();
  20710. Client cli(HOST, port);
  20711. std::vector<std::string> log;
  20712. cli.set_error_logger(record_errors(log));
  20713. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20714. cli.Get("/big", [](const char *, size_t) { return false; });
  20715. EXPECT_EQ(expected, log);
  20716. log.clear();
  20717. cli.Get("/big", [](size_t, size_t) { return false; });
  20718. EXPECT_EQ(expected, log);
  20719. }
  20720. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20721. // Fails while the body is read
  20722. auto broken = [](const Request &, Response &res) {
  20723. res.set_content_provider(10, "text/plain",
  20724. [](size_t, size_t, DataSink &) { return false; });
  20725. };
  20726. Server other;
  20727. other.Get("/broken", broken);
  20728. auto other_port = other.bind_to_any_port(HOST);
  20729. std::thread other_t([&]() { other.listen_after_bind(); });
  20730. auto other_se = detail::scope_exit([&] {
  20731. other.stop();
  20732. other_t.join();
  20733. });
  20734. other.wait_until_ready();
  20735. Server svr;
  20736. svr.Get("/broken", broken);
  20737. svr.Get("/same-origin",
  20738. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20739. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20740. res.set_redirect("http://" + std::string(HOST) + ":" +
  20741. std::to_string(other_port) + "/broken");
  20742. });
  20743. auto port = svr.bind_to_any_port(HOST);
  20744. std::thread t([&]() { svr.listen_after_bind(); });
  20745. auto se = detail::scope_exit([&] {
  20746. svr.stop();
  20747. t.join();
  20748. });
  20749. svr.wait_until_ready();
  20750. Client cli(HOST, port);
  20751. cli.set_follow_location(true);
  20752. std::vector<std::string> log;
  20753. cli.set_error_logger(record_errors(log));
  20754. for (auto path : {"/same-origin", "/cross-origin"}) {
  20755. log.clear();
  20756. auto res = cli.Get(path);
  20757. ASSERT_FALSE(res);
  20758. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20759. log);
  20760. }
  20761. }
  20762. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20763. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20764. std::vector<std::string> log;
  20765. cli.set_error_logger(record_errors(log));
  20766. auto handle = cli.open_stream("GET", "/x");
  20767. EXPECT_FALSE(handle.is_valid());
  20768. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20769. log);
  20770. });
  20771. }
  20772. #ifdef CPPHTTPLIB_SSL_ENABLED
  20773. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20774. // Not a TLS server, so the handshake fails. It waits for a request line in
  20775. // the handshake bytes, so a short read timeout lets it close quickly.
  20776. Server svr;
  20777. svr.set_read_timeout(0, 100000);
  20778. svr.Get("/x", [](const Request &, Response &res) {
  20779. res.set_content("x", "text/plain");
  20780. });
  20781. auto port = svr.bind_to_any_port(HOST);
  20782. std::thread t([&]() { svr.listen_after_bind(); });
  20783. auto se = detail::scope_exit([&] {
  20784. svr.stop();
  20785. t.join();
  20786. });
  20787. svr.wait_until_ready();
  20788. std::vector<std::string> log;
  20789. SSLClient cli(HOST, port);
  20790. cli.enable_server_certificate_verification(false);
  20791. cli.set_error_logger(record_errors(log));
  20792. auto res = cli.Get("/x");
  20793. ASSERT_FALSE(res);
  20794. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20795. log.clear();
  20796. auto handle = cli.open_stream("GET", "/x");
  20797. EXPECT_FALSE(handle.is_valid());
  20798. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20799. log.clear();
  20800. SSLClient no_ca(HOST, port);
  20801. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20802. no_ca.set_error_logger(record_errors(log));
  20803. res = no_ca.Get("/x");
  20804. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20805. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20806. }
  20807. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20808. #ifndef _WIN32
  20809. signal(SIGPIPE, SIG_IGN);
  20810. #endif
  20811. // Refused, answered with a challenge, or closed without an answer
  20812. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20813. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20814. "Content-Length: 0\r\n\r\n",
  20815. ""}) {
  20816. std::promise<int> port_promise;
  20817. auto server_thread = serve_single_response(port_promise, response);
  20818. SSLClient cli("example.com", 443);
  20819. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20820. std::vector<std::string> log;
  20821. cli.set_error_logger(record_errors(log));
  20822. auto res = cli.Get("/");
  20823. server_thread.join();
  20824. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20825. << response;
  20826. }
  20827. }
  20828. #endif
  20829. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20830. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20831. // the chunked coding and drop Content-Length, so a front-end that trusts
  20832. // Content-Length would disagree about where the body ends (response
  20833. // smuggling). The client must reject such a response.
  20834. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20835. for (const char *te : {"chunked", "gzip, chunked"}) {
  20836. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20837. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20838. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20839. "5\r\nhello\r\n0\r\n\r\n";
  20840. with_single_response(response, [&](Client &cli) {
  20841. auto res = cli.Get("/");
  20842. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20843. EXPECT_EQ(Error::Read, res.error()) << te;
  20844. });
  20845. with_single_response(response, [&](Client &cli) {
  20846. auto handle = cli.open_stream("GET", "/");
  20847. EXPECT_FALSE(handle.is_valid()) << te;
  20848. EXPECT_EQ(Error::Read, handle.error) << te;
  20849. });
  20850. }
  20851. }
  20852. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20853. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20854. // closing the connection (unlike a request, which must be rejected).
  20855. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20856. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20857. "Transfer-Encoding: chunked\r\n"
  20858. "Connection: close\r\n"
  20859. "\r\n"
  20860. "5\r\nhello\r\n0\r\n\r\n",
  20861. "HTTP/1.1 200 OK\r\n"
  20862. "Transfer-Encoding: gzip\r\n"
  20863. "Connection: close\r\n"
  20864. "\r\n"
  20865. "hello"}) {
  20866. with_single_response(response, [&](Client &cli) {
  20867. auto res = cli.Get("/");
  20868. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20869. EXPECT_EQ("hello", res->body);
  20870. });
  20871. with_single_response(response, [&](Client &cli) {
  20872. auto handle = cli.open_stream("GET", "/");
  20873. ASSERT_TRUE(handle.is_valid()) << response;
  20874. EXPECT_EQ("hello", read_all(handle));
  20875. });
  20876. }
  20877. }
  20878. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20879. // framing headers describe nothing to read and must not be rejected.
  20880. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20881. const std::string framing = "Content-Length: 5\r\n"
  20882. "Transfer-Encoding: chunked\r\n"
  20883. "Connection: close\r\n"
  20884. "\r\n";
  20885. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20886. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20887. });
  20888. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20889. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20890. });
  20891. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20892. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20893. with_single_response(response, [&](Client &cli) {
  20894. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20895. });
  20896. with_single_response(response, [&](Client &cli) {
  20897. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20898. });
  20899. }
  20900. }
  20901. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20902. // header section, so a stream opened on one has nothing to read, whatever
  20903. // framing or coding headers it carries.
  20904. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20905. struct Case {
  20906. const char *method;
  20907. const char *status;
  20908. };
  20909. // A reader of the declared body reports an early close when nothing
  20910. // follows, and hands back what does.
  20911. struct Framing {
  20912. const char *headers;
  20913. const char *after;
  20914. };
  20915. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20916. Case{"GET", "304 Not Modified"}}) {
  20917. for (const auto &f :
  20918. {Framing{"Content-Length: 5\r\n", ""},
  20919. Framing{"Content-Length: 5\r\n", "hello"},
  20920. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20921. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20922. // Not decoded, so a build without Brotli opens it too
  20923. Framing{"Content-Encoding: br\r\n", ""}}) {
  20924. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20925. "Connection: close\r\n"
  20926. "\r\n" +
  20927. f.after;
  20928. with_single_response(response, [&](Client &cli) {
  20929. auto handle = cli.open_stream(c.method, "/");
  20930. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20931. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20932. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20933. });
  20934. }
  20935. }
  20936. }
  20937. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20938. // response, is faulty framing, so the connection is not reused after it.
  20939. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20940. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20941. "Content-Length: 0\r\n"
  20942. "Transfer-Encoding: chunked\r\n"
  20943. "\r\n"
  20944. "5\r\nhello\r\n0\r\n\r\n",
  20945. "HTTP/1.0 200 Connection established\r\n"
  20946. "Connection: keep-alive\r\n"
  20947. "Transfer-Encoding: chunked\r\n"
  20948. "\r\n"
  20949. "5\r\nhello\r\n0\r\n\r\n"}) {
  20950. with_single_response(response, [&](Client &cli) {
  20951. cli.set_keep_alive(true);
  20952. auto res = cli.Get("/");
  20953. ASSERT_TRUE(res) << response;
  20954. EXPECT_EQ("hello", res->body);
  20955. EXPECT_FALSE(cli.is_socket_open()) << response;
  20956. });
  20957. }
  20958. }
  20959. // A payload max length of 0 means no limit, however the body is framed.
  20960. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20961. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20962. "Transfer-Encoding: chunked\r\n"
  20963. "\r\n"
  20964. "5\r\nhello\r\n0\r\n\r\n",
  20965. "HTTP/1.1 200 OK\r\n"
  20966. "Connection: close\r\n"
  20967. "\r\n"
  20968. "hello"}) {
  20969. with_single_response(response, [&](Client &cli) {
  20970. cli.set_payload_max_length(0);
  20971. auto res = cli.Get("/");
  20972. ASSERT_TRUE(res) << response;
  20973. EXPECT_EQ("hello", res->body) << response;
  20974. });
  20975. }
  20976. }
  20977. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20978. Server svr;
  20979. svr.set_payload_max_length(0);
  20980. svr.Post("/echo", [](const Request &req, Response &res) {
  20981. res.set_content(req.body, "text/plain");
  20982. });
  20983. auto port = svr.bind_to_any_port(HOST);
  20984. thread t = thread([&] { svr.listen_after_bind(); });
  20985. auto se = detail::scope_exit([&] {
  20986. svr.stop();
  20987. t.join();
  20988. ASSERT_FALSE(svr.is_running());
  20989. });
  20990. svr.wait_until_ready();
  20991. Client cli(HOST, port);
  20992. auto res = cli.Post(
  20993. "/echo",
  20994. [](size_t /*offset*/, DataSink &sink) {
  20995. sink.write("hello", 5);
  20996. sink.done();
  20997. return true;
  20998. },
  20999. "text/plain");
  21000. ASSERT_TRUE(res);
  21001. EXPECT_EQ(StatusCode::OK_200, res->status);
  21002. EXPECT_EQ("hello", res->body);
  21003. }
  21004. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21005. TEST_F(OpenStreamTest, Gzip) {
  21006. Client cli("127.0.0.1", port_);
  21007. auto handle = cli.open_stream("GET", "/compressible", {},
  21008. {{"Accept-Encoding", "gzip"}});
  21009. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21010. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21011. }
  21012. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21013. Client cli("127.0.0.1", port_);
  21014. auto handle =
  21015. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21016. {{"Accept-Encoding", "gzip"}});
  21017. ASSERT_TRUE(handle.is_valid());
  21018. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21019. EXPECT_EQ("123456789", read_all(handle));
  21020. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21021. }
  21022. #endif
  21023. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21024. TEST_F(OpenStreamTest, Brotli) {
  21025. Client cli("127.0.0.1", port_);
  21026. auto handle =
  21027. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21028. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21029. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21030. }
  21031. #endif
  21032. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21033. TEST_F(OpenStreamTest, Zstd) {
  21034. Client cli("127.0.0.1", port_);
  21035. auto handle = cli.open_stream("GET", "/compressible", {},
  21036. {{"Accept-Encoding", "zstd"}});
  21037. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21038. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21039. }
  21040. #endif
  21041. #ifdef CPPHTTPLIB_SSL_ENABLED
  21042. class SSLOpenStreamTest : public ::testing::Test {
  21043. protected:
  21044. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21045. void SetUp() override {
  21046. svr_.Get("/hello", [](const Request &, Response &res) {
  21047. res.set_content("Hello SSL World!", "text/plain");
  21048. });
  21049. svr_.Get("/chunked", [](const Request &, Response &res) {
  21050. res.set_chunked_content_provider("text/plain",
  21051. [](size_t offset, DataSink &sink) {
  21052. if (offset < 15) {
  21053. sink.write("chunk", 5);
  21054. return true;
  21055. }
  21056. sink.done();
  21057. return true;
  21058. });
  21059. });
  21060. svr_.Post("/echo", [](const Request &req, Response &res) {
  21061. res.set_content(req.body, req.get_header_value("Content-Type"));
  21062. });
  21063. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21064. std::string body = req.body;
  21065. res.set_chunked_content_provider(
  21066. "text/plain", [body](size_t offset, DataSink &sink) {
  21067. if (offset < body.size()) {
  21068. sink.write(body.data() + offset, body.size() - offset);
  21069. }
  21070. sink.done();
  21071. return true;
  21072. });
  21073. });
  21074. port_ = svr_.bind_to_any_port("127.0.0.1");
  21075. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21076. svr_.wait_until_ready();
  21077. }
  21078. void TearDown() override {
  21079. svr_.stop();
  21080. if (thread_.joinable()) thread_.join();
  21081. }
  21082. SSLServer svr_;
  21083. std::thread thread_;
  21084. int port_ = 0;
  21085. };
  21086. TEST_F(SSLOpenStreamTest, Basic) {
  21087. SSLClient cli("127.0.0.1", port_);
  21088. cli.enable_server_certificate_verification(false);
  21089. auto handle = cli.open_stream("GET", "/hello");
  21090. ASSERT_TRUE(handle.is_valid());
  21091. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21092. }
  21093. TEST_F(SSLOpenStreamTest, Chunked) {
  21094. SSLClient cli("127.0.0.1", port_);
  21095. cli.enable_server_certificate_verification(false);
  21096. auto handle = cli.open_stream("GET", "/chunked");
  21097. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21098. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21099. "Transfer-Encoding") == "chunked");
  21100. auto body = read_all(handle);
  21101. EXPECT_EQ("chunkchunkchunk", body);
  21102. }
  21103. TEST_F(SSLOpenStreamTest, Post) {
  21104. SSLClient cli("127.0.0.1", port_);
  21105. cli.enable_server_certificate_verification(false);
  21106. auto handle =
  21107. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21108. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21109. EXPECT_EQ(200, handle.response->status);
  21110. auto body = read_all(handle);
  21111. EXPECT_EQ("Hello SSL POST", body);
  21112. }
  21113. TEST_F(SSLOpenStreamTest, PostChunked) {
  21114. SSLClient cli("127.0.0.1", port_);
  21115. cli.enable_server_certificate_verification(false);
  21116. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21117. "Chunked SSL Data", "text/plain");
  21118. ASSERT_TRUE(handle.is_valid());
  21119. EXPECT_EQ(200, handle.response->status);
  21120. auto body = read_all(handle);
  21121. EXPECT_EQ("Chunked SSL Data", body);
  21122. }
  21123. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21124. // Content-Length is terminated by the server closing the connection. When the
  21125. // SSL peer sends a close_notify after the body, the client must treat it as a
  21126. // clean EOF and return a successful response rather than an error.
  21127. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21129. ASSERT_TRUE(svr.is_valid());
  21130. svr.set_keep_alive_max_count(1);
  21131. const std::string expected_body = "Hello from connection-close response!";
  21132. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21133. res.set_content_provider("text/plain",
  21134. [&](size_t offset, DataSink &sink) -> bool {
  21135. if (offset < expected_body.size()) {
  21136. sink.write(expected_body.data() + offset,
  21137. expected_body.size() - offset);
  21138. }
  21139. sink.done();
  21140. return true;
  21141. });
  21142. });
  21143. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21144. auto se = detail::scope_exit([&] {
  21145. svr.stop();
  21146. listen_thread.join();
  21147. ASSERT_FALSE(svr.is_running());
  21148. });
  21149. svr.wait_until_ready();
  21150. SSLClient cli(HOST, PORT);
  21151. cli.enable_server_certificate_verification(false);
  21152. auto res = cli.Get("/no-content-length");
  21153. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21154. EXPECT_EQ(StatusCode::OK_200, res->status);
  21155. EXPECT_EQ(expected_body, res->body);
  21156. }
  21157. // Without Content-Length, the full buffer size reaches tls::read().
  21158. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21159. if (sizeof(size_t) <= sizeof(int)) {
  21160. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21161. }
  21162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21163. ASSERT_TRUE(svr.is_valid());
  21164. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21165. res.set_content_provider("text/plain",
  21166. [&](size_t offset, DataSink &sink) -> bool {
  21167. if (offset == 0) { sink.write("Hello", 5); }
  21168. sink.done();
  21169. return true;
  21170. });
  21171. });
  21172. auto port = svr.bind_to_any_port(HOST);
  21173. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21174. auto se = detail::scope_exit([&] {
  21175. svr.stop();
  21176. listen_thread.join();
  21177. });
  21178. svr.wait_until_ready();
  21179. SSLClient cli(HOST, port);
  21180. cli.enable_server_certificate_verification(false);
  21181. auto handle = cli.open_stream("GET", "/no-content-length");
  21182. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21183. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21184. std::unique_ptr<char[]> buf(new char[len]);
  21185. std::string body;
  21186. ssize_t n;
  21187. while ((n = handle.read(buf.get(), len)) > 0) {
  21188. body.append(buf.get(), static_cast<size_t>(n));
  21189. }
  21190. EXPECT_EQ(0, n);
  21191. EXPECT_EQ("Hello", body);
  21192. }
  21193. #endif // CPPHTTPLIB_SSL_ENABLED
  21194. //==============================================================================
  21195. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21196. // results for various scenarios.
  21197. //==============================================================================
  21198. TEST(ParityTest, GetVsOpenStream) {
  21199. Server svr;
  21200. const std::string path = "/parity";
  21201. const std::string content = "Parity test content: hello world";
  21202. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21203. res.set_content(content, "text/plain");
  21204. });
  21205. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21206. auto se = detail::scope_exit([&] {
  21207. svr.stop();
  21208. t.join();
  21209. ASSERT_FALSE(svr.is_running());
  21210. });
  21211. svr.wait_until_ready();
  21212. Client cli(HOST, PORT);
  21213. // Non-stream path
  21214. auto r1 = cli.Get(path);
  21215. ASSERT_TRUE(r1);
  21216. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21217. // Stream path
  21218. auto h = cli.open_stream("GET", path);
  21219. ASSERT_TRUE(h.is_valid());
  21220. EXPECT_EQ(r1->body, read_all(h));
  21221. }
  21222. // Helper to compress data with provided compressor type T
  21223. template <typename Compressor>
  21224. static std::string compress_payload_for_parity(const std::string &in) {
  21225. std::string out;
  21226. Compressor compressor;
  21227. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21228. [&](const char *data, size_t n) {
  21229. out.append(data, n);
  21230. return true;
  21231. });
  21232. EXPECT_TRUE(ok);
  21233. return out;
  21234. }
  21235. // Helper function for compression parity tests
  21236. template <typename Compressor>
  21237. static void test_compression_parity(const std::string &original,
  21238. const std::string &path,
  21239. const std::string &encoding) {
  21240. const std::string compressed =
  21241. compress_payload_for_parity<Compressor>(original);
  21242. Server svr;
  21243. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21244. res.set_content(compressed, "application/octet-stream");
  21245. res.set_header("Content-Encoding", encoding);
  21246. });
  21247. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21248. auto se = detail::scope_exit([&] {
  21249. svr.stop();
  21250. t.join();
  21251. ASSERT_FALSE(svr.is_running());
  21252. });
  21253. svr.wait_until_ready();
  21254. Client cli(HOST, PORT);
  21255. // Non-streaming
  21256. {
  21257. auto res = cli.Get(path);
  21258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21259. EXPECT_EQ(StatusCode::OK_200, res->status);
  21260. EXPECT_EQ(original, res->body);
  21261. }
  21262. // Streaming
  21263. {
  21264. auto h = cli.open_stream("GET", path);
  21265. ASSERT_TRUE(h.is_valid());
  21266. EXPECT_EQ(original, read_all(h));
  21267. }
  21268. }
  21269. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21270. TEST(ParityTest, Gzip) {
  21271. test_compression_parity<detail::gzip_compressor>(
  21272. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21273. }
  21274. #endif
  21275. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21276. TEST(ParityTest, Brotli) {
  21277. test_compression_parity<detail::brotli_compressor>(
  21278. "Hello, brotli parity test payload", "/parity-br", "br");
  21279. }
  21280. #endif
  21281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21282. TEST(ParityTest, Zstd) {
  21283. test_compression_parity<detail::zstd_compressor>(
  21284. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21285. }
  21286. #endif
  21287. //==============================================================================
  21288. // New Stream API Tests
  21289. //==============================================================================
  21290. inline std::string read_body(httplib::stream::Result &result) {
  21291. std::string body;
  21292. while (result.next()) {
  21293. body.append(result.data(), result.size());
  21294. }
  21295. return body;
  21296. }
  21297. TEST(ClientConnectionTest, Basic) {
  21298. httplib::ClientConnection conn;
  21299. EXPECT_FALSE(conn.is_open());
  21300. conn.sock = 1;
  21301. EXPECT_TRUE(conn.is_open());
  21302. httplib::ClientConnection conn2(std::move(conn));
  21303. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21304. conn2.sock = INVALID_SOCKET;
  21305. }
  21306. // Unified test server for all stream::* tests
  21307. class StreamApiTest : public ::testing::Test {
  21308. protected:
  21309. void SetUp() override {
  21310. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21311. res.set_content("Hello World!", "text/plain");
  21312. });
  21313. svr_.Get("/echo-params",
  21314. [](const httplib::Request &req, httplib::Response &res) {
  21315. std::string r;
  21316. for (const auto &p : req.params) {
  21317. if (!r.empty()) r += "&";
  21318. r += p.first + "=" + p.second;
  21319. }
  21320. res.set_content(r, "text/plain");
  21321. });
  21322. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21323. res.set_content(req.body, req.get_header_value("Content-Type"));
  21324. });
  21325. svr_.Post("/echo-headers",
  21326. [](const httplib::Request &req, httplib::Response &res) {
  21327. std::string r;
  21328. for (const auto &h : req.headers)
  21329. r += h.first + ": " + h.second + "\n";
  21330. res.set_content(r, "text/plain");
  21331. });
  21332. svr_.Post("/echo-params",
  21333. [](const httplib::Request &req, httplib::Response &res) {
  21334. std::string r = "params:";
  21335. for (const auto &p : req.params)
  21336. r += p.first + "=" + p.second + ";";
  21337. res.set_content(r + " body:" + req.body, "text/plain");
  21338. });
  21339. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21340. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21341. });
  21342. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21343. res.set_content("PUT:" + req.body, "text/plain");
  21344. });
  21345. svr_.Patch("/echo",
  21346. [](const httplib::Request &req, httplib::Response &res) {
  21347. res.set_content("PATCH:" + req.body, "text/plain");
  21348. });
  21349. svr_.Delete(
  21350. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21351. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21352. "text/plain");
  21353. });
  21354. svr_.Get("/head-test",
  21355. [](const httplib::Request &, httplib::Response &res) {
  21356. res.set_content("body for HEAD", "text/plain");
  21357. });
  21358. svr_.Options("/options",
  21359. [](const httplib::Request &, httplib::Response &res) {
  21360. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21361. });
  21362. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21363. svr_.wait_until_ready();
  21364. }
  21365. void TearDown() override {
  21366. svr_.stop();
  21367. if (thread_.joinable()) thread_.join();
  21368. }
  21369. httplib::Server svr_;
  21370. std::thread thread_;
  21371. };
  21372. // stream::Get tests
  21373. TEST_F(StreamApiTest, GetBasic) {
  21374. httplib::Client cli(HOST, PORT);
  21375. auto result = httplib::stream::Get(cli, "/hello");
  21376. ASSERT_TRUE(result.is_valid());
  21377. EXPECT_EQ(200, result.status());
  21378. EXPECT_EQ("Hello World!", read_body(result));
  21379. }
  21380. TEST_F(StreamApiTest, GetWithParams) {
  21381. httplib::Client cli(HOST, PORT);
  21382. httplib::Params params{{"foo", "bar"}};
  21383. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21384. ASSERT_TRUE(result.is_valid());
  21385. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21386. }
  21387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21388. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21389. httplib::Client cli(HOST, PORT);
  21390. cli.set_payload_max_length(0);
  21391. auto result = httplib::stream::Get(cli, "/hello");
  21392. ASSERT_TRUE(result.is_valid());
  21393. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21394. EXPECT_EQ("Hello World!", read_body(result));
  21395. }
  21396. #endif
  21397. TEST_F(StreamApiTest, GetConnectionError) {
  21398. httplib::Client cli(HOST, 9999);
  21399. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21400. }
  21401. TEST_F(StreamApiTest, Get404) {
  21402. httplib::Client cli(HOST, PORT);
  21403. auto result = httplib::stream::Get(cli, "/nonexistent");
  21404. EXPECT_TRUE(result.is_valid());
  21405. EXPECT_EQ(404, result.status());
  21406. }
  21407. // stream::Post tests
  21408. TEST_F(StreamApiTest, PostBasic) {
  21409. httplib::Client cli(HOST, PORT);
  21410. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21411. "application/json");
  21412. ASSERT_TRUE(result.is_valid());
  21413. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21414. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21415. }
  21416. TEST_F(StreamApiTest, PostWithHeaders) {
  21417. httplib::Client cli(HOST, PORT);
  21418. httplib::Headers headers{{"X-Custom", "value"}};
  21419. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21420. "text/plain");
  21421. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21422. }
  21423. TEST_F(StreamApiTest, PostWithParams) {
  21424. httplib::Client cli(HOST, PORT);
  21425. httplib::Params params{{"k", "v"}};
  21426. auto result =
  21427. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21428. auto body = read_body(result);
  21429. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21430. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21431. }
  21432. TEST_F(StreamApiTest, PostLarge) {
  21433. httplib::Client cli(HOST, PORT);
  21434. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21435. size_t total = 0;
  21436. while (result.next()) {
  21437. total += result.size();
  21438. }
  21439. EXPECT_EQ(100u * 1024u, total);
  21440. }
  21441. // stream::Put/Patch tests
  21442. TEST_F(StreamApiTest, PutAndPatch) {
  21443. httplib::Client cli(HOST, PORT);
  21444. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21445. EXPECT_EQ("PUT:test", read_body(put));
  21446. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21447. EXPECT_EQ("PATCH:test", read_body(patch));
  21448. }
  21449. // stream::Delete tests
  21450. TEST_F(StreamApiTest, Delete) {
  21451. httplib::Client cli(HOST, PORT);
  21452. auto del1 = httplib::stream::Delete(cli, "/resource");
  21453. EXPECT_EQ("Deleted", read_body(del1));
  21454. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21455. EXPECT_EQ("Deleted:data", read_body(del2));
  21456. }
  21457. // stream::Head/Options tests
  21458. TEST_F(StreamApiTest, HeadAndOptions) {
  21459. httplib::Client cli(HOST, PORT);
  21460. auto head = httplib::stream::Head(cli, "/head-test");
  21461. EXPECT_TRUE(head.is_valid());
  21462. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21463. auto opts = httplib::stream::Options(cli, "/options");
  21464. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21465. }
  21466. // SSL stream::* tests
  21467. #ifdef CPPHTTPLIB_SSL_ENABLED
  21468. class SSLStreamApiTest : public ::testing::Test {
  21469. protected:
  21470. void SetUp() override {
  21471. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21472. res.set_content("Hello SSL!", "text/plain");
  21473. });
  21474. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21475. res.set_content(req.body, "text/plain");
  21476. });
  21477. port_ = svr_.bind_to_any_port("127.0.0.1");
  21478. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21479. svr_.wait_until_ready();
  21480. }
  21481. void TearDown() override {
  21482. svr_.stop();
  21483. if (thread_.joinable()) thread_.join();
  21484. }
  21485. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21486. std::thread thread_;
  21487. int port_ = 0;
  21488. };
  21489. TEST_F(SSLStreamApiTest, GetAndPost) {
  21490. httplib::SSLClient cli("127.0.0.1", port_);
  21491. cli.enable_server_certificate_verification(false);
  21492. auto get = httplib::stream::Get(cli, "/hello");
  21493. EXPECT_EQ("Hello SSL!", read_body(get));
  21494. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21495. EXPECT_EQ("test", read_body(post));
  21496. }
  21497. #endif
  21498. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21499. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21500. // BodyReader
  21501. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21502. // Test that read timeout during streaming is detected
  21503. // Use a large content-length response where server delays mid-stream
  21504. Server svr;
  21505. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21506. // Send a large response with delay in the middle
  21507. res.set_content_provider(
  21508. 1000, // content_length
  21509. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21510. if (offset < 100) {
  21511. // Send first 100 bytes immediately
  21512. std::string data(100, 'A');
  21513. sink.write(data.c_str(), data.size());
  21514. return true;
  21515. }
  21516. // Then delay longer than client timeout
  21517. std::this_thread::sleep_for(std::chrono::seconds(3));
  21518. std::string data(900, 'B');
  21519. sink.write(data.c_str(), data.size());
  21520. return true;
  21521. });
  21522. });
  21523. auto port = 8091;
  21524. std::thread t([&]() { svr.listen("localhost", port); });
  21525. svr.wait_until_ready();
  21526. Client cli("localhost", port);
  21527. cli.set_read_timeout(1, 0); // 1 second timeout
  21528. auto handle = cli.open_stream("GET", "/slow-stream");
  21529. ASSERT_TRUE(handle.is_valid());
  21530. char buf[256];
  21531. ssize_t total = 0;
  21532. ssize_t n;
  21533. bool got_error = false;
  21534. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21535. total += n;
  21536. }
  21537. if (n < 0) {
  21538. got_error = true;
  21539. // Should be timeout or read error
  21540. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21541. handle.get_read_error() == Error::Read)
  21542. << "Actual error: " << to_string(handle.get_read_error());
  21543. }
  21544. // Either we got an error, or we got less data than expected
  21545. EXPECT_TRUE(got_error || total < 1000)
  21546. << "Expected timeout but got all " << total << " bytes";
  21547. svr.stop();
  21548. t.join();
  21549. }
  21550. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21551. // Test connection closed detection via BodyReader
  21552. Server svr;
  21553. std::atomic<bool> close_now{false};
  21554. svr.Get("/will-close", [&](const Request &, Response &res) {
  21555. res.set_content_provider(
  21556. 10000, // Large content_length that we won't fully send
  21557. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21558. if (offset < 100) {
  21559. std::string data(100, 'X');
  21560. sink.write(data.c_str(), data.size());
  21561. return true;
  21562. }
  21563. // Wait for signal then abort
  21564. while (!close_now) {
  21565. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21566. }
  21567. return false; // Abort - server will close connection
  21568. });
  21569. });
  21570. auto port = 8092;
  21571. std::thread t([&]() { svr.listen("localhost", port); });
  21572. svr.wait_until_ready();
  21573. Client cli("localhost", port);
  21574. auto handle = cli.open_stream("GET", "/will-close");
  21575. ASSERT_TRUE(handle.is_valid());
  21576. char buf[256];
  21577. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21578. EXPECT_GT(n, 0) << "First read should succeed";
  21579. // Signal server to close
  21580. close_now = true;
  21581. // Keep reading until error or EOF
  21582. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21583. // Keep reading
  21584. }
  21585. // Should get an error since content_length wasn't satisfied
  21586. if (n < 0) {
  21587. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21588. handle.get_read_error() == Error::Read)
  21589. << "Actual error: " << to_string(handle.get_read_error());
  21590. }
  21591. svr.stop();
  21592. t.join();
  21593. }
  21594. #ifdef CPPHTTPLIB_SSL_ENABLED
  21595. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21596. // Test that read timeout during SSL streaming is detected
  21597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21598. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21599. res.set_content_provider(
  21600. 1000, "text/plain",
  21601. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21602. if (offset < 100) {
  21603. std::string data(100, 'A');
  21604. sink.write(data.c_str(), data.size());
  21605. return true;
  21606. }
  21607. std::this_thread::sleep_for(std::chrono::seconds(3));
  21608. std::string data(900, 'B');
  21609. sink.write(data.c_str(), data.size());
  21610. return true;
  21611. });
  21612. });
  21613. auto port = 8093;
  21614. std::thread t([&]() { svr.listen("localhost", port); });
  21615. svr.wait_until_ready();
  21616. SSLClient cli("localhost", port);
  21617. cli.enable_server_certificate_verification(false);
  21618. cli.set_read_timeout(1, 0); // 1 second timeout
  21619. auto handle = cli.open_stream("GET", "/slow-stream");
  21620. ASSERT_TRUE(handle.is_valid());
  21621. char buf[256];
  21622. ssize_t total = 0;
  21623. ssize_t n;
  21624. bool got_error = false;
  21625. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21626. total += n;
  21627. }
  21628. if (n < 0) {
  21629. got_error = true;
  21630. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21631. handle.get_read_error() == Error::Read)
  21632. << "Actual error: " << to_string(handle.get_read_error());
  21633. }
  21634. EXPECT_TRUE(got_error || total < 1000)
  21635. << "Expected timeout but got all " << total << " bytes";
  21636. svr.stop();
  21637. t.join();
  21638. }
  21639. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21640. // Test SSL connection closed detection
  21641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21642. std::atomic<bool> close_now{false};
  21643. svr.Get("/will-close", [&](const Request &, Response &res) {
  21644. res.set_content_provider(
  21645. 10000, "text/plain",
  21646. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21647. if (offset < 100) {
  21648. std::string data(100, 'X');
  21649. sink.write(data.c_str(), data.size());
  21650. return true;
  21651. }
  21652. while (!close_now) {
  21653. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21654. }
  21655. return false;
  21656. });
  21657. });
  21658. auto port = 8094;
  21659. std::thread t([&]() { svr.listen("localhost", port); });
  21660. svr.wait_until_ready();
  21661. SSLClient cli("localhost", port);
  21662. cli.enable_server_certificate_verification(false);
  21663. auto handle = cli.open_stream("GET", "/will-close");
  21664. ASSERT_TRUE(handle.is_valid());
  21665. char buf[256];
  21666. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21667. EXPECT_GT(n, 0);
  21668. // Signal server to close
  21669. close_now = true;
  21670. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21671. // Keep reading
  21672. }
  21673. if (n < 0) {
  21674. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21675. handle.get_read_error() == Error::Read)
  21676. << "Actual error: " << to_string(handle.get_read_error());
  21677. }
  21678. svr.stop();
  21679. t.join();
  21680. }
  21681. #endif
  21682. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21683. using namespace httplib;
  21684. // Create a test file
  21685. const char *fname = "etag_testfile.txt";
  21686. const char *content = "etag-content";
  21687. {
  21688. std::ofstream ofs(fname);
  21689. ofs << content;
  21690. ASSERT_TRUE(ofs.good());
  21691. }
  21692. Server svr;
  21693. svr.set_mount_point("/static", ".");
  21694. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21695. svr.wait_until_ready();
  21696. Client cli(HOST, PORT);
  21697. // First request: should get 200 with ETag header
  21698. auto res1 = cli.Get("/static/etag_testfile.txt");
  21699. ASSERT_TRUE(res1);
  21700. ASSERT_EQ(200, res1->status);
  21701. ASSERT_TRUE(res1->has_header("ETag"));
  21702. std::string etag = res1->get_header_value("ETag");
  21703. EXPECT_FALSE(etag.empty());
  21704. // Verify ETag format: W/"hex-hex"
  21705. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21706. EXPECT_EQ('W', etag[0]);
  21707. EXPECT_EQ('/', etag[1]);
  21708. EXPECT_EQ('"', etag[2]);
  21709. EXPECT_EQ('"', etag.back());
  21710. // Exact match: expect 304 Not Modified
  21711. Headers h2 = {{"If-None-Match", etag}};
  21712. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21713. ASSERT_TRUE(res2);
  21714. EXPECT_EQ(304, res2->status);
  21715. // Wildcard match: expect 304 Not Modified
  21716. Headers h3 = {{"If-None-Match", "*"}};
  21717. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21718. ASSERT_TRUE(res3);
  21719. EXPECT_EQ(304, res3->status);
  21720. // Non-matching ETag: expect 200
  21721. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21722. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21723. ASSERT_TRUE(res4);
  21724. EXPECT_EQ(200, res4->status);
  21725. // Multiple ETags with one matching: expect 304
  21726. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21727. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21728. ASSERT_TRUE(res5);
  21729. EXPECT_EQ(304, res5->status);
  21730. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21731. // that equivalent to the single comma-separated list above, so the match on
  21732. // the second line must still be found.
  21733. Headers h6;
  21734. h6.emplace("If-None-Match", "W/\"other\"");
  21735. h6.emplace("If-None-Match", etag);
  21736. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21737. ASSERT_TRUE(res6);
  21738. EXPECT_EQ(304, res6->status);
  21739. svr.stop();
  21740. t.join();
  21741. std::remove(fname);
  21742. }
  21743. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21744. using namespace httplib;
  21745. Server svr;
  21746. svr.set_mount_point("/static", ".");
  21747. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21748. svr.wait_until_ready();
  21749. Client cli(HOST, PORT);
  21750. // Send If-None-Match: * to a non-existent file
  21751. Headers h = {{"If-None-Match", "*"}};
  21752. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21754. EXPECT_EQ(404, res->status);
  21755. svr.stop();
  21756. t.join();
  21757. }
  21758. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21759. using namespace httplib;
  21760. // Create a test file
  21761. const char *fname = "etag_boundary_testfile.txt";
  21762. const char *content = "boundary-test";
  21763. {
  21764. std::ofstream ofs(fname);
  21765. ofs << content;
  21766. ASSERT_TRUE(ofs.good());
  21767. }
  21768. Server svr;
  21769. svr.set_mount_point("/static", ".");
  21770. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21771. svr.wait_until_ready();
  21772. Client cli(HOST, PORT);
  21773. // Get the actual ETag
  21774. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21775. ASSERT_TRUE(res1);
  21776. ASSERT_EQ(200, res1->status);
  21777. ASSERT_TRUE(res1->has_header("ETag"));
  21778. std::string etag = res1->get_header_value("ETag");
  21779. // Test 1: Very long ETag value (longer than actual ETag)
  21780. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21781. Headers h1 = {{"If-None-Match", "W/"
  21782. "\"very-long-etag-value-that-is-much-longer-"
  21783. "than-the-actual-etag-value\""}};
  21784. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21785. ASSERT_TRUE(res2);
  21786. EXPECT_EQ(200, res2->status); // Should not match
  21787. // Test 2: Long string followed by wildcard
  21788. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21789. // string)
  21790. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21791. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21792. ASSERT_TRUE(res3);
  21793. EXPECT_EQ(304, res3->status); // Should match on "*"
  21794. // Test 3: Wildcard followed by long string
  21795. // Should match on "*" immediately and return 304
  21796. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21797. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21798. ASSERT_TRUE(res4);
  21799. EXPECT_EQ(304, res4->status); // Should match on "*"
  21800. // Test 4: Multiple long non-matching values
  21801. // Should NOT match and return 200 (test that all comparisons are safe)
  21802. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21803. "W/\"second-long-non-matching-value\", "
  21804. "W/\"third-long-non-matching-value\""}};
  21805. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21806. ASSERT_TRUE(res5);
  21807. EXPECT_EQ(200, res5->status); // Should not match
  21808. // Test 5: Single character that is not "*" (edge case)
  21809. Headers h5 = {{"If-None-Match", "X"}};
  21810. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21811. ASSERT_TRUE(res6);
  21812. EXPECT_EQ(200, res6->status); // Should not match
  21813. svr.stop();
  21814. t.join();
  21815. std::remove(fname);
  21816. }
  21817. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21818. using namespace httplib;
  21819. // Create a test file
  21820. const char *fname = "ims_testfile.txt";
  21821. const char *content = "if-modified-since-test";
  21822. {
  21823. std::ofstream ofs(fname);
  21824. ofs << content;
  21825. ASSERT_TRUE(ofs.good());
  21826. }
  21827. Server svr;
  21828. svr.set_mount_point("/static", ".");
  21829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21830. svr.wait_until_ready();
  21831. Client cli(HOST, PORT);
  21832. // First request: should get 200 with Last-Modified header
  21833. auto res1 = cli.Get("/static/ims_testfile.txt");
  21834. ASSERT_TRUE(res1);
  21835. ASSERT_EQ(200, res1->status);
  21836. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21837. std::string last_modified = res1->get_header_value("Last-Modified");
  21838. EXPECT_FALSE(last_modified.empty());
  21839. // If-Modified-Since with same time: expect 304
  21840. Headers h2 = {{"If-Modified-Since", last_modified}};
  21841. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21842. ASSERT_TRUE(res2);
  21843. EXPECT_EQ(304, res2->status);
  21844. // If-Modified-Since with future time: expect 304
  21845. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21846. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21847. ASSERT_TRUE(res3);
  21848. EXPECT_EQ(304, res3->status);
  21849. // If-Modified-Since with past time: expect 200
  21850. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21851. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21852. ASSERT_TRUE(res4);
  21853. EXPECT_EQ(200, res4->status);
  21854. // If-None-Match takes precedence over If-Modified-Since
  21855. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21856. ASSERT_TRUE(res1->has_header("ETag"));
  21857. std::string etag = res1->get_header_value("ETag");
  21858. Headers h5 = {{"If-None-Match", etag},
  21859. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21860. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21861. ASSERT_TRUE(res5);
  21862. EXPECT_EQ(304, res5->status);
  21863. svr.stop();
  21864. t.join();
  21865. std::remove(fname);
  21866. }
  21867. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21868. using namespace httplib;
  21869. Server svr;
  21870. // Endpoint that returns compressible content
  21871. svr.Get("/compressible", [](const Request &, Response &res) {
  21872. // Return a large enough body to trigger compression
  21873. std::string body(1000, 'a');
  21874. res.set_content(body, "text/plain");
  21875. });
  21876. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21877. svr.wait_until_ready();
  21878. Client cli(HOST, PORT);
  21879. // Request with gzip support: should get Vary header when compressed
  21880. cli.set_compress(true);
  21881. auto res1 = cli.Get("/compressible");
  21882. ASSERT_TRUE(res1);
  21883. EXPECT_EQ(200, res1->status);
  21884. // If Content-Encoding is set, Vary should also be set
  21885. if (res1->has_header("Content-Encoding")) {
  21886. EXPECT_TRUE(res1->has_header("Vary"));
  21887. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21888. }
  21889. // Request without Accept-Encoding header: should not have compression
  21890. Headers h_no_compress;
  21891. auto res2 = cli.Get("/compressible", h_no_compress);
  21892. ASSERT_TRUE(res2);
  21893. EXPECT_EQ(200, res2->status);
  21894. // Verify Vary header is present when compression is applied
  21895. // (the exact behavior depends on server configuration)
  21896. svr.stop();
  21897. t.join();
  21898. }
  21899. TEST(ETagTest, IfRangeWithETag) {
  21900. using namespace httplib;
  21901. // Create a test file with known content
  21902. const char *fname = "if_range_testfile.txt";
  21903. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21904. {
  21905. std::ofstream ofs(fname);
  21906. ofs << content;
  21907. ASSERT_TRUE(ofs.good());
  21908. }
  21909. Server svr;
  21910. svr.set_mount_point("/static", ".");
  21911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21912. svr.wait_until_ready();
  21913. Client cli(HOST, PORT);
  21914. // First request: get ETag
  21915. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21916. ASSERT_TRUE(res1);
  21917. ASSERT_EQ(200, res1->status);
  21918. ASSERT_TRUE(res1->has_header("ETag"));
  21919. std::string etag = res1->get_header_value("ETag");
  21920. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21921. // Since our server generates weak ETags (W/"..."), If-Range with our
  21922. // ETag should NOT result in partial content - it should return full content.
  21923. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21924. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21925. ASSERT_TRUE(res2);
  21926. // Weak ETag in If-Range -> full content (200), not partial (206)
  21927. EXPECT_EQ(200, res2->status);
  21928. EXPECT_EQ(content, res2->body);
  21929. EXPECT_FALSE(res2->has_header("Content-Range"));
  21930. // Range request with non-matching If-Range (ETag): should get 200 (full
  21931. // content)
  21932. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21933. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21934. ASSERT_TRUE(res3);
  21935. EXPECT_EQ(200, res3->status);
  21936. EXPECT_EQ(content, res3->body);
  21937. EXPECT_FALSE(res3->has_header("Content-Range"));
  21938. // Range request with strong ETag (hypothetical - our server doesn't generate
  21939. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21940. // should return full content)
  21941. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21942. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21943. ASSERT_TRUE(res4);
  21944. EXPECT_EQ(200, res4->status);
  21945. EXPECT_EQ(content, res4->body);
  21946. EXPECT_FALSE(res4->has_header("Content-Range"));
  21947. svr.stop();
  21948. t.join();
  21949. std::remove(fname);
  21950. }
  21951. TEST(ETagTest, IfRangeWithDate) {
  21952. using namespace httplib;
  21953. // Create a test file
  21954. const char *fname = "if_range_date_testfile.txt";
  21955. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21956. {
  21957. std::ofstream ofs(fname);
  21958. ofs << content;
  21959. ASSERT_TRUE(ofs.good());
  21960. }
  21961. Server svr;
  21962. svr.set_mount_point("/static", ".");
  21963. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21964. svr.wait_until_ready();
  21965. Client cli(HOST, PORT);
  21966. // First request: get Last-Modified
  21967. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21968. ASSERT_TRUE(res1);
  21969. ASSERT_EQ(200, res1->status);
  21970. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21971. std::string last_modified = res1->get_header_value("Last-Modified");
  21972. // Range request with matching If-Range (date): should get 206
  21973. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21974. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21975. ASSERT_TRUE(res2);
  21976. EXPECT_EQ(206, res2->status);
  21977. EXPECT_EQ("FGHIJ", res2->body);
  21978. // Range request with old If-Range date: should get 200 (full content)
  21979. Headers h3 = {{"Range", "bytes=5-9"},
  21980. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21981. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21982. ASSERT_TRUE(res3);
  21983. EXPECT_EQ(200, res3->status);
  21984. EXPECT_EQ(content, res3->body);
  21985. // Range request with future If-Range date: should get 206
  21986. Headers h4 = {{"Range", "bytes=0-4"},
  21987. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21988. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21989. ASSERT_TRUE(res4);
  21990. EXPECT_EQ(206, res4->status);
  21991. EXPECT_EQ("ABCDE", res4->body);
  21992. svr.stop();
  21993. t.join();
  21994. std::remove(fname);
  21995. }
  21996. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21997. using namespace httplib;
  21998. const char *fname = "etag_malformed.txt";
  21999. const char *content = "malformed-etag";
  22000. {
  22001. std::ofstream ofs(fname);
  22002. ofs << content;
  22003. ASSERT_TRUE(ofs.good());
  22004. }
  22005. Server svr;
  22006. svr.set_mount_point("/static", ".");
  22007. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22008. svr.wait_until_ready();
  22009. Client cli(HOST, PORT);
  22010. // baseline: should get 200 and an ETag
  22011. auto res1 = cli.Get("/static/etag_malformed.txt");
  22012. ASSERT_TRUE(res1);
  22013. ASSERT_EQ(200, res1->status);
  22014. ASSERT_TRUE(res1->has_header("ETag"));
  22015. // Malformed ETag value (missing quotes) should be treated as non-matching
  22016. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22017. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22018. ASSERT_TRUE(res_bad);
  22019. EXPECT_EQ(200, res_bad->status);
  22020. // Whitespace-only header value should be considered invalid / non-matching
  22021. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22022. "Host: localhost\r\n"
  22023. "If-None-Match: \r\n"
  22024. "Connection: close\r\n"
  22025. "\r\n";
  22026. std::string out;
  22027. ASSERT_TRUE(send_request(5, raw_req, &out));
  22028. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22029. svr.stop();
  22030. t.join();
  22031. std::remove(fname);
  22032. }
  22033. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22034. using namespace httplib;
  22035. const char *fname = "ims_invalid_format.txt";
  22036. const char *content = "ims-bad-format";
  22037. {
  22038. std::ofstream ofs(fname);
  22039. ofs << content;
  22040. ASSERT_TRUE(ofs.good());
  22041. }
  22042. Server svr;
  22043. svr.set_mount_point("/static", ".");
  22044. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22045. svr.wait_until_ready();
  22046. Client cli(HOST, PORT);
  22047. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22048. ASSERT_TRUE(res1);
  22049. ASSERT_EQ(200, res1->status);
  22050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22051. // If-Modified-Since with invalid format should not result in 304
  22052. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22053. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22054. ASSERT_TRUE(res_bad);
  22055. EXPECT_EQ(200, res_bad->status);
  22056. // If-Range with invalid date format should be treated as mismatch -> full
  22057. // content (200)
  22058. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22059. {"If-Range", "invalid-date"}};
  22060. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22061. ASSERT_TRUE(res_ifrange);
  22062. EXPECT_EQ(200, res_ifrange->status);
  22063. svr.stop();
  22064. t.join();
  22065. std::remove(fname);
  22066. }
  22067. TEST(ETagTest, IfRangeWithMalformedETag) {
  22068. using namespace httplib;
  22069. const char *fname = "ifrange_malformed.txt";
  22070. const std::string content = "0123456789";
  22071. {
  22072. std::ofstream ofs(fname);
  22073. ofs << content;
  22074. ASSERT_TRUE(ofs.good());
  22075. }
  22076. Server svr;
  22077. svr.set_mount_point("/static", ".");
  22078. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22079. svr.wait_until_ready();
  22080. Client cli(HOST, PORT);
  22081. // First request: get ETag
  22082. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22083. ASSERT_TRUE(res1);
  22084. ASSERT_EQ(200, res1->status);
  22085. ASSERT_TRUE(res1->has_header("ETag"));
  22086. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22087. // full content (200)
  22088. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22089. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22090. ASSERT_TRUE(res2);
  22091. EXPECT_EQ(200, res2->status);
  22092. EXPECT_EQ(content, res2->body);
  22093. svr.stop();
  22094. t.join();
  22095. std::remove(fname);
  22096. }
  22097. TEST(ETagTest, ExtremeLargeDateValues) {
  22098. using namespace httplib;
  22099. const char *fname = "ims_extreme_date.txt";
  22100. const char *content = "ims-extreme-date";
  22101. {
  22102. std::ofstream ofs(fname);
  22103. ofs << content;
  22104. ASSERT_TRUE(ofs.good());
  22105. }
  22106. Server svr;
  22107. svr.set_mount_point("/static", ".");
  22108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22109. svr.wait_until_ready();
  22110. Client cli(HOST, PORT);
  22111. auto res1 = cli.Get(std::string("/static/") + fname);
  22112. ASSERT_TRUE(res1);
  22113. ASSERT_EQ(200, res1->status);
  22114. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22115. // Extremely large year that may overflow date parsing routines.
  22116. Headers h_large_date = {
  22117. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22118. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22119. ASSERT_TRUE(res_bad);
  22120. // Expect server to treat this as invalid/mismatch and return full content
  22121. EXPECT_EQ(200, res_bad->status);
  22122. // If-Range with extremely large date should be treated as mismatch -> full
  22123. // content (200)
  22124. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22125. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22126. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22127. ASSERT_TRUE(res_ifrange);
  22128. EXPECT_EQ(200, res_ifrange->status);
  22129. svr.stop();
  22130. t.join();
  22131. std::remove(fname);
  22132. }
  22133. TEST(ETagTest, NegativeFileModificationTime) {
  22134. using namespace httplib;
  22135. const char *fname = "ims_negative_mtime.txt";
  22136. const std::string content = "negative-mtime";
  22137. {
  22138. std::ofstream ofs(fname);
  22139. ofs << content;
  22140. ASSERT_TRUE(ofs.good());
  22141. }
  22142. // Try to set file mtime to a negative value. This may fail on some
  22143. // platforms/filesystems; if it fails, the test will still verify server
  22144. // behaves safely by performing a regular conditional request.
  22145. #if defined(__APPLE__) || defined(__linux__)
  22146. bool set_negative = false;
  22147. do {
  22148. struct timeval times[2];
  22149. // access time: now
  22150. times[0].tv_sec = time(nullptr);
  22151. times[0].tv_usec = 0;
  22152. // modification time: negative (e.g., -1)
  22153. times[1].tv_sec = -1;
  22154. times[1].tv_usec = 0;
  22155. if (utimes(fname, times) == 0) { set_negative = true; }
  22156. } while (0);
  22157. #else
  22158. bool set_negative = false;
  22159. #endif
  22160. Server svr;
  22161. svr.set_mount_point("/static", ".");
  22162. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22163. svr.wait_until_ready();
  22164. Client cli(HOST, PORT);
  22165. auto res1 = cli.Get(std::string("/static/") + fname);
  22166. ASSERT_TRUE(res1);
  22167. ASSERT_EQ(200, res1->status);
  22168. bool has_last_modified = res1->has_header("Last-Modified");
  22169. std::string last_modified;
  22170. if (has_last_modified) {
  22171. last_modified = res1->get_header_value("Last-Modified");
  22172. }
  22173. if (set_negative) {
  22174. // If we successfully set a negative mtime, ensure server returns a
  22175. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22176. // with an old date and ensure server handles it without crash.
  22177. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22178. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22179. ASSERT_TRUE(res2);
  22180. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22181. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22182. } else {
  22183. // Could not set negative mtime on this platform; fall back to verifying
  22184. // that normal invalid/malformed dates are treated safely (non-304).
  22185. Headers h_bad_date = {
  22186. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22187. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22188. ASSERT_TRUE(res_bad);
  22189. EXPECT_EQ(200, res_bad->status);
  22190. }
  22191. svr.stop();
  22192. t.join();
  22193. std::remove(fname);
  22194. }
  22195. //==============================================================================
  22196. // Integration Tests with Server
  22197. //==============================================================================
  22198. class SSEIntegrationTest : public ::testing::Test {
  22199. protected:
  22200. void SetUp() override {
  22201. stop_server_.store(false);
  22202. events_.clear();
  22203. server_ = httplib::detail::make_unique<Server>();
  22204. setup_server();
  22205. start_server();
  22206. }
  22207. void TearDown() override {
  22208. stop_server_.store(true);
  22209. event_cv_.notify_all();
  22210. server_->stop();
  22211. if (server_thread_.joinable()) { server_thread_.join(); }
  22212. }
  22213. void setup_server() {
  22214. // Simple SSE endpoint
  22215. server_->Get("/events", [this](const Request &req, Response &res) {
  22216. auto last_id = req.get_header_value("Last-Event-ID");
  22217. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22218. res.set_chunked_content_provider(
  22219. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22220. std::unique_lock<std::mutex> lock(event_mutex_);
  22221. if (event_cv_.wait_for(
  22222. lock, std::chrono::milliseconds(200), [this] {
  22223. return !events_.empty() || stop_server_.load();
  22224. })) {
  22225. if (stop_server_.load()) { return false; }
  22226. if (!events_.empty()) {
  22227. std::string event = events_.front();
  22228. events_.erase(events_.begin());
  22229. sink.write(event.data(), event.size());
  22230. return true;
  22231. }
  22232. }
  22233. return !stop_server_.load();
  22234. });
  22235. });
  22236. // Endpoint that returns error
  22237. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22238. res.status = 500;
  22239. res.set_content("Internal Server Error", "text/plain");
  22240. });
  22241. // Endpoint for custom event types
  22242. server_->Get("/custom-events", [](const Request &, Response &res) {
  22243. res.set_chunked_content_provider(
  22244. "text/event-stream", [](size_t offset, DataSink &sink) {
  22245. if (offset == 0) {
  22246. std::string event = "event: update\ndata: updated\n\n"
  22247. "event: delete\ndata: deleted\n\n";
  22248. sink.write(event.data(), event.size());
  22249. }
  22250. return false; // End stream after sending
  22251. });
  22252. });
  22253. }
  22254. void start_server() {
  22255. port_ = server_->bind_to_any_port(HOST);
  22256. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22257. // Wait for server to start
  22258. while (!server_->is_running()) {
  22259. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22260. }
  22261. }
  22262. int get_port() const { return port_; }
  22263. void send_event(const std::string &event) {
  22264. std::lock_guard<std::mutex> lock(event_mutex_);
  22265. events_.push_back(event);
  22266. event_cv_.notify_all();
  22267. }
  22268. std::unique_ptr<Server> server_;
  22269. std::thread server_thread_;
  22270. std::mutex event_mutex_;
  22271. std::condition_variable event_cv_;
  22272. std::vector<std::string> events_;
  22273. std::atomic<bool> stop_server_{false};
  22274. std::string last_received_event_id_;
  22275. int port_ = 0;
  22276. };
  22277. //==============================================================================
  22278. // SSE Parsing Tests
  22279. //==============================================================================
  22280. class SSEParsingTest : public SSEIntegrationTest {
  22281. protected:
  22282. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22283. // A trailing sentinel event tells when the whole stream has been parsed.
  22284. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22285. auto body = stream + "event: end\ndata: end\n\n";
  22286. server_->Get("/parse", [body](const Request &, Response &res) {
  22287. res.set_content(body, "text/event-stream");
  22288. });
  22289. return collect("/parse");
  22290. }
  22291. // Runs SSEClient against path until an "end" event arrives and returns the
  22292. // messages dispatched before it
  22293. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22294. Client client(HOST, get_port());
  22295. sse::SSEClient sse(client, path);
  22296. std::mutex mutex;
  22297. std::condition_variable cv;
  22298. std::vector<sse::SSEMessage> messages;
  22299. auto done = false;
  22300. sse.on_message([&](const sse::SSEMessage &msg) {
  22301. std::lock_guard<std::mutex> lock(mutex);
  22302. // Ignore a replay from a reconnect that races with stop()
  22303. if (!done) { messages.push_back(msg); }
  22304. });
  22305. sse.on_event("end", [&](const sse::SSEMessage &) {
  22306. std::lock_guard<std::mutex> lock(mutex);
  22307. done = true;
  22308. cv.notify_all();
  22309. });
  22310. sse.set_reconnect_interval(100);
  22311. sse.start_async();
  22312. {
  22313. std::unique_lock<std::mutex> lock(mutex);
  22314. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22315. }
  22316. sse.stop();
  22317. EXPECT_TRUE(done);
  22318. return messages;
  22319. }
  22320. };
  22321. TEST_F(SSEParsingTest, SingleLineData) {
  22322. auto msgs = parse("data: hello\n\n");
  22323. ASSERT_EQ(msgs.size(), 1u);
  22324. EXPECT_EQ(msgs[0].data, "hello");
  22325. EXPECT_EQ(msgs[0].event, "message");
  22326. }
  22327. TEST_F(SSEParsingTest, MultiLineData) {
  22328. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22329. ASSERT_EQ(msgs.size(), 1u);
  22330. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22331. }
  22332. TEST_F(SSEParsingTest, CustomEventType) {
  22333. auto msgs = parse("event: update\ndata: payload\n\n");
  22334. ASSERT_EQ(msgs.size(), 1u);
  22335. EXPECT_EQ(msgs[0].event, "update");
  22336. EXPECT_EQ(msgs[0].data, "payload");
  22337. }
  22338. TEST_F(SSEParsingTest, EventIdHandling) {
  22339. auto msgs = parse("id: 12345\ndata: test\n\n");
  22340. ASSERT_EQ(msgs.size(), 1u);
  22341. EXPECT_EQ(msgs[0].id, "12345");
  22342. }
  22343. TEST_F(SSEParsingTest, EmptyEventId) {
  22344. auto msgs = parse("id:\ndata: test\n\n");
  22345. ASSERT_EQ(msgs.size(), 1u);
  22346. EXPECT_EQ(msgs[0].id, "");
  22347. }
  22348. TEST_F(SSEParsingTest, CommentsIgnored) {
  22349. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22350. ASSERT_EQ(msgs.size(), 1u);
  22351. EXPECT_EQ(msgs[0].data, "hello");
  22352. EXPECT_EQ(msgs[0].event, "message");
  22353. }
  22354. TEST_F(SSEParsingTest, ColonInValue) {
  22355. auto msgs = parse("data: hello:world:test\n\n");
  22356. ASSERT_EQ(msgs.size(), 1u);
  22357. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22358. }
  22359. TEST_F(SSEParsingTest, FieldNameOnly) {
  22360. // A line without a colon is a field name with an empty value
  22361. auto msgs = parse("data\n\n");
  22362. ASSERT_EQ(msgs.size(), 1u);
  22363. EXPECT_EQ(msgs[0].data, "");
  22364. }
  22365. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22366. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22367. ASSERT_EQ(msgs.size(), 1u);
  22368. EXPECT_EQ(msgs[0].event, "update");
  22369. EXPECT_EQ(msgs[0].data, "hello");
  22370. }
  22371. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22372. auto msgs = parse("data\r\n\r\n");
  22373. ASSERT_EQ(msgs.size(), 1u);
  22374. EXPECT_EQ(msgs[0].data, "");
  22375. }
  22376. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22377. auto msgs = parse("event: update\rdata: hello\r\r");
  22378. ASSERT_EQ(msgs.size(), 1u);
  22379. EXPECT_EQ(msgs[0].event, "update");
  22380. EXPECT_EQ(msgs[0].data, "hello");
  22381. }
  22382. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22383. // Chunk boundaries fall inside every \r\n and right before the first one
  22384. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22385. "\n\r", "\nevent: end\ndata: end\n\n"};
  22386. server_->Get("/split", [chunks](const Request &, Response &res) {
  22387. auto i = std::make_shared<size_t>(0);
  22388. res.set_chunked_content_provider(
  22389. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22390. if (*i == chunks.size()) {
  22391. sink.done();
  22392. } else {
  22393. sink.write(chunks[*i].data(), chunks[*i].size());
  22394. (*i)++;
  22395. }
  22396. return true;
  22397. });
  22398. });
  22399. auto msgs = collect("/split");
  22400. ASSERT_EQ(msgs.size(), 1u);
  22401. EXPECT_EQ(msgs[0].event, "update");
  22402. EXPECT_EQ(msgs[0].data, "hello");
  22403. }
  22404. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22405. // Only a BOM at the start of the stream is ignored
  22406. auto msgs = parse("\xEF\xBB\xBF"
  22407. "data: first\n\n"
  22408. "\xEF\xBB\xBF"
  22409. "data: second\n\n");
  22410. ASSERT_EQ(msgs.size(), 1u);
  22411. EXPECT_EQ(msgs[0].data, "first");
  22412. }
  22413. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22414. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22415. ASSERT_EQ(msgs.size(), 1u);
  22416. EXPECT_EQ(msgs[0].data, "hello");
  22417. EXPECT_EQ(msgs[0].event, "message");
  22418. }
  22419. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22420. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22421. ASSERT_EQ(msgs.size(), 2u);
  22422. EXPECT_EQ(msgs[0].data, "hello");
  22423. EXPECT_EQ(msgs[1].data, "hello");
  22424. }
  22425. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22426. // An event without data is not dispatched, and its type must not leak
  22427. // into the next event
  22428. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22429. ASSERT_EQ(msgs.size(), 1u);
  22430. EXPECT_EQ(msgs[0].event, "message");
  22431. EXPECT_EQ(msgs[0].data, "hello");
  22432. }
  22433. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22434. // Also when the empty field replaces an earlier type
  22435. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22436. ASSERT_EQ(msgs.size(), 2u);
  22437. EXPECT_EQ(msgs[0].event, "message");
  22438. EXPECT_EQ(msgs[1].event, "message");
  22439. }
  22440. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22441. // The first connection sends only an id; the second echoes back the
  22442. // Last-Event-ID it was reconnected with
  22443. std::atomic<int> connection_count{0};
  22444. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22445. if (connection_count++ == 0) {
  22446. res.set_content("id: 42\n\n", "text/event-stream");
  22447. } else {
  22448. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22449. "\n\nevent: end\ndata: end\n\n",
  22450. "text/event-stream");
  22451. }
  22452. });
  22453. auto msgs = collect("/id-only");
  22454. ASSERT_EQ(msgs.size(), 1u);
  22455. EXPECT_EQ(msgs[0].data, "42");
  22456. }
  22457. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22458. // The first connection sets an id and then clears it with an empty one; the
  22459. // second reports whether it was reconnected with a Last-Event-ID
  22460. std::atomic<int> connection_count{0};
  22461. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22462. if (connection_count++ == 0) {
  22463. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22464. "text/event-stream");
  22465. } else {
  22466. res.set_content(
  22467. std::string("data: ") +
  22468. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22469. "\n\nevent: end\ndata: end\n\n",
  22470. "text/event-stream");
  22471. }
  22472. });
  22473. auto msgs = collect("/id-clear");
  22474. ASSERT_EQ(msgs.size(), 3u);
  22475. EXPECT_EQ(msgs[0].id, "1");
  22476. EXPECT_EQ(msgs[1].id, "");
  22477. EXPECT_EQ(msgs[2].data, "not sent");
  22478. }
  22479. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22480. // The first connection sets an id and then sends ids that cannot be carried
  22481. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22482. // with
  22483. std::atomic<int> connection_count{0};
  22484. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22485. if (connection_count++ == 0) {
  22486. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22487. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22488. "text/event-stream");
  22489. } else {
  22490. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22491. "\n\nevent: end\ndata: end\n\n",
  22492. "text/event-stream");
  22493. }
  22494. });
  22495. auto msgs = collect("/id-unsendable");
  22496. ASSERT_EQ(msgs.size(), 1u);
  22497. EXPECT_EQ(msgs[0].data, "42");
  22498. }
  22499. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22500. auto msgs = parse("event: notification\nid: evt-42\n"
  22501. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22502. ASSERT_EQ(msgs.size(), 1u);
  22503. EXPECT_EQ(msgs[0].event, "notification");
  22504. EXPECT_EQ(msgs[0].id, "evt-42");
  22505. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22506. }
  22507. TEST(SSEMessageTest, Clear) {
  22508. sse::SSEMessage msg;
  22509. msg.event = "custom";
  22510. msg.data = "some data";
  22511. msg.id = "123";
  22512. msg.clear();
  22513. EXPECT_EQ(msg.event, "message");
  22514. EXPECT_EQ(msg.data, "");
  22515. EXPECT_EQ(msg.id, "");
  22516. }
  22517. //==============================================================================
  22518. // SSE Integration Tests
  22519. //==============================================================================
  22520. // Test: Successful connection and on_open callback
  22521. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22522. // Add a simple endpoint that sends one event and closes
  22523. server_->Get("/simple-event", [](const Request &, Response &res) {
  22524. res.set_chunked_content_provider(
  22525. "text/event-stream", [](size_t offset, DataSink &sink) {
  22526. if (offset == 0) {
  22527. std::string event = "data: hello\n\n";
  22528. sink.write(event.data(), event.size());
  22529. }
  22530. return false; // Close stream after sending
  22531. });
  22532. });
  22533. Client client("localhost", get_port());
  22534. sse::SSEClient sse(client, "/simple-event");
  22535. std::atomic<bool> open_called{false};
  22536. std::atomic<bool> message_received{false};
  22537. sse.on_open([&open_called]() { open_called.store(true); });
  22538. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22539. if (msg.data == "hello") { message_received.store(true); }
  22540. });
  22541. sse.set_reconnect_interval(100);
  22542. sse.set_max_reconnect_attempts(1);
  22543. // Start async
  22544. sse.start_async();
  22545. // Wait for message to be processed
  22546. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22547. sse.stop();
  22548. EXPECT_TRUE(open_called.load());
  22549. EXPECT_TRUE(message_received.load());
  22550. }
  22551. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22552. // A data line that never ends.
  22553. server_->Get("/endless-line", [](const Request &, Response &res) {
  22554. res.set_chunked_content_provider(
  22555. "text/event-stream", [](size_t offset, DataSink &sink) {
  22556. if (offset == 0) { sink.write("data: ", 6); }
  22557. std::string chunk(64 * 1024, 'A');
  22558. return sink.write(chunk.data(), chunk.size());
  22559. });
  22560. });
  22561. Client client("localhost", get_port());
  22562. sse::SSEClient sse(client, "/endless-line");
  22563. std::atomic<bool> too_long{false};
  22564. sse.on_error([&](Error err) {
  22565. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22566. });
  22567. sse.set_max_reconnect_attempts(1);
  22568. sse.start_async();
  22569. for (int i = 0; i < 500 && !too_long; i++) {
  22570. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22571. }
  22572. sse.stop();
  22573. EXPECT_TRUE(too_long);
  22574. }
  22575. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22576. // Far more in all than the client's payload limit below.
  22577. server_->Get("/many-events", [](const Request &, Response &res) {
  22578. res.set_chunked_content_provider(
  22579. "text/event-stream", [](size_t offset, DataSink &sink) {
  22580. if (offset == 0) {
  22581. std::string events;
  22582. for (int i = 0; i < 1000; i++) {
  22583. events += "data: message\n\n";
  22584. }
  22585. sink.write(events.data(), events.size());
  22586. }
  22587. return false;
  22588. });
  22589. });
  22590. Client client("localhost", get_port());
  22591. client.set_payload_max_length(1024);
  22592. sse::SSEClient sse(client, "/many-events");
  22593. std::atomic<int> messages{0};
  22594. std::atomic<bool> too_large{false};
  22595. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22596. sse.on_error([&](Error err) {
  22597. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22598. });
  22599. sse.set_max_reconnect_attempts(1);
  22600. sse.start_async();
  22601. for (int i = 0; i < 500 && messages < 1000; i++) {
  22602. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22603. }
  22604. sse.stop();
  22605. EXPECT_GE(messages.load(), 1000);
  22606. EXPECT_FALSE(too_large);
  22607. }
  22608. // Test: on_message callback
  22609. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22610. // Endpoint that sends multiple events then closes
  22611. server_->Get("/multi-event", [](const Request &, Response &res) {
  22612. res.set_chunked_content_provider(
  22613. "text/event-stream", [](size_t offset, DataSink &sink) {
  22614. if (offset == 0) {
  22615. std::string events = "data: message1\n\ndata: message2\n\n";
  22616. sink.write(events.data(), events.size());
  22617. }
  22618. return false;
  22619. });
  22620. });
  22621. Client client("localhost", get_port());
  22622. sse::SSEClient sse(client, "/multi-event");
  22623. std::vector<std::string> received_messages;
  22624. std::mutex messages_mutex;
  22625. sse.on_message([&](const sse::SSEMessage &msg) {
  22626. std::lock_guard<std::mutex> lock(messages_mutex);
  22627. received_messages.push_back(msg.data);
  22628. });
  22629. sse.set_reconnect_interval(100);
  22630. sse.set_max_reconnect_attempts(1);
  22631. sse.start_async();
  22632. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22633. sse.stop();
  22634. std::lock_guard<std::mutex> lock(messages_mutex);
  22635. EXPECT_GE(received_messages.size(), 2u);
  22636. if (received_messages.size() >= 2) {
  22637. EXPECT_EQ(received_messages[0], "message1");
  22638. EXPECT_EQ(received_messages[1], "message2");
  22639. }
  22640. }
  22641. // Test: on_event for specific types
  22642. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22643. Client client("localhost", get_port());
  22644. sse::SSEClient sse(client, "/custom-events");
  22645. std::atomic<bool> update_received{false};
  22646. std::atomic<bool> delete_received{false};
  22647. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22648. if (msg.data == "updated") { update_received.store(true); }
  22649. });
  22650. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22651. if (msg.data == "deleted") { delete_received.store(true); }
  22652. });
  22653. sse.set_max_reconnect_attempts(1);
  22654. sse.start_async();
  22655. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22656. sse.stop();
  22657. EXPECT_TRUE(update_received.load());
  22658. EXPECT_TRUE(delete_received.load());
  22659. }
  22660. // Test: on_error callback on connection failure
  22661. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22662. // Connect to a non-existent port
  22663. Client client("localhost", 59999);
  22664. sse::SSEClient sse(client, "/events");
  22665. std::atomic<bool> error_called{false};
  22666. Error received_error = Error::Success;
  22667. sse.on_error([&](Error err) {
  22668. error_called.store(true);
  22669. received_error = err;
  22670. });
  22671. sse.set_reconnect_interval(50);
  22672. sse.set_max_reconnect_attempts(1);
  22673. sse.start_async();
  22674. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22675. sse.stop();
  22676. EXPECT_TRUE(error_called.load());
  22677. EXPECT_NE(received_error, Error::Success);
  22678. }
  22679. // Test: Last-Event-ID header sent on reconnect
  22680. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22681. // Endpoint that sends event with ID
  22682. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22683. res.set_chunked_content_provider(
  22684. "text/event-stream", [](size_t offset, DataSink &sink) {
  22685. if (offset == 0) {
  22686. std::string event = "id: evt-123\ndata: test\n\n";
  22687. sink.write(event.data(), event.size());
  22688. }
  22689. return false;
  22690. });
  22691. });
  22692. Client client("localhost", get_port());
  22693. sse::SSEClient sse(client, "/event-with-id");
  22694. std::atomic<bool> id_received{false};
  22695. sse.on_message([&](const sse::SSEMessage &msg) {
  22696. if (!msg.id.empty()) { id_received.store(true); }
  22697. });
  22698. sse.set_reconnect_interval(100);
  22699. sse.set_max_reconnect_attempts(1);
  22700. sse.start_async();
  22701. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22702. sse.stop();
  22703. EXPECT_TRUE(id_received.load());
  22704. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22705. }
  22706. // Test: last_event_id() read from another thread while start_async() runs
  22707. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22708. // Ids of every length up to 200, so the stored id keeps changing size
  22709. server_->Get("/many-ids", [](const Request &, Response &res) {
  22710. res.set_chunked_content_provider(
  22711. "text/event-stream", [](size_t offset, DataSink &sink) {
  22712. if (offset == 0) {
  22713. std::string events;
  22714. for (size_t i = 0; i < 2000; i++) {
  22715. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22716. events += "data: x\n\n";
  22717. }
  22718. events += "id: end\ndata: x\n\n";
  22719. sink.write(events.data(), events.size());
  22720. }
  22721. return false;
  22722. });
  22723. });
  22724. Client client("localhost", get_port());
  22725. sse::SSEClient sse(client, "/many-ids");
  22726. // Wait out the rest of the test rather than replay the stream
  22727. sse.set_reconnect_interval(10000);
  22728. sse.set_max_reconnect_attempts(1);
  22729. sse.start_async();
  22730. auto well_formed = true;
  22731. std::string id;
  22732. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22733. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22734. id = sse.last_event_id();
  22735. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22736. well_formed = false;
  22737. }
  22738. }
  22739. sse.stop();
  22740. EXPECT_TRUE(well_formed);
  22741. EXPECT_EQ(sse.last_event_id(), "end");
  22742. }
  22743. // Test: Manual stop
  22744. TEST_F(SSEIntegrationTest, ManualStop) {
  22745. // Endpoint that sends one event and stays open briefly. The server outlives
  22746. // this test body, so the provider uses the fixture's flag, not a local.
  22747. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22748. res.set_chunked_content_provider(
  22749. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22750. if (offset == 0) {
  22751. std::string event = "data: connected\n\n";
  22752. sink.write(event.data(), event.size());
  22753. }
  22754. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22755. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22756. }
  22757. return false;
  22758. });
  22759. });
  22760. Client client("localhost", get_port());
  22761. sse::SSEClient sse(client, "/stay-open");
  22762. std::atomic<bool> connected{false};
  22763. sse.on_open([&connected]() { connected.store(true); });
  22764. sse.set_reconnect_interval(100);
  22765. sse.set_max_reconnect_attempts(1);
  22766. sse.start_async();
  22767. // Wait for connection to establish
  22768. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22769. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22770. }
  22771. EXPECT_TRUE(connected.load());
  22772. EXPECT_TRUE(sse.is_connected());
  22773. // Signal handler to stop
  22774. stop_server_.store(true);
  22775. // Stop SSE client
  22776. sse.stop();
  22777. EXPECT_FALSE(sse.is_connected());
  22778. }
  22779. // Sends one event, then nothing until stop is set
  22780. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22781. return [&stop](const Request &, Response &res) {
  22782. res.set_chunked_content_provider(
  22783. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22784. if (offset == 0) {
  22785. std::string event = "data: hello\n\n";
  22786. sink.write(event.data(), event.size());
  22787. }
  22788. while (!stop.load()) {
  22789. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22790. }
  22791. return false;
  22792. });
  22793. };
  22794. }
  22795. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22796. static void check_stop_interrupts_blocked_read(Client &client) {
  22797. client.set_read_timeout(30, 0);
  22798. for (auto by_destructor : {false, true}) {
  22799. std::atomic<bool> received{false};
  22800. std::chrono::steady_clock::time_point start;
  22801. {
  22802. sse::SSEClient sse(client, "/idle-stream");
  22803. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22804. sse.start_async();
  22805. for (int i = 0; i < 500 && !received.load(); ++i) {
  22806. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22807. }
  22808. ASSERT_TRUE(received.load());
  22809. // Let the client block in the next read
  22810. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22811. start = std::chrono::steady_clock::now();
  22812. if (!by_destructor) { sse.stop(); }
  22813. }
  22814. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22815. std::chrono::seconds(2));
  22816. }
  22817. }
  22818. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22819. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22820. Client client("localhost", get_port());
  22821. check_stop_interrupts_blocked_read(client);
  22822. }
  22823. #ifdef CPPHTTPLIB_SSL_ENABLED
  22824. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22826. std::atomic<bool> done{false};
  22827. svr.Get("/idle-stream", idle_event_stream(done));
  22828. auto port = svr.bind_to_any_port(HOST);
  22829. std::thread t([&] { svr.listen_after_bind(); });
  22830. auto se = detail::scope_exit([&] {
  22831. done.store(true);
  22832. svr.stop();
  22833. t.join();
  22834. });
  22835. svr.wait_until_ready();
  22836. Client client("https://localhost:" + std::to_string(port));
  22837. client.enable_server_certificate_verification(false);
  22838. check_stop_interrupts_blocked_read(client);
  22839. }
  22840. #endif
  22841. // Test: SSEClient with custom headers
  22842. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22843. // Setup a server endpoint that checks for custom header
  22844. std::atomic<bool> header_received{false};
  22845. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22846. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22847. header_received.store(true);
  22848. }
  22849. res.set_chunked_content_provider("text/event-stream",
  22850. [](size_t, DataSink &) { return false; });
  22851. });
  22852. Client client("localhost", get_port());
  22853. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22854. sse::SSEClient sse(client, "/header-check", headers);
  22855. sse.set_max_reconnect_attempts(1);
  22856. sse.start_async();
  22857. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22858. sse.stop();
  22859. EXPECT_TRUE(header_received.load());
  22860. }
  22861. // Test: Reconnect interval configuration
  22862. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22863. Client client("localhost", get_port());
  22864. sse::SSEClient sse(client, "/events");
  22865. auto &result = sse.set_reconnect_interval(500);
  22866. // Builder pattern should return reference to self
  22867. EXPECT_EQ(&result, &sse);
  22868. }
  22869. // Test: Max reconnect attempts
  22870. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22871. // Connect to non-existent port to force reconnects
  22872. Client client("localhost", 59998);
  22873. sse::SSEClient sse(client, "/events");
  22874. std::atomic<int> error_count{0};
  22875. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22876. sse.set_reconnect_interval(50);
  22877. sse.set_max_reconnect_attempts(2);
  22878. auto start = std::chrono::steady_clock::now();
  22879. sse.start(); // Blocking call
  22880. auto end = std::chrono::steady_clock::now();
  22881. // Should have stopped after 2 failed attempts
  22882. EXPECT_GE(error_count.load(), 2);
  22883. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22884. auto duration =
  22885. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22886. #ifdef _WIN32
  22887. // Windows is much slower for socket connection failures
  22888. EXPECT_LT(duration.count(), 7000);
  22889. #else
  22890. EXPECT_LT(duration.count(), 1000);
  22891. #endif
  22892. }
  22893. // Test: Multi-line data in integration
  22894. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22895. // Endpoint with multi-line data
  22896. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22897. res.set_chunked_content_provider(
  22898. "text/event-stream", [](size_t offset, DataSink &sink) {
  22899. if (offset == 0) {
  22900. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22901. sink.write(event.data(), event.size());
  22902. }
  22903. return false;
  22904. });
  22905. });
  22906. Client client("localhost", get_port());
  22907. sse::SSEClient sse(client, "/multiline-data");
  22908. std::string received_data;
  22909. std::mutex data_mutex;
  22910. sse.on_message([&](const sse::SSEMessage &msg) {
  22911. std::lock_guard<std::mutex> lock(data_mutex);
  22912. received_data = msg.data;
  22913. });
  22914. sse.set_reconnect_interval(100);
  22915. sse.set_max_reconnect_attempts(1);
  22916. sse.start_async();
  22917. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22918. sse.stop();
  22919. std::lock_guard<std::mutex> lock(data_mutex);
  22920. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22921. }
  22922. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22923. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22924. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22925. DataSink &sink) {
  22926. if (offset == 0) {
  22927. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22928. sink.write(events.data(), events.size());
  22929. }
  22930. return false;
  22931. });
  22932. });
  22933. Client client("localhost", get_port());
  22934. sse::SSEClient sse(client, "/empty-data-lines");
  22935. std::mutex mutex;
  22936. std::condition_variable cv;
  22937. std::vector<std::string> received;
  22938. sse.on_message([&](const sse::SSEMessage &msg) {
  22939. std::lock_guard<std::mutex> lock(mutex);
  22940. received.push_back(msg.data);
  22941. cv.notify_all();
  22942. });
  22943. sse.set_max_reconnect_attempts(1);
  22944. sse.start_async();
  22945. {
  22946. std::unique_lock<std::mutex> lock(mutex);
  22947. cv.wait_for(lock, std::chrono::seconds(2),
  22948. [&] { return received.size() >= 3; });
  22949. }
  22950. sse.stop();
  22951. ASSERT_GE(received.size(), 3u);
  22952. EXPECT_EQ(received[0], "");
  22953. EXPECT_EQ(received[1], "\nhello");
  22954. EXPECT_EQ(received[2], "");
  22955. }
  22956. // Test: Auto-reconnect after server disconnection
  22957. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22958. std::atomic<int> connection_count{0};
  22959. std::atomic<int> message_count{0};
  22960. // Endpoint that sends one event and closes, forcing reconnect
  22961. server_->Get("/reconnect-test",
  22962. [&connection_count](const Request &, Response &res) {
  22963. connection_count.fetch_add(1);
  22964. res.set_chunked_content_provider(
  22965. "text/event-stream", [](size_t offset, DataSink &sink) {
  22966. if (offset == 0) {
  22967. std::string event = "data: hello\n\n";
  22968. sink.write(event.data(), event.size());
  22969. }
  22970. return false; // Close connection after sending
  22971. });
  22972. });
  22973. Client client("localhost", get_port());
  22974. sse::SSEClient sse(client, "/reconnect-test");
  22975. sse.on_message([&message_count](const sse::SSEMessage &) {
  22976. message_count.fetch_add(1);
  22977. });
  22978. sse.set_reconnect_interval(100);
  22979. sse.set_max_reconnect_attempts(3);
  22980. sse.start_async();
  22981. // Wait long enough for multiple reconnects
  22982. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22983. sse.stop();
  22984. // Should have connected multiple times (initial + reconnects)
  22985. EXPECT_GE(connection_count.load(), 2);
  22986. // Should have received messages from multiple connections
  22987. EXPECT_GE(message_count.load(), 2);
  22988. }
  22989. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22990. std::atomic<int> connection_count{0};
  22991. // Neither Content-Length nor chunked: the close ends the stream
  22992. server_->Get("/close-delimited",
  22993. [&connection_count](const Request &, Response &res) {
  22994. connection_count.fetch_add(1);
  22995. res.set_content_provider(
  22996. "text/event-stream", [](size_t offset, DataSink &sink) {
  22997. if (offset == 0) {
  22998. std::string event = "data: hello\n\n";
  22999. sink.write(event.data(), event.size());
  23000. } else {
  23001. sink.done();
  23002. }
  23003. return true;
  23004. });
  23005. });
  23006. Client client("localhost", get_port());
  23007. sse::SSEClient sse(client, "/close-delimited");
  23008. std::atomic<int> error_count{0};
  23009. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23010. sse.set_reconnect_interval(100);
  23011. sse.start_async();
  23012. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23013. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23014. }
  23015. sse.stop();
  23016. // Reconnects as after any end of the stream, but reports no error
  23017. EXPECT_GE(connection_count.load(), 2);
  23018. EXPECT_EQ(0, error_count.load());
  23019. }
  23020. // Test: A retry field that is not all ASCII digits is ignored
  23021. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  23022. std::atomic<int> connection_count{0};
  23023. server_->Get("/bad-retry",
  23024. [&connection_count](const Request &, Response &res) {
  23025. connection_count.fetch_add(1);
  23026. res.set_chunked_content_provider(
  23027. "text/event-stream", [](size_t offset, DataSink &sink) {
  23028. if (offset == 0) {
  23029. std::string event = "retry: -1\ndata: hello\n\n";
  23030. sink.write(event.data(), event.size());
  23031. }
  23032. return false;
  23033. });
  23034. });
  23035. Client client("localhost", get_port());
  23036. sse::SSEClient sse(client, "/bad-retry");
  23037. sse.set_reconnect_interval(10000);
  23038. sse.start_async();
  23039. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23040. sse.stop();
  23041. EXPECT_EQ(connection_count.load(), 1);
  23042. }
  23043. // Test: A retry field of all ASCII digits sets the reconnection time
  23044. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23045. std::mutex mutex;
  23046. std::condition_variable cv;
  23047. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23048. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23049. {
  23050. std::lock_guard<std::mutex> lock(mutex);
  23051. connected_at.push_back(std::chrono::steady_clock::now());
  23052. cv.notify_all();
  23053. }
  23054. res.set_chunked_content_provider(
  23055. "text/event-stream", [](size_t offset, DataSink &sink) {
  23056. if (offset == 0) {
  23057. std::string event = "retry: 0\ndata: hello\n\n";
  23058. sink.write(event.data(), event.size());
  23059. }
  23060. return false;
  23061. });
  23062. });
  23063. Client client("localhost", get_port());
  23064. sse::SSEClient sse(client, "/zero-retry");
  23065. sse.set_reconnect_interval(10000);
  23066. sse.start_async();
  23067. {
  23068. std::unique_lock<std::mutex> lock(mutex);
  23069. cv.wait_for(lock, std::chrono::seconds(5),
  23070. [&] { return connected_at.size() >= 2; });
  23071. }
  23072. sse.stop();
  23073. // The server-supplied interval is applied, but never below 100ms, so
  23074. // "retry: 0" does not cause a busy reconnect loop
  23075. std::lock_guard<std::mutex> lock(mutex);
  23076. ASSERT_GE(connected_at.size(), 2u);
  23077. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23078. connected_at[1] - connected_at[0])
  23079. .count();
  23080. EXPECT_GE(interval_ms, 100);
  23081. }
  23082. // Test: Last-Event-ID sent on reconnect
  23083. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23084. std::atomic<int> connection_count{0};
  23085. std::vector<std::string> received_last_event_ids;
  23086. std::mutex id_mutex;
  23087. // Endpoint that checks Last-Event-ID header and sends event with ID
  23088. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23089. int conn = connection_count.fetch_add(1);
  23090. // Capture the Last-Event-ID header from each connection
  23091. {
  23092. std::lock_guard<std::mutex> lock(id_mutex);
  23093. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23094. }
  23095. res.set_chunked_content_provider(
  23096. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23097. if (offset == 0) {
  23098. std::string event =
  23099. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23100. sink.write(event.data(), event.size());
  23101. }
  23102. return false;
  23103. });
  23104. });
  23105. Client client("localhost", get_port());
  23106. sse::SSEClient sse(client, "/reconnect-with-id");
  23107. sse.set_reconnect_interval(100);
  23108. sse.set_max_reconnect_attempts(3);
  23109. sse.start_async();
  23110. // Wait for at least 2 connections
  23111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23112. sse.stop();
  23113. // Verify behavior
  23114. std::lock_guard<std::mutex> lock(id_mutex);
  23115. EXPECT_GE(received_last_event_ids.size(), 2u);
  23116. // First connection should have no Last-Event-ID
  23117. if (!received_last_event_ids.empty()) {
  23118. EXPECT_EQ(received_last_event_ids[0], "");
  23119. }
  23120. // Second connection should have Last-Event-ID from first connection
  23121. if (received_last_event_ids.size() >= 2) {
  23122. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23123. }
  23124. }
  23125. // Test: set_headers updates headers used on reconnect
  23126. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23127. std::vector<std::string> received_tokens;
  23128. std::mutex token_mutex;
  23129. // Endpoint that captures Authorization header
  23130. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23131. {
  23132. std::lock_guard<std::mutex> lock(token_mutex);
  23133. received_tokens.push_back(req.get_header_value("Authorization"));
  23134. }
  23135. res.set_chunked_content_provider(
  23136. "text/event-stream", [](size_t offset, DataSink &sink) {
  23137. if (offset == 0) {
  23138. std::string event = "data: hello\n\n";
  23139. sink.write(event.data(), event.size());
  23140. }
  23141. return false; // Close connection to trigger reconnect
  23142. });
  23143. });
  23144. Client client("localhost", get_port());
  23145. Headers headers = {{"Authorization", "Bearer old-token"}};
  23146. sse::SSEClient sse(client, "/auth-check", headers);
  23147. // Update headers on each successful connection
  23148. sse.on_open(
  23149. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23150. sse.set_reconnect_interval(100);
  23151. sse.set_max_reconnect_attempts(3);
  23152. sse.start_async();
  23153. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23154. sse.stop();
  23155. std::lock_guard<std::mutex> lock(token_mutex);
  23156. ASSERT_GE(received_tokens.size(), 2u);
  23157. // First connection uses original header
  23158. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23159. // Second connection uses updated header from set_headers
  23160. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23161. }
  23162. // Test: 401 allows reconnection (so on_error can refresh headers)
  23163. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23164. std::atomic<int> connection_count{0};
  23165. // Endpoint: returns 401 on first attempt, 200 on second
  23166. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23167. int conn = connection_count.fetch_add(1);
  23168. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23169. res.status = StatusCode::Unauthorized_401;
  23170. res.set_content("Unauthorized", "text/plain");
  23171. return;
  23172. }
  23173. res.set_chunked_content_provider(
  23174. "text/event-stream", [](size_t offset, DataSink &sink) {
  23175. if (offset == 0) {
  23176. std::string event = "data: authenticated\n\n";
  23177. sink.write(event.data(), event.size());
  23178. }
  23179. return false;
  23180. });
  23181. });
  23182. Client client("localhost", get_port());
  23183. Headers headers = {{"Authorization", "Bearer expired"}};
  23184. sse::SSEClient sse(client, "/auth-retry", headers);
  23185. std::atomic<bool> message_received{false};
  23186. // Refresh token on error
  23187. sse.on_error(
  23188. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23189. sse.on_message([&](const sse::SSEMessage &msg) {
  23190. if (msg.data == "authenticated") { message_received.store(true); }
  23191. });
  23192. sse.set_reconnect_interval(100);
  23193. sse.set_max_reconnect_attempts(3);
  23194. sse.start_async();
  23195. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23196. sse.stop();
  23197. // Should have reconnected after 401 and succeeded with new token
  23198. EXPECT_GE(connection_count.load(), 2);
  23199. EXPECT_TRUE(message_received.load());
  23200. }
  23201. TEST(Issue2318Test, EmptyHostString) {
  23202. {
  23203. httplib::Client cli_empty("", PORT);
  23204. auto res = cli_empty.Get("/");
  23205. ASSERT_FALSE(res);
  23206. EXPECT_EQ(httplib::Error::Connection, res.error());
  23207. }
  23208. {
  23209. httplib::Client cli(" ", PORT);
  23210. auto res = cli.Get("/");
  23211. ASSERT_FALSE(res);
  23212. EXPECT_EQ(httplib::Error::Connection, res.error());
  23213. }
  23214. }
  23215. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23216. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23217. Server svr;
  23218. // Set a small payload limit (1KB)
  23219. svr.set_payload_max_length(1024);
  23220. svr.Post("/test", [&](const Request &req, Response &res) {
  23221. res.set_content("Body size: " + std::to_string(req.body.size()),
  23222. "text/plain");
  23223. });
  23224. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23225. auto se = detail::scope_exit([&] {
  23226. svr.stop();
  23227. listen_thread.join();
  23228. });
  23229. svr.wait_until_ready();
  23230. // Create data that compresses well but exceeds limit when decompressed
  23231. // 8KB of repeated null bytes compresses to a very small size
  23232. std::string original_data(8 * 1024, '\0');
  23233. // Compress the data using gzip
  23234. std::string compressed_data;
  23235. detail::gzip_compressor compressor;
  23236. compressor.compress(original_data.data(), original_data.size(), true,
  23237. [&](const char *data, size_t size) {
  23238. compressed_data.append(data, size);
  23239. return true;
  23240. });
  23241. // Verify compression worked (compressed should be much smaller)
  23242. ASSERT_LT(compressed_data.size(), original_data.size());
  23243. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23244. // Send compressed data with Content-Encoding: gzip
  23245. Client cli(HOST, PORT);
  23246. Headers headers = {{"Content-Encoding", "gzip"}};
  23247. auto res =
  23248. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23249. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23251. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23252. }
  23253. #endif
  23254. // ============================================================================
  23255. // OpenSSL-Specific Tests
  23256. // ============================================================================
  23257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23258. X509 *readCertificate(const std::string &strFileName) {
  23259. std::ifstream inStream(strFileName);
  23260. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23261. std::istreambuf_iterator<char>());
  23262. if (strCertPEM.empty()) return (nullptr);
  23263. BIO *pbCert = BIO_new(BIO_s_mem());
  23264. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23265. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23266. BIO_free(pbCert);
  23267. return (pCert);
  23268. }
  23269. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23270. std::ifstream inStream(strFileName);
  23271. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23272. std::istreambuf_iterator<char>());
  23273. if (strPrivateKeyPEM.empty()) return (nullptr);
  23274. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23275. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23276. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23277. BIO_free(pbPrivKey);
  23278. return (pPrivateKey);
  23279. }
  23280. TEST(BindServerTest, UpdateCerts) {
  23281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23282. int port = svr.bind_to_any_port("0.0.0.0");
  23283. ASSERT_TRUE(svr.is_valid());
  23284. ASSERT_TRUE(port > 0);
  23285. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23286. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23287. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23288. ASSERT_TRUE(cert != nullptr);
  23289. ASSERT_TRUE(ca_cert != nullptr);
  23290. ASSERT_TRUE(key != nullptr);
  23291. X509_STORE *cert_store = X509_STORE_new();
  23292. X509_STORE_add_cert(cert_store, ca_cert);
  23293. // svr.update_certs(cert, key, cert_store); // deprecated
  23294. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23295. CLIENT_CA_CERT_FILE);
  23296. ASSERT_TRUE(svr.is_valid());
  23297. svr.stop();
  23298. X509_STORE_free(cert_store);
  23299. X509_free(cert);
  23300. X509_free(ca_cert);
  23301. EVP_PKEY_free(key);
  23302. }
  23303. // Test that update_certs() updates client CA list correctly
  23304. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23305. // Start with file-based constructor
  23306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23307. ASSERT_TRUE(svr.is_valid());
  23308. // Initially no client CA list should be set
  23309. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23310. ASSERT_TRUE(ssl_ctx != nullptr);
  23311. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23312. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23313. // Now update with client CA (PEM string)
  23314. std::string cert_pem, key_pem, ca_pem;
  23315. read_file(SERVER_CERT_FILE, cert_pem);
  23316. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23317. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23318. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23319. ASSERT_TRUE(svr.is_valid());
  23320. // Now client CA list should be set
  23321. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23322. ASSERT_TRUE(ca_list_after != nullptr);
  23323. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23324. }
  23325. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23326. // Test that the file-path SSLServer constructor properly sets the client CA
  23327. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23329. ASSERT_TRUE(svr.is_valid());
  23330. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23331. ASSERT_TRUE(ssl_ctx != nullptr);
  23332. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23333. ASSERT_TRUE(ca_list != nullptr);
  23334. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23335. }
  23336. #endif
  23337. // ============================================================================
  23338. // MbedTLS-Specific Tests
  23339. // ============================================================================
  23340. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23341. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23342. using namespace httplib::tls;
  23343. // Track if callback was invoked
  23344. bool callback_invoked = false;
  23345. // The callback receives void* ctx which is actually MbedTlsContext*
  23346. // We can access the mbedtls_ssl_config via the context
  23347. auto setup_callback = [&callback_invoked](void *ctx) {
  23348. callback_invoked = true;
  23349. // Cast to MbedTlsContext* to access the ssl config
  23350. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23351. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23352. // Use static variables to hold certificate data (simplified for test)
  23353. static mbedtls_x509_crt own_cert;
  23354. static mbedtls_pk_context own_key;
  23355. static mbedtls_x509_crt ca_chain;
  23356. static bool initialized = false;
  23357. if (!initialized) {
  23358. mbedtls_x509_crt_init(&own_cert);
  23359. mbedtls_pk_init(&own_key);
  23360. mbedtls_x509_crt_init(&ca_chain);
  23361. // Load server certificate
  23362. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23363. return false;
  23364. }
  23365. // Load server private key.
  23366. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23367. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23368. #if MBEDTLS_VERSION_MAJOR == 3
  23369. ,
  23370. mbedtls_ctr_drbg_random, nullptr
  23371. #endif
  23372. ) != 0) {
  23373. return false;
  23374. }
  23375. // Load CA chain for client verification
  23376. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23377. return false;
  23378. }
  23379. initialized = true;
  23380. }
  23381. // Configure the SSL config
  23382. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23383. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23384. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23385. // Set minimum TLS version using mbedTLS native API
  23386. #if MBEDTLS_VERSION_MAJOR >= 3
  23387. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23388. #else
  23389. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23390. MBEDTLS_SSL_MINOR_VERSION_3);
  23391. #endif
  23392. return true;
  23393. };
  23394. SSLServer svr(setup_callback);
  23395. ASSERT_TRUE(svr.is_valid());
  23396. ASSERT_TRUE(callback_invoked);
  23397. svr.Get("/test", [&](const Request &req, Response &res) {
  23398. res.set_content("test", "text/plain");
  23399. auto cert = req.peer_cert();
  23400. ASSERT_TRUE(static_cast<bool>(cert));
  23401. auto common_name = cert.subject_cn();
  23402. EXPECT_EQ("Common Name", common_name);
  23403. });
  23404. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23405. auto se = detail::scope_exit([&] {
  23406. svr.stop();
  23407. t.join();
  23408. ASSERT_FALSE(svr.is_running());
  23409. });
  23410. svr.wait_until_ready();
  23411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23412. cli.enable_server_certificate_verification(false);
  23413. cli.set_connection_timeout(30);
  23414. auto res = cli.Get("/test");
  23415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23416. ASSERT_EQ(StatusCode::OK_200, res->status);
  23417. }
  23418. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23419. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23420. // keep-alive SSL session, which reads through that config in
  23421. // mbedtls_ssl_close_notify.
  23422. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23424. ASSERT_TRUE(svr.is_valid());
  23425. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23426. res.set_content("test", "text/plain");
  23427. });
  23428. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23429. auto se = detail::scope_exit([&] {
  23430. svr.stop();
  23431. t.join();
  23432. ASSERT_FALSE(svr.is_running());
  23433. });
  23434. svr.wait_until_ready();
  23435. {
  23436. SSLClient cli(HOST, PORT);
  23437. cli.enable_server_certificate_verification(false);
  23438. cli.set_keep_alive(true);
  23439. auto res = cli.Get("/test");
  23440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23441. ASSERT_EQ(StatusCode::OK_200, res->status);
  23442. // cli is destructed here with the keep-alive SSL session still open.
  23443. }
  23444. }
  23445. #endif
  23446. // WebSocket Tests
  23447. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23448. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23449. // defining the meaning of these bits has been negotiated.
  23450. auto make_frame = [](uint8_t first_byte) {
  23451. std::string frame;
  23452. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23453. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23454. frame += "Hello";
  23455. return frame;
  23456. };
  23457. // RSV1 set (0x40)
  23458. {
  23459. detail::BufferStream strm;
  23460. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23461. ws::Opcode opcode;
  23462. std::string payload;
  23463. bool fin;
  23464. EXPECT_EQ(
  23465. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23466. ws::impl::FrameRead::Fail);
  23467. }
  23468. // RSV2 set (0x20)
  23469. {
  23470. detail::BufferStream strm;
  23471. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23472. ws::Opcode opcode;
  23473. std::string payload;
  23474. bool fin;
  23475. EXPECT_EQ(
  23476. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23477. ws::impl::FrameRead::Fail);
  23478. }
  23479. // RSV3 set (0x10)
  23480. {
  23481. detail::BufferStream strm;
  23482. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23483. ws::Opcode opcode;
  23484. std::string payload;
  23485. bool fin;
  23486. EXPECT_EQ(
  23487. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23488. ws::impl::FrameRead::Fail);
  23489. }
  23490. // No RSV bits set - should succeed
  23491. {
  23492. detail::BufferStream strm;
  23493. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23494. ws::Opcode opcode;
  23495. std::string payload;
  23496. bool fin;
  23497. EXPECT_EQ(
  23498. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23499. ws::impl::FrameRead::Ok);
  23500. EXPECT_EQ(ws::Opcode::Text, opcode);
  23501. EXPECT_EQ("Hello", payload);
  23502. EXPECT_TRUE(fin);
  23503. }
  23504. }
  23505. TEST(WebSocketTest, ControlFrameValidation) {
  23506. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23507. // payload length <= 125.
  23508. // Ping with FIN=0 - must be rejected
  23509. {
  23510. detail::BufferStream strm;
  23511. std::string frame;
  23512. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23513. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23514. strm.write(frame.data(), frame.size());
  23515. ws::Opcode opcode;
  23516. std::string payload;
  23517. bool fin;
  23518. EXPECT_EQ(
  23519. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23520. ws::impl::FrameRead::Fail);
  23521. }
  23522. // Close with FIN=0 - must be rejected
  23523. {
  23524. detail::BufferStream strm;
  23525. std::string frame;
  23526. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23527. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23528. strm.write(frame.data(), frame.size());
  23529. ws::Opcode opcode;
  23530. std::string payload;
  23531. bool fin;
  23532. EXPECT_EQ(
  23533. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23534. ws::impl::FrameRead::Fail);
  23535. }
  23536. // Ping with payload_len=126 (extended length) - must be rejected
  23537. {
  23538. detail::BufferStream strm;
  23539. std::string frame;
  23540. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23541. frame += static_cast<char>(126); // payload_len=126 (>125)
  23542. frame += static_cast<char>(0x00); // extended length high byte
  23543. frame += static_cast<char>(126); // extended length low byte
  23544. frame += std::string(126, 'x');
  23545. strm.write(frame.data(), frame.size());
  23546. ws::Opcode opcode;
  23547. std::string payload;
  23548. bool fin;
  23549. EXPECT_EQ(
  23550. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23551. ws::impl::FrameRead::Fail);
  23552. }
  23553. // Ping with FIN=1 and payload_len=125 - should succeed
  23554. {
  23555. detail::BufferStream strm;
  23556. std::string frame;
  23557. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23558. frame += static_cast<char>(125); // payload_len=125
  23559. frame += std::string(125, 'x');
  23560. strm.write(frame.data(), frame.size());
  23561. ws::Opcode opcode;
  23562. std::string payload;
  23563. bool fin;
  23564. EXPECT_EQ(
  23565. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23566. ws::impl::FrameRead::Ok);
  23567. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23568. EXPECT_EQ(125u, payload.size());
  23569. EXPECT_TRUE(fin);
  23570. }
  23571. }
  23572. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23573. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23574. // length MUST be 0.
  23575. // MSB set - must be rejected
  23576. {
  23577. detail::BufferStream strm;
  23578. std::string frame;
  23579. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23580. frame += static_cast<char>(127); // 64-bit extended length
  23581. frame += static_cast<char>(0x80); // MSB set (invalid)
  23582. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23583. strm.write(frame.data(), frame.size());
  23584. ws::Opcode opcode;
  23585. std::string payload;
  23586. bool fin;
  23587. EXPECT_EQ(
  23588. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23589. ws::impl::FrameRead::Fail);
  23590. }
  23591. // MSB clear - should pass length parsing (will be rejected by max_len,
  23592. // but that's a different check; use a small length to verify)
  23593. {
  23594. detail::BufferStream strm;
  23595. std::string frame;
  23596. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23597. frame += static_cast<char>(127); // 64-bit extended length
  23598. frame += std::string(7, '\0'); // high bytes = 0
  23599. frame += static_cast<char>(0x03); // length = 3
  23600. frame += "abc";
  23601. strm.write(frame.data(), frame.size());
  23602. ws::Opcode opcode;
  23603. std::string payload;
  23604. bool fin;
  23605. EXPECT_EQ(
  23606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23607. ws::impl::FrameRead::Ok);
  23608. EXPECT_EQ(ws::Opcode::Text, opcode);
  23609. EXPECT_EQ("abc", payload);
  23610. }
  23611. }
  23612. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23613. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23614. // Valid UTF-8
  23615. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23616. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23617. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23618. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23619. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23620. // Invalid UTF-8
  23621. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23622. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23623. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23624. EXPECT_FALSE(
  23625. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23626. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23627. }
  23628. TEST(WebSocketTest, ConnectAndDisconnect) {
  23629. Server svr;
  23630. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23631. std::string msg;
  23632. while (ws.read(msg)) {}
  23633. });
  23634. auto port = svr.bind_to_any_port(HOST);
  23635. std::thread t([&]() { svr.listen_after_bind(); });
  23636. svr.wait_until_ready();
  23637. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23638. auto res = client.connect();
  23639. ASSERT_TRUE(res);
  23640. EXPECT_EQ(Error::Success, res.error());
  23641. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23642. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23643. EXPECT_TRUE(client.is_open());
  23644. client.close();
  23645. EXPECT_FALSE(client.is_open());
  23646. svr.stop();
  23647. t.join();
  23648. }
  23649. TEST(WebSocketTest, ValidURL) {
  23650. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23651. EXPECT_TRUE(ws1.is_valid());
  23652. ws::WebSocketClient ws2("ws://example.com/path");
  23653. EXPECT_TRUE(ws2.is_valid());
  23654. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23655. EXPECT_TRUE(ws3.is_valid());
  23656. #ifdef CPPHTTPLIB_SSL_ENABLED
  23657. ws::WebSocketClient wss1("wss://example.com/path");
  23658. EXPECT_TRUE(wss1.is_valid());
  23659. ws::WebSocketClient wss2("wss://example.com:443/path");
  23660. EXPECT_TRUE(wss2.is_valid());
  23661. #endif
  23662. }
  23663. TEST(WebSocketTest, InvalidURL) {
  23664. // No scheme
  23665. ws::WebSocketClient ws1("localhost:8080/path");
  23666. EXPECT_FALSE(ws1.is_valid());
  23667. // No path
  23668. ws::WebSocketClient ws2("ws://localhost:8080");
  23669. EXPECT_FALSE(ws2.is_valid());
  23670. // Empty string
  23671. ws::WebSocketClient ws3("");
  23672. EXPECT_FALSE(ws3.is_valid());
  23673. // Missing host
  23674. ws::WebSocketClient ws4("ws://:8080/path");
  23675. EXPECT_FALSE(ws4.is_valid());
  23676. // Port number overflow — should not crash
  23677. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23678. EXPECT_FALSE(ws5.is_valid());
  23679. // Port out of range
  23680. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23681. EXPECT_FALSE(ws6.is_valid());
  23682. }
  23683. TEST(WebSocketTest, UnsupportedScheme) {
  23684. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23685. ws::WebSocketClient ws1("http://localhost:8080/path");
  23686. EXPECT_FALSE(ws1.is_valid());
  23687. ws::WebSocketClient ws2("https://localhost:8080/path");
  23688. EXPECT_FALSE(ws2.is_valid());
  23689. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23690. EXPECT_FALSE(ws3.is_valid());
  23691. #else
  23692. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23693. std::invalid_argument);
  23694. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23695. std::invalid_argument);
  23696. #endif
  23697. }
  23698. TEST(WebSocketTest, ConnectWhenInvalid) {
  23699. ws::WebSocketClient ws("not a valid url");
  23700. EXPECT_FALSE(ws.is_valid());
  23701. auto res = ws.connect();
  23702. EXPECT_FALSE(res);
  23703. EXPECT_EQ(Error::Connection, res.error());
  23704. EXPECT_EQ(-1, res.status());
  23705. }
  23706. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23707. // Grab a port that is free, then close it again so nothing listens there
  23708. Server svr;
  23709. auto port = svr.bind_to_any_port(HOST);
  23710. svr.stop();
  23711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23712. auto res = client.connect();
  23713. ASSERT_FALSE(res);
  23714. EXPECT_EQ(Error::Connection, res.error());
  23715. EXPECT_EQ(-1, res.status());
  23716. }
  23717. TEST(WebSocketTest, DefaultPort) {
  23718. ws::WebSocketClient ws1("ws://example.com/path");
  23719. EXPECT_TRUE(ws1.is_valid());
  23720. // ws:// defaults to port 80 (verified by successful parse)
  23721. #ifdef CPPHTTPLIB_SSL_ENABLED
  23722. ws::WebSocketClient ws2("wss://example.com/path");
  23723. EXPECT_TRUE(ws2.is_valid());
  23724. // wss:// defaults to port 443 (verified by successful parse)
  23725. #endif
  23726. }
  23727. TEST(WebSocketTest, IPv6LiteralAddress) {
  23728. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23729. EXPECT_TRUE(ws1.is_valid());
  23730. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23731. EXPECT_TRUE(ws2.is_valid());
  23732. }
  23733. TEST(WebSocketTest, ComplexPath) {
  23734. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23735. EXPECT_TRUE(ws1.is_valid());
  23736. ws::WebSocketClient ws2("ws://localhost:8080/");
  23737. EXPECT_TRUE(ws2.is_valid());
  23738. }
  23739. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23740. Server svr;
  23741. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23742. std::string msg;
  23743. while (ws.read(msg)) {}
  23744. });
  23745. auto port = svr.bind_to_any_port(HOST);
  23746. std::thread t([&]() { svr.listen_after_bind(); });
  23747. svr.wait_until_ready();
  23748. auto another_host = "example.com";
  23749. auto wrong_ip = "192.0.2.1";
  23750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23751. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23752. ASSERT_TRUE(client.connect());
  23753. EXPECT_TRUE(client.is_open());
  23754. client.close();
  23755. svr.stop();
  23756. t.join();
  23757. }
  23758. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23759. Server svr;
  23760. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23761. std::string msg;
  23762. while (ws.read(msg)) {}
  23763. });
  23764. auto port = svr.bind_to_any_port(HOST);
  23765. std::thread t([&]() { svr.listen_after_bind(); });
  23766. svr.wait_until_ready();
  23767. auto wrong_ip = "192.0.2.1";
  23768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23769. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23770. client.set_connection_timeout(1);
  23771. client.set_read_timeout(1);
  23772. client.set_write_timeout(1);
  23773. EXPECT_FALSE(client.connect());
  23774. EXPECT_FALSE(client.is_open());
  23775. svr.stop();
  23776. t.join();
  23777. }
  23778. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23779. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23780. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23781. // (RFC 6761) is only a map key and the Host header value.
  23782. auto host = "target.invalid";
  23783. Server svr;
  23784. std::string received_host;
  23785. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23786. received_host = req.get_header_value("Host");
  23787. std::string msg;
  23788. while (ws.read(msg)) {}
  23789. });
  23790. auto port = svr.bind_to_any_port(HOST);
  23791. std::thread t([&]() { svr.listen_after_bind(); });
  23792. // ASSERT_* below returns from the test body, which would leave t joinable
  23793. // and make ~thread call std::terminate.
  23794. auto se = detail::scope_exit([&] {
  23795. svr.stop();
  23796. if (t.joinable()) { t.join(); }
  23797. });
  23798. svr.wait_until_ready();
  23799. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23800. std::to_string(port) + "/ws");
  23801. client.set_direct_hostname_addr_map({{host, HOST}});
  23802. ASSERT_TRUE(client.connect());
  23803. EXPECT_TRUE(client.is_open());
  23804. client.close();
  23805. svr.stop();
  23806. t.join();
  23807. // The mapping only redirects the connection; the identity stays host_.
  23808. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23809. }
  23810. class WebSocketIntegrationTest : public ::testing::Test {
  23811. protected:
  23812. void SetUp() override {
  23813. server_ = httplib::detail::make_unique<Server>();
  23814. setup_server();
  23815. start_server();
  23816. }
  23817. void TearDown() override {
  23818. server_->stop();
  23819. if (server_thread_.joinable()) { server_thread_.join(); }
  23820. }
  23821. void setup_server() {
  23822. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23823. std::string msg;
  23824. ws::ReadResult ret;
  23825. while ((ret = ws.read(msg))) {
  23826. if (ret == ws::Binary) {
  23827. ws.send(msg.data(), msg.size());
  23828. } else {
  23829. ws.send(msg);
  23830. }
  23831. }
  23832. });
  23833. server_->WebSocket("/ws-echo-string",
  23834. [](const Request &, ws::WebSocket &ws) {
  23835. std::string msg;
  23836. while (ws.read(msg)) {
  23837. ws.send("echo: " + msg);
  23838. }
  23839. });
  23840. server_->WebSocket(
  23841. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23842. // Echo back request metadata
  23843. ws.send("path:" + req.path);
  23844. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23845. std::string msg;
  23846. while (ws.read(msg)) {}
  23847. });
  23848. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23849. std::string msg;
  23850. ws.read(msg); // wait for a message
  23851. ws.close();
  23852. });
  23853. server_->WebSocket("/ws-close-status",
  23854. [](const Request &, ws::WebSocket &ws) {
  23855. std::string msg;
  23856. ws.read(msg); // wait for a message
  23857. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23858. });
  23859. server_->WebSocket(
  23860. "/ws-subprotocol",
  23861. [](const Request &, ws::WebSocket &ws) {
  23862. std::string msg;
  23863. while (ws.read(msg)) {
  23864. ws.send(msg);
  23865. }
  23866. },
  23867. [](const std::vector<std::string> &protocols) -> std::string {
  23868. for (const auto &p : protocols) {
  23869. if (p == "graphql-ws") { return p; }
  23870. }
  23871. return "";
  23872. });
  23873. server_->WebSocket(
  23874. "/ws-subprotocol-unoffered",
  23875. [](const Request &, ws::WebSocket &ws) {
  23876. std::string msg;
  23877. while (ws.read(msg)) {
  23878. ws.send(msg);
  23879. }
  23880. },
  23881. [](const std::vector<std::string> &) -> std::string {
  23882. return "admin";
  23883. });
  23884. }
  23885. void start_server() {
  23886. port_ = server_->bind_to_any_port(HOST);
  23887. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23888. server_->wait_until_ready();
  23889. }
  23890. std::unique_ptr<Server> server_;
  23891. std::thread server_thread_;
  23892. int port_ = 0;
  23893. };
  23894. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23896. "/ws-echo");
  23897. ASSERT_TRUE(client.connect());
  23898. ASSERT_TRUE(client.is_open());
  23899. ASSERT_TRUE(client.send("Hello WebSocket"));
  23900. std::string msg;
  23901. EXPECT_EQ(ws::Text, client.read(msg));
  23902. EXPECT_EQ("Hello WebSocket", msg);
  23903. client.close();
  23904. }
  23905. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23907. "/ws-echo");
  23908. ASSERT_TRUE(client.connect());
  23909. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23910. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23911. std::string msg;
  23912. EXPECT_EQ(ws::Binary, client.read(msg));
  23913. EXPECT_EQ(binary_data, msg);
  23914. client.close();
  23915. }
  23916. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23917. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23918. "/ws-echo");
  23919. ASSERT_TRUE(client.connect());
  23920. for (int i = 0; i < 10; i++) {
  23921. auto text = "message " + std::to_string(i);
  23922. ASSERT_TRUE(client.send(text));
  23923. std::string msg;
  23924. ASSERT_TRUE(client.read(msg));
  23925. EXPECT_EQ(text, msg);
  23926. }
  23927. client.close();
  23928. }
  23929. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23931. "/ws-close");
  23932. ASSERT_TRUE(client.connect());
  23933. // Send a message to trigger the server to close
  23934. ASSERT_TRUE(client.send("trigger close"));
  23935. // The server will close, so read should return false
  23936. std::string msg;
  23937. EXPECT_FALSE(client.read(msg));
  23938. EXPECT_FALSE(client.is_open());
  23939. }
  23940. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23942. "/ws-echo");
  23943. ASSERT_TRUE(client.connect());
  23944. // 128KB message
  23945. std::string large_data(128 * 1024, 'X');
  23946. ASSERT_TRUE(client.send(large_data));
  23947. std::string msg;
  23948. ASSERT_TRUE(client.read(msg));
  23949. EXPECT_EQ(large_data, msg);
  23950. client.close();
  23951. }
  23952. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23954. "/ws-echo");
  23955. ASSERT_TRUE(client.connect());
  23956. const int num_threads = 4;
  23957. std::vector<std::thread> threads;
  23958. std::atomic<int> send_count{0};
  23959. for (int t = 0; t < num_threads; t++) {
  23960. threads.emplace_back([&client, &send_count, t]() {
  23961. for (int i = 0; i < 5; i++) {
  23962. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23963. if (client.send(text)) { send_count++; }
  23964. }
  23965. });
  23966. }
  23967. for (auto &th : threads) {
  23968. th.join();
  23969. }
  23970. int received = 0;
  23971. std::string msg;
  23972. while (received < send_count.load()) {
  23973. if (!client.read(msg)) { break; }
  23974. received++;
  23975. }
  23976. EXPECT_EQ(send_count.load(), received);
  23977. client.close();
  23978. }
  23979. TEST_F(WebSocketIntegrationTest, ReadString) {
  23980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23981. "/ws-echo-string");
  23982. ASSERT_TRUE(client.connect());
  23983. ASSERT_TRUE(client.send("hello"));
  23984. std::string msg;
  23985. ASSERT_TRUE(client.read(msg));
  23986. EXPECT_EQ("echo: hello", msg);
  23987. ASSERT_TRUE(client.send("world"));
  23988. ASSERT_TRUE(client.read(msg));
  23989. EXPECT_EQ("echo: world", msg);
  23990. client.close();
  23991. }
  23992. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23993. Headers headers = {{"X-Test-Header", "test-value"}};
  23994. ws::WebSocketClient client(
  23995. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23996. ASSERT_TRUE(client.connect());
  23997. std::string msg;
  23998. ASSERT_TRUE(client.read(msg));
  23999. EXPECT_EQ("path:/ws-request-info", msg);
  24000. ASSERT_TRUE(client.read(msg));
  24001. EXPECT_EQ("header:test-value", msg);
  24002. client.close();
  24003. }
  24004. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24005. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24006. "/ws-echo");
  24007. client.set_read_timeout(1, 0); // 1 second
  24008. ASSERT_TRUE(client.connect());
  24009. // Don't send anything — server echo handler waits for a message, so read()
  24010. // should time out. The connection survives it: nothing was consumed.
  24011. std::string msg;
  24012. EXPECT_EQ(client.read(msg), ws::Timeout);
  24013. EXPECT_TRUE(client.is_open());
  24014. // And it is still usable afterwards.
  24015. EXPECT_TRUE(client.send("after timeout"));
  24016. EXPECT_EQ(client.read(msg), ws::Text);
  24017. EXPECT_EQ(msg, "after timeout");
  24018. }
  24019. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24020. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24021. "/ws-echo");
  24022. client.set_read_timeout(1, 0);
  24023. ASSERT_TRUE(client.connect());
  24024. ASSERT_TRUE(client.send("first"));
  24025. std::string msg;
  24026. ASSERT_EQ(client.read(msg), ws::Text);
  24027. ASSERT_EQ(msg, "first");
  24028. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24029. // not be used with a read timeout: it would reprocess the previous message.
  24030. EXPECT_EQ(client.read(msg), ws::Timeout);
  24031. EXPECT_EQ(msg, "first");
  24032. }
  24033. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24035. "/ws-echo");
  24036. ASSERT_TRUE(client.connect());
  24037. // Setting it once the connection is open reaches the live stream, not just
  24038. // the seed for the next connect().
  24039. client.set_read_timeout(1, 0);
  24040. std::string msg;
  24041. EXPECT_EQ(client.read(msg), ws::Timeout);
  24042. EXPECT_TRUE(client.is_open());
  24043. }
  24044. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24046. "/ws-echo");
  24047. client.set_read_timeout(5, 0);
  24048. ASSERT_TRUE(client.connect());
  24049. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24050. // The server should reject it and close the connection.
  24051. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24052. client.send(oversized);
  24053. // The server's read() should have failed due to payload limit,
  24054. // so our read() should return false (connection closed).
  24055. std::string msg;
  24056. EXPECT_FALSE(client.read(msg));
  24057. }
  24058. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24060. "/ws-echo");
  24061. client.set_read_timeout(10, 0);
  24062. ASSERT_TRUE(client.connect());
  24063. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24064. // This should succeed.
  24065. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24066. ASSERT_TRUE(client.send(at_limit));
  24067. std::string msg;
  24068. ASSERT_TRUE(client.read(msg));
  24069. EXPECT_EQ(at_limit.size(), msg.size());
  24070. client.close();
  24071. }
  24072. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24074. "/nonexistent");
  24075. auto res = client.connect();
  24076. EXPECT_FALSE(res);
  24077. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24078. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24079. EXPECT_FALSE(client.is_open());
  24080. }
  24081. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24083. "/ws-echo");
  24084. ASSERT_TRUE(client.connect());
  24085. ASSERT_TRUE(client.send(""));
  24086. std::string msg;
  24087. EXPECT_EQ(ws::Text, client.read(msg));
  24088. EXPECT_EQ("", msg);
  24089. client.close();
  24090. }
  24091. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24093. "/ws-echo");
  24094. // First connection
  24095. ASSERT_TRUE(client.connect());
  24096. ASSERT_TRUE(client.send("first"));
  24097. std::string msg;
  24098. ASSERT_TRUE(client.read(msg));
  24099. EXPECT_EQ("first", msg);
  24100. client.close();
  24101. EXPECT_FALSE(client.is_open());
  24102. // Reconnect using the same client object
  24103. ASSERT_TRUE(client.connect());
  24104. ASSERT_TRUE(client.is_open());
  24105. ASSERT_TRUE(client.send("second"));
  24106. ASSERT_TRUE(client.read(msg));
  24107. EXPECT_EQ("second", msg);
  24108. client.close();
  24109. }
  24110. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24112. "/ws-close-status");
  24113. ASSERT_TRUE(client.connect());
  24114. // Trigger the server to close with GoingAway status
  24115. ASSERT_TRUE(client.send("trigger"));
  24116. // read() should return false after receiving the close frame
  24117. std::string msg;
  24118. EXPECT_FALSE(client.read(msg));
  24119. EXPECT_FALSE(client.is_open());
  24120. }
  24121. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24123. "/ws-echo");
  24124. ASSERT_TRUE(client.connect());
  24125. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24126. EXPECT_FALSE(client.is_open());
  24127. }
  24128. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24129. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24130. ws::WebSocketClient client(
  24131. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24132. ASSERT_TRUE(client.connect());
  24133. // Server should have selected graphql-ws
  24134. EXPECT_EQ("graphql-ws", client.subprotocol());
  24135. client.close();
  24136. }
  24137. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24138. Headers headers;
  24139. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24140. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24141. ws::WebSocketClient client(
  24142. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24143. ASSERT_TRUE(client.connect());
  24144. // The offer on the second field line counts too, so graphql-ws is selected
  24145. EXPECT_EQ("graphql-ws", client.subprotocol());
  24146. client.close();
  24147. }
  24148. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24149. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24150. ws::WebSocketClient client(
  24151. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24152. ASSERT_TRUE(client.connect());
  24153. // Server should not have selected any subprotocol
  24154. EXPECT_TRUE(client.subprotocol().empty());
  24155. client.close();
  24156. }
  24157. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24158. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24159. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24160. "/ws-subprotocol-unoffered",
  24161. headers);
  24162. ASSERT_TRUE(client.connect());
  24163. EXPECT_TRUE(client.subprotocol().empty());
  24164. client.close();
  24165. }
  24166. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24167. // Connect without requesting any subprotocol
  24168. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24169. "/ws-subprotocol");
  24170. ASSERT_TRUE(client.connect());
  24171. EXPECT_TRUE(client.subprotocol().empty());
  24172. client.close();
  24173. }
  24174. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24176. "/ws-echo");
  24177. client.set_tcp_nodelay(true);
  24178. client.set_connection_timeout(3, 0);
  24179. bool socket_options_called = false;
  24180. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24181. ASSERT_TRUE(client.connect());
  24182. ASSERT_TRUE(client.is_open());
  24183. EXPECT_TRUE(socket_options_called);
  24184. ASSERT_TRUE(client.send("hello"));
  24185. std::string msg;
  24186. auto result = client.read(msg);
  24187. EXPECT_EQ(result, ws::ReadResult::Text);
  24188. EXPECT_EQ(msg, "hello");
  24189. client.close();
  24190. }
  24191. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24192. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24193. "/ws-echo");
  24194. client.set_connection_timeout(std::chrono::seconds(3));
  24195. client.set_write_timeout(std::chrono::seconds(3));
  24196. // A sub-second remainder exercises the seconds/microseconds split.
  24197. client.set_read_timeout(std::chrono::milliseconds(1500));
  24198. ASSERT_TRUE(client.connect());
  24199. auto start = std::chrono::steady_clock::now();
  24200. std::string msg;
  24201. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24202. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24203. std::chrono::steady_clock::now() - start)
  24204. .count();
  24205. // Above 1s so that dropping the microseconds half of the split fails here.
  24206. // Ignoring the setter altogether would not reach this line at all: a client
  24207. // waits forever by default.
  24208. EXPECT_GE(elapsed, 1400);
  24209. EXPECT_LT(elapsed, 30000);
  24210. }
  24211. #ifndef _WIN32
  24212. // A send() that times out after part of the data went out returns the count
  24213. // written so far. Every byte of the frame must still be sent, or the peer reads
  24214. // the next frame's header and payload as the rest of this one.
  24215. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24216. signal(SIGPIPE, SIG_IGN);
  24217. const std::string large(4 * 1024 * 1024, 'A');
  24218. std::atomic<bool> large_sent{false};
  24219. std::atomic<bool> small_sent{false};
  24220. Server svr;
  24221. svr.set_write_timeout(0, 500000);
  24222. svr.set_socket_options([](socket_t sock) {
  24223. int size = 8192;
  24224. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24225. reinterpret_cast<const char *>(&size), sizeof(size));
  24226. });
  24227. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24228. large_sent = ws.send(large.data(), large.size());
  24229. small_sent = ws.send("after");
  24230. std::string msg;
  24231. while (ws.read(msg)) {}
  24232. });
  24233. auto port = svr.bind_to_any_port(HOST);
  24234. std::thread t([&]() { svr.listen_after_bind(); });
  24235. auto se = detail::scope_exit([&] {
  24236. svr.stop();
  24237. t.join();
  24238. });
  24239. svr.wait_until_ready();
  24240. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24241. std::to_string(port) + "/ws");
  24242. client.set_read_timeout(5);
  24243. client.set_socket_options([](socket_t sock) {
  24244. int size = 8192;
  24245. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24246. reinterpret_cast<const char *>(&size), sizeof(size));
  24247. });
  24248. ASSERT_TRUE(client.connect());
  24249. // Outlast the server's write timeout, then drain.
  24250. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24251. std::string msg;
  24252. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24253. EXPECT_TRUE(msg == large);
  24254. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24255. EXPECT_EQ("after", msg);
  24256. EXPECT_TRUE(large_sent);
  24257. EXPECT_TRUE(small_sent);
  24258. client.close();
  24259. }
  24260. #endif
  24261. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24262. Server svr;
  24263. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24264. if (!req.has_header("Authorization")) {
  24265. res.status = StatusCode::Unauthorized_401;
  24266. res.set_content("Unauthorized", "text/plain");
  24267. return Server::HandlerResponse::Handled;
  24268. }
  24269. return Server::HandlerResponse::Unhandled;
  24270. });
  24271. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24272. std::string msg;
  24273. while (ws.read(msg)) {
  24274. ws.send(msg);
  24275. }
  24276. });
  24277. auto port = svr.bind_to_any_port("localhost");
  24278. std::thread t([&]() { svr.listen_after_bind(); });
  24279. svr.wait_until_ready();
  24280. // Without Authorization header - should be rejected before upgrade
  24281. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24282. EXPECT_FALSE(client1.connect());
  24283. // The rejection is framed like any other HTTP response
  24284. {
  24285. Client cli("localhost", port);
  24286. Headers headers = {{"Upgrade", "websocket"},
  24287. {"Connection", "Upgrade"},
  24288. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24289. {"Sec-WebSocket-Version", "13"}};
  24290. auto res = cli.Get("/ws", headers);
  24291. ASSERT_TRUE(res);
  24292. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24293. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24294. EXPECT_EQ("Unauthorized", res->body);
  24295. }
  24296. // With Authorization header - should succeed
  24297. Headers headers = {{"Authorization", "Bearer token123"}};
  24298. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24299. headers);
  24300. ASSERT_TRUE(client2.connect());
  24301. ASSERT_TRUE(client2.send("hello"));
  24302. std::string msg;
  24303. ASSERT_TRUE(client2.read(msg));
  24304. EXPECT_EQ("hello", msg);
  24305. client2.close();
  24306. svr.stop();
  24307. t.join();
  24308. }
  24309. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24310. Server svr;
  24311. std::atomic<int> pre_routing_calls{0};
  24312. std::atomic<int> pre_request_calls{0};
  24313. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24314. pre_routing_calls++;
  24315. if (req.path == "/handled") {
  24316. res.set_content("handled", "text/plain");
  24317. return Server::HandlerResponse::Handled;
  24318. }
  24319. return Server::HandlerResponse::Unhandled;
  24320. });
  24321. svr.set_pre_request_handler([&](const Request &, Response &) {
  24322. pre_request_calls++;
  24323. return Server::HandlerResponse::Unhandled;
  24324. });
  24325. svr.Get("/http", [](const Request &, Response &res) {
  24326. res.set_content("http", "text/plain");
  24327. });
  24328. svr.WebSocket("/ws",
  24329. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24330. auto port = svr.bind_to_any_port("localhost");
  24331. std::thread t([&]() { svr.listen_after_bind(); });
  24332. auto se = detail::scope_exit([&] {
  24333. svr.stop();
  24334. t.join();
  24335. });
  24336. svr.wait_until_ready();
  24337. Headers upgrade = {{"Upgrade", "websocket"},
  24338. {"Connection", "Upgrade"},
  24339. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24340. {"Sec-WebSocket-Version", "13"}};
  24341. auto get = [&](const char *path) {
  24342. pre_routing_calls = 0;
  24343. return Client("localhost", port).Get(path, upgrade);
  24344. };
  24345. // No WebSocket route, but an HTTP one
  24346. auto res = get("/http");
  24347. ASSERT_TRUE(res);
  24348. EXPECT_EQ(StatusCode::OK_200, res->status);
  24349. EXPECT_EQ("http", res->body);
  24350. EXPECT_EQ(1, pre_routing_calls);
  24351. EXPECT_EQ(1, pre_request_calls);
  24352. // No route at all
  24353. res = get("/none");
  24354. ASSERT_TRUE(res);
  24355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24356. EXPECT_EQ(1, pre_routing_calls);
  24357. // Answered by the pre-routing handler
  24358. res = get("/handled");
  24359. ASSERT_TRUE(res);
  24360. EXPECT_EQ(StatusCode::OK_200, res->status);
  24361. EXPECT_EQ("handled", res->body);
  24362. EXPECT_EQ(1, pre_routing_calls);
  24363. // A WebSocket route
  24364. pre_routing_calls = 0;
  24365. pre_request_calls = 0;
  24366. {
  24367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24368. "/ws");
  24369. ASSERT_TRUE(client.connect());
  24370. std::string msg;
  24371. ASSERT_TRUE(client.read(msg));
  24372. EXPECT_EQ("ws", msg);
  24373. client.close();
  24374. }
  24375. EXPECT_EQ(1, pre_routing_calls);
  24376. EXPECT_EQ(1, pre_request_calls);
  24377. }
  24378. // An upgrade request answered by a hook leaves its body unread, so that body
  24379. // must not be served as the next request on the connection.
  24380. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24381. Server svr;
  24382. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24383. if (req.path == "/pre-routing") {
  24384. res.set_content("pre-routing", "text/plain");
  24385. return Server::HandlerResponse::Handled;
  24386. }
  24387. return Server::HandlerResponse::Unhandled;
  24388. });
  24389. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24390. if (req.matched_route == "/pre-request") {
  24391. res.set_content("pre-request", "text/plain");
  24392. return Server::HandlerResponse::Handled;
  24393. }
  24394. return Server::HandlerResponse::Unhandled;
  24395. });
  24396. svr.Get("/smuggled", [](const Request &, Response &res) {
  24397. res.set_content("smuggled", "text/plain");
  24398. });
  24399. svr.WebSocket("/pre-request",
  24400. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24401. auto port = svr.bind_to_any_port(HOST);
  24402. std::thread t([&]() { svr.listen_after_bind(); });
  24403. auto se = detail::scope_exit([&] {
  24404. svr.stop();
  24405. t.join();
  24406. });
  24407. svr.wait_until_ready();
  24408. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24409. for (auto path : {"/pre-routing", "/pre-request"}) {
  24410. std::string req = std::string("GET ") + path +
  24411. " HTTP/1.1\r\n"
  24412. "Host: localhost\r\n"
  24413. "Upgrade: websocket\r\n"
  24414. "Connection: Upgrade\r\n"
  24415. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24416. "Sec-WebSocket-Version: 13\r\n"
  24417. "Content-Length: " +
  24418. std::to_string(body.size()) + "\r\n\r\n" + body;
  24419. std::string res;
  24420. ASSERT_TRUE(send_request(5, req, &res, port));
  24421. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24422. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24423. // Only one response, and the body was not served as a request
  24424. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24425. }
  24426. }
  24427. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24428. Server svr;
  24429. std::atomic<int> pre_request_calls{0};
  24430. std::atomic<bool> route_matched{false};
  24431. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24432. pre_request_calls++;
  24433. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24434. if (req.get_header_value("Authorization") != "Bearer token123") {
  24435. res.status = StatusCode::Unauthorized_401;
  24436. res.set_content("Unauthorized", "text/plain");
  24437. return Server::HandlerResponse::Handled;
  24438. }
  24439. return Server::HandlerResponse::Unhandled;
  24440. });
  24441. std::atomic<bool> handler_called{false};
  24442. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24443. handler_called = true;
  24444. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24445. });
  24446. auto port = svr.bind_to_any_port("localhost");
  24447. std::thread t([&]() { svr.listen_after_bind(); });
  24448. svr.wait_until_ready();
  24449. // Without Authorization header - should be rejected before upgrade
  24450. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24451. "/ws/1");
  24452. EXPECT_FALSE(client1.connect());
  24453. EXPECT_FALSE(handler_called);
  24454. EXPECT_EQ(1, pre_request_calls);
  24455. EXPECT_TRUE(route_matched);
  24456. // The rejection is an ordinary HTTP response, not a protocol switch
  24457. {
  24458. Client cli("localhost", port);
  24459. Headers headers = {{"Upgrade", "websocket"},
  24460. {"Connection", "Upgrade"},
  24461. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24462. {"Sec-WebSocket-Version", "13"}};
  24463. auto res = cli.Get("/ws/1", headers);
  24464. ASSERT_TRUE(res);
  24465. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24466. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24467. EXPECT_EQ("Unauthorized", res->body);
  24468. }
  24469. EXPECT_FALSE(handler_called);
  24470. // With Authorization header - should succeed
  24471. Headers headers = {{"Authorization", "Bearer token123"}};
  24472. ws::WebSocketClient client2(
  24473. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24474. ASSERT_TRUE(client2.connect());
  24475. std::string msg;
  24476. ASSERT_TRUE(client2.read(msg));
  24477. EXPECT_EQ("/ws/:id 2", msg);
  24478. EXPECT_TRUE(handler_called);
  24479. client2.close();
  24480. svr.stop();
  24481. t.join();
  24482. }
  24483. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24484. static Headers websocket_upgrade_headers() {
  24485. return {{"Upgrade", "websocket"},
  24486. {"Connection", "Upgrade"},
  24487. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24488. {"Sec-WebSocket-Version", "13"},
  24489. {"Sec-WebSocket-Protocol", "chat"}};
  24490. }
  24491. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24492. Server svr;
  24493. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24494. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24495. return Server::HandlerResponse::Unhandled;
  24496. });
  24497. svr.set_pre_request_handler([](const Request &req, Response &) {
  24498. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24499. return Server::HandlerResponse::Unhandled;
  24500. });
  24501. svr.set_exception_handler(
  24502. [](const Request &, Response &res, std::exception_ptr ep) {
  24503. try {
  24504. std::rethrow_exception(ep);
  24505. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24506. });
  24507. auto handler = [](const Request &, ws::WebSocket &) {};
  24508. svr.WebSocket("/pre-routing", handler);
  24509. svr.WebSocket("/pre-request", handler);
  24510. svr.WebSocket("/sub-protocol", handler,
  24511. [](const std::vector<std::string> &) -> std::string {
  24512. throw std::runtime_error("/sub-protocol");
  24513. });
  24514. auto port = svr.bind_to_any_port(HOST);
  24515. ASSERT_GT(port, 0);
  24516. thread t = thread([&] { svr.listen_after_bind(); });
  24517. auto se = detail::scope_exit([&] {
  24518. svr.stop();
  24519. t.join();
  24520. ASSERT_FALSE(svr.is_running());
  24521. });
  24522. svr.wait_until_ready();
  24523. Client cli(HOST, port);
  24524. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24525. auto res = cli.Get(path, websocket_upgrade_headers());
  24526. if (!res) {
  24527. ADD_FAILURE() << path << ": " << to_string(res.error());
  24528. continue;
  24529. }
  24530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24531. EXPECT_EQ(path, res->body);
  24532. }
  24533. }
  24534. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24535. Server svr;
  24536. svr.set_pre_routing_handler(
  24537. [](const Request &, Response &) -> Server::HandlerResponse {
  24538. throw std::runtime_error("pre-routing");
  24539. });
  24540. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24541. auto port = svr.bind_to_any_port(HOST);
  24542. ASSERT_GT(port, 0);
  24543. thread t = thread([&] { svr.listen_after_bind(); });
  24544. auto se = detail::scope_exit([&] {
  24545. svr.stop();
  24546. t.join();
  24547. ASSERT_FALSE(svr.is_running());
  24548. });
  24549. svr.wait_until_ready();
  24550. Client cli(HOST, port);
  24551. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24552. ASSERT_TRUE(res) << to_string(res.error());
  24553. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24554. }
  24555. #endif
  24556. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24557. Server svr;
  24558. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24559. // A read timeout is how a handler gets control back. Without it, a handler
  24560. // parked in read() can never write on the connection it is reading.
  24561. ws.set_read_timeout(std::chrono::milliseconds(100));
  24562. std::string msg;
  24563. while (ws.is_open()) {
  24564. auto r = ws.read(msg);
  24565. if (r == httplib::ws::Timeout) {
  24566. ws.send("tick");
  24567. continue;
  24568. }
  24569. if (r == httplib::ws::Fail) { break; }
  24570. ws.send(msg);
  24571. }
  24572. });
  24573. auto port = svr.bind_to_any_port("localhost");
  24574. std::thread t([&]() { svr.listen_after_bind(); });
  24575. svr.wait_until_ready();
  24576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24577. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24578. ASSERT_TRUE(client.connect());
  24579. // The client sends nothing, so anything it receives came out of the
  24580. // handler's timeout path.
  24581. std::string msg;
  24582. ASSERT_EQ(client.read(msg), ws::Text);
  24583. EXPECT_EQ("tick", msg);
  24584. client.close();
  24585. svr.stop();
  24586. t.join();
  24587. }
  24588. // Stream::read may return fewer bytes than asked for. This is that contract at
  24589. // its worst -- one byte per call -- which is what a frame header straddling a
  24590. // read buffer's boundary looks like to the frame parser.
  24591. class WsByteAtATimeStream : public Stream {
  24592. public:
  24593. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24594. bool is_readable() const override { return true; }
  24595. bool wait_readable() const override { return true; }
  24596. bool wait_writable() const override { return true; }
  24597. ssize_t read(char *ptr, size_t size) override {
  24598. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24599. *ptr = data_[pos_++];
  24600. return 1;
  24601. }
  24602. ssize_t write(const char *, size_t size) override {
  24603. return static_cast<ssize_t>(size);
  24604. }
  24605. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24606. ip = "127.0.0.1";
  24607. port = 0;
  24608. }
  24609. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24610. ip = "127.0.0.1";
  24611. port = 0;
  24612. }
  24613. socket_t socket() const override { return INVALID_SOCKET; }
  24614. time_t duration() const override { return 0; }
  24615. private:
  24616. std::string data_;
  24617. size_t pos_ = 0;
  24618. };
  24619. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24620. // The payload uses the 16-bit extended length, so the header, the length
  24621. // and the mask key are all multi-byte fields here. Each used to be read
  24622. // with a single read() call, which fails as soon as one is split. The
  24623. // payload is also a little over one read chunk, so it is read in two.
  24624. std::string body;
  24625. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24626. body += static_cast<char>(i % 251);
  24627. }
  24628. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24629. std::string frame;
  24630. frame += static_cast<char>(0x81); // FIN + Text
  24631. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24632. frame += static_cast<char>(body.size() >> 8);
  24633. frame += static_cast<char>(body.size() & 0xff);
  24634. for (size_t i = 0; i < 4; i++) {
  24635. frame += static_cast<char>(mask[i]);
  24636. }
  24637. for (size_t i = 0; i < body.size(); i++) {
  24638. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24639. }
  24640. WsByteAtATimeStream strm(frame);
  24641. ws::Opcode opcode;
  24642. std::string payload;
  24643. bool fin = false;
  24644. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24645. /*expect_masked=*/true, body.size()),
  24646. ws::impl::FrameRead::Ok);
  24647. EXPECT_TRUE(fin);
  24648. EXPECT_EQ(opcode, ws::Opcode::Text);
  24649. EXPECT_EQ(payload, body);
  24650. }
  24651. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24652. std::string body(2000, 'x');
  24653. std::string frame;
  24654. frame += static_cast<char>(0x82); // FIN + Binary
  24655. frame += static_cast<char>(126); // 16-bit length follows
  24656. frame += static_cast<char>(body.size() >> 8);
  24657. frame += static_cast<char>(body.size() & 0xff);
  24658. frame += body;
  24659. detail::BufferStream strm;
  24660. strm.write(frame.data(), frame.size());
  24661. ws::Opcode opcode;
  24662. std::string payload;
  24663. bool fin;
  24664. EXPECT_EQ(
  24665. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24666. ws::impl::FrameRead::Ok);
  24667. EXPECT_EQ(body, payload);
  24668. }
  24669. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24670. // The header announces the largest payload allowed, and only 3 bytes of it
  24671. // ever arrive.
  24672. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24673. std::string frame;
  24674. frame += static_cast<char>(0x82); // FIN + Binary
  24675. frame += static_cast<char>(127); // 64-bit length follows
  24676. for (int shift = 56; shift >= 0; shift -= 8) {
  24677. frame += static_cast<char>((len >> shift) & 0xff);
  24678. }
  24679. frame += "abc";
  24680. detail::BufferStream strm;
  24681. strm.write(frame.data(), frame.size());
  24682. ws::Opcode opcode;
  24683. std::string payload;
  24684. bool fin;
  24685. EXPECT_EQ(
  24686. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24687. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24688. ws::impl::FrameRead::Fail);
  24689. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24690. }
  24691. TEST(WebSocketTest, QueryStringInHandshake) {
  24692. Server svr;
  24693. std::mutex mtx;
  24694. std::string received_target;
  24695. std::string received_token;
  24696. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24697. {
  24698. std::lock_guard<std::mutex> lock(mtx);
  24699. received_target = req.target;
  24700. if (req.has_param("token")) {
  24701. received_token = req.get_param_value("token");
  24702. }
  24703. }
  24704. std::string msg;
  24705. while (ws.read(msg)) {
  24706. ws.send(msg);
  24707. }
  24708. });
  24709. auto port = svr.bind_to_any_port("localhost");
  24710. std::thread t([&]() { svr.listen_after_bind(); });
  24711. svr.wait_until_ready();
  24712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24713. "/ws?token=ABC&session=123");
  24714. ASSERT_TRUE(client.connect());
  24715. // Round-trip ensures the handler has run and captured the request.
  24716. ASSERT_TRUE(client.send("hello"));
  24717. std::string msg;
  24718. ASSERT_TRUE(client.read(msg));
  24719. EXPECT_EQ("hello", msg);
  24720. client.close();
  24721. {
  24722. std::lock_guard<std::mutex> lock(mtx);
  24723. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24724. EXPECT_EQ("ABC", received_token);
  24725. }
  24726. svr.stop();
  24727. t.join();
  24728. }
  24729. // Run a handshake against a throwaway server and hand the request the server
  24730. // received back to the caller, so tests can assert on the headers the client
  24731. // actually put on the wire.
  24732. static void capture_websocket_handshake_request(
  24733. const Headers &client_headers,
  24734. std::function<void(const Request &, int port)> verify) {
  24735. Server svr;
  24736. std::mutex mtx;
  24737. Request received;
  24738. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24739. {
  24740. std::lock_guard<std::mutex> lock(mtx);
  24741. received = req;
  24742. }
  24743. std::string msg;
  24744. while (ws.read(msg)) {
  24745. ws.send(msg);
  24746. }
  24747. });
  24748. auto port = svr.bind_to_any_port("localhost");
  24749. std::thread t([&]() { svr.listen_after_bind(); });
  24750. auto se = detail::scope_exit([&] {
  24751. svr.stop();
  24752. t.join();
  24753. });
  24754. svr.wait_until_ready();
  24755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24756. client_headers);
  24757. ASSERT_TRUE(client.connect());
  24758. ASSERT_TRUE(client.send("hello"));
  24759. std::string msg;
  24760. ASSERT_TRUE(client.read(msg));
  24761. client.close();
  24762. {
  24763. std::lock_guard<std::mutex> lock(mtx);
  24764. verify(received, port);
  24765. }
  24766. }
  24767. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24768. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24769. // Non-default port must be present in the Host header. Default ports
  24770. // (80/443) are omitted; that logic is covered by
  24771. // MakeHostAndPortStringTest.
  24772. EXPECT_EQ("localhost:" + std::to_string(port),
  24773. req.get_header_value("Host"));
  24774. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24775. req.get_header_value("User-Agent"));
  24776. EXPECT_FALSE(req.has_header("Accept"));
  24777. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24778. EXPECT_FALSE(req.has_header("Content-Length"));
  24779. });
  24780. }
  24781. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24782. capture_websocket_handshake_request(
  24783. {{"Host", "example.com"},
  24784. {"User-Agent", "custom-agent"},
  24785. {"X-Custom", "value"}},
  24786. [](const Request &req, int) {
  24787. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24788. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24789. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24790. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24791. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24792. });
  24793. }
  24794. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24795. capture_websocket_handshake_request(
  24796. {{"Upgrade", "bogus"},
  24797. {"Connection", "close"},
  24798. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24799. {"Sec-WebSocket-Version", "8"}},
  24800. [](const Request &req, int) {
  24801. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24802. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24803. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24804. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24805. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24806. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24807. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24808. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24809. req.get_header_value("Sec-WebSocket-Key"));
  24810. });
  24811. }
  24812. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24813. // A header the client refuses to send must abort the handshake before any
  24814. // part of it reaches the wire; a lone request line would otherwise sit in
  24815. // the peer's buffer as a truncated request.
  24816. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24817. ASSERT_NE(INVALID_SOCKET, srv);
  24818. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24819. sockaddr_in addr{};
  24820. addr.sin_family = AF_INET;
  24821. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24822. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24823. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24824. ASSERT_EQ(0, ::listen(srv, 1));
  24825. sockaddr_in bound{};
  24826. socklen_t bound_len = sizeof(bound);
  24827. ASSERT_EQ(
  24828. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24829. auto port = ntohs(bound.sin_port);
  24830. ssize_t received = -1;
  24831. std::thread t([&] {
  24832. // Bound every blocking call so a regression fails the test with a bad
  24833. // value instead of hanging the suite.
  24834. fd_set rfds;
  24835. FD_ZERO(&rfds);
  24836. FD_SET(srv, &rfds);
  24837. timeval tv{5, 0};
  24838. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24839. 0) {
  24840. return;
  24841. }
  24842. sockaddr_in cli_addr{};
  24843. socklen_t cli_len = sizeof(cli_addr);
  24844. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24845. if (cli == INVALID_SOCKET) { return; }
  24846. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24847. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24848. char buf[4096];
  24849. received = ::recv(cli, buf, sizeof(buf), 0);
  24850. });
  24851. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24852. // connect() has already shut the socket down by the time it returns false,
  24853. // so the peer sees EOF without waiting for the client to be destroyed.
  24854. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24855. {{"X-Bad", "a\r\nInjected: 1"}});
  24856. EXPECT_FALSE(client.connect());
  24857. t.join();
  24858. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24859. EXPECT_EQ(0, received);
  24860. }
  24861. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24862. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24863. // contains "upgrade" as a substring is a different token and must not
  24864. // start a WebSocket handshake.
  24865. auto make_request = [](const std::vector<std::string> &connection_values) {
  24866. Request req;
  24867. req.method = "GET";
  24868. req.headers.emplace("Upgrade", "websocket");
  24869. for (const auto &value : connection_values) {
  24870. req.headers.emplace("Connection", value);
  24871. }
  24872. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24873. req.headers.emplace("Sec-WebSocket-Version", "13");
  24874. return req;
  24875. };
  24876. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24877. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24878. EXPECT_TRUE(
  24879. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24880. EXPECT_TRUE(
  24881. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24882. EXPECT_TRUE(
  24883. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24884. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24885. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24886. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24887. EXPECT_FALSE(
  24888. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24889. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24890. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24891. }
  24892. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24893. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24894. // asks recipients to match each protocol-name case-insensitively, and RFC
  24895. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24896. // client naming websocket alongside another protocol, or on a second field
  24897. // line, is offering websocket; a value that merely contains "websocket" as a
  24898. // substring is a different protocol name and is not.
  24899. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24900. Request req;
  24901. req.method = "GET";
  24902. for (const auto &value : upgrade_values) {
  24903. req.headers.emplace("Upgrade", value);
  24904. }
  24905. req.headers.emplace("Connection", "Upgrade");
  24906. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24907. req.headers.emplace("Sec-WebSocket-Version", "13");
  24908. return req;
  24909. };
  24910. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24911. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24912. EXPECT_TRUE(
  24913. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24914. EXPECT_TRUE(
  24915. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24916. EXPECT_TRUE(
  24917. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24918. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24919. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24920. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24921. EXPECT_FALSE(
  24922. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24923. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24924. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24925. }
  24926. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24927. Server svr;
  24928. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24929. auto port = svr.bind_to_any_port("localhost");
  24930. std::thread t([&]() { svr.listen_after_bind(); });
  24931. auto se = detail::scope_exit([&] {
  24932. svr.stop();
  24933. t.join();
  24934. });
  24935. svr.wait_until_ready();
  24936. Headers headers = {{"Upgrade", "websocket"},
  24937. {"Connection", "notupgrade"},
  24938. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24939. {"Sec-WebSocket-Version", "13"}};
  24940. Client cli("localhost", port);
  24941. auto res = cli.Get("/ws", headers);
  24942. // The route exists only as a WebSocket route, so a request that fails the
  24943. // handshake check falls through to ordinary routing.
  24944. ASSERT_TRUE(res);
  24945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24946. }
  24947. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24948. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24949. // Connection value is the only thing left for the client to reject.
  24950. Server svr;
  24951. svr.Get("/ws", [](const Request &req, Response &res) {
  24952. res.status = StatusCode::SwitchingProtocol_101;
  24953. res.set_header("Upgrade", "websocket");
  24954. res.set_header("Connection", "notupgrade");
  24955. res.set_header("Sec-WebSocket-Accept",
  24956. detail::websocket_accept_key(
  24957. req.get_header_value("Sec-WebSocket-Key")));
  24958. });
  24959. auto port = svr.bind_to_any_port("localhost");
  24960. std::thread t([&]() { svr.listen_after_bind(); });
  24961. auto se = detail::scope_exit([&] {
  24962. svr.stop();
  24963. t.join();
  24964. });
  24965. svr.wait_until_ready();
  24966. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24967. auto res = client.connect();
  24968. EXPECT_FALSE(res);
  24969. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24970. EXPECT_FALSE(client.is_open());
  24971. }
  24972. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24973. Server svr;
  24974. svr.Get("/ws", [](const Request &req, Response &res) {
  24975. res.status = StatusCode::SwitchingProtocol_101;
  24976. res.set_header("Upgrade", "websocket");
  24977. res.set_header("Connection", "Upgrade");
  24978. res.set_header("Sec-WebSocket-Accept",
  24979. detail::websocket_accept_key(
  24980. req.get_header_value("Sec-WebSocket-Key")));
  24981. res.set_header("Sec-WebSocket-Protocol", "admin");
  24982. });
  24983. auto port = svr.bind_to_any_port("localhost");
  24984. std::thread t([&]() { svr.listen_after_bind(); });
  24985. auto se = detail::scope_exit([&] {
  24986. svr.stop();
  24987. t.join();
  24988. });
  24989. svr.wait_until_ready();
  24990. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24991. // Server selects a subprotocol the client never offered
  24992. {
  24993. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24994. ws::WebSocketClient client(url, headers);
  24995. auto res = client.connect();
  24996. EXPECT_FALSE(res);
  24997. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24998. EXPECT_FALSE(client.is_open());
  24999. EXPECT_TRUE(client.subprotocol().empty());
  25000. }
  25001. // Client offered none but the server named one anyway
  25002. {
  25003. ws::WebSocketClient client(url);
  25004. auto res = client.connect();
  25005. EXPECT_FALSE(res);
  25006. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25007. EXPECT_FALSE(client.is_open());
  25008. EXPECT_TRUE(client.subprotocol().empty());
  25009. }
  25010. }
  25011. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25012. // The socket path doubles as the URL host, so it must not contain '/'.
  25013. const char *shard = getenv("GTEST_SHARD_INDEX");
  25014. const std::string sock_path =
  25015. shard ? std::string("httplib-ws-") + shard + ".sock"
  25016. : std::string("httplib-ws.sock");
  25017. std::remove(sock_path.c_str());
  25018. Server svr;
  25019. std::mutex mtx;
  25020. std::string received_host;
  25021. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25022. {
  25023. std::lock_guard<std::mutex> lock(mtx);
  25024. received_host = req.get_header_value("Host");
  25025. }
  25026. std::string msg;
  25027. while (ws.read(msg)) {
  25028. ws.send(msg);
  25029. }
  25030. });
  25031. svr.set_address_family(AF_UNIX);
  25032. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25033. auto se = detail::scope_exit([&] {
  25034. svr.stop();
  25035. t.join();
  25036. std::remove(sock_path.c_str());
  25037. });
  25038. svr.wait_until_ready();
  25039. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25040. client.set_address_family(AF_UNIX);
  25041. ASSERT_TRUE(client.connect());
  25042. ASSERT_TRUE(client.send("hello"));
  25043. std::string msg;
  25044. ASSERT_TRUE(client.read(msg));
  25045. client.close();
  25046. {
  25047. std::lock_guard<std::mutex> lock(mtx);
  25048. // There is no host:port for a Unix socket, so the same "localhost"
  25049. // placeholder the HTTP client uses is expected.
  25050. EXPECT_EQ("localhost", received_host);
  25051. }
  25052. }
  25053. // Two threads must never parse WebSocket frames from the same stream.
  25054. // close() used to read the peer's Close reply with its own frame read, so it
  25055. // raced a reader thread that was in the middle of a payload: the payload loop
  25056. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25057. // so bytes taken by close() were replaced with bytes from further along the
  25058. // stream. The message kept its length and silently changed content.
  25059. //
  25060. // The raw peer below sends a frame header plus part of the payload, waits for
  25061. // the handler to call close(), and only then sends the rest. Whichever thread
  25062. // would win the race for those bytes, the message must arrive intact, because
  25063. // close() must not touch the stream while read() owns it.
  25064. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25065. #ifndef _WIN32
  25066. signal(SIGPIPE, SIG_IGN);
  25067. #endif
  25068. const size_t payload_len = 120; // fits the 7-bit length field
  25069. const size_t prefix_len = 8;
  25070. const int attempts = 8;
  25071. std::string expected(payload_len, '\0');
  25072. for (size_t i = 0; i < payload_len; i++) {
  25073. expected[i] = static_cast<char>('a' + i % 26);
  25074. }
  25075. std::atomic<bool> peer_stalled{false};
  25076. std::atomic<bool> handler_done{false};
  25077. std::mutex received_mutex;
  25078. std::vector<std::string> received;
  25079. // Bound every wait, so a regression fails the test instead of hanging the
  25080. // suite.
  25081. auto wait_for = [](const std::atomic<bool> &flag) {
  25082. for (int i = 0; i < 500 && !flag; i++) {
  25083. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25084. }
  25085. };
  25086. Server svr;
  25087. svr.set_websocket_ping_interval(0);
  25088. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25089. std::thread reader([&]() {
  25090. std::string msg;
  25091. while (ws.read(msg)) {
  25092. std::lock_guard<std::mutex> guard(received_mutex);
  25093. received.push_back(msg);
  25094. }
  25095. });
  25096. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25097. // inside read_websocket_frame() when close() runs.
  25098. wait_for(peer_stalled);
  25099. ws.close();
  25100. reader.join();
  25101. handler_done = true;
  25102. });
  25103. auto port = svr.bind_to_any_port("127.0.0.1");
  25104. std::thread t([&]() { svr.listen_after_bind(); });
  25105. auto se = detail::scope_exit([&] {
  25106. svr.stop();
  25107. t.join();
  25108. });
  25109. svr.wait_until_ready();
  25110. auto send_bytes = [](socket_t s, const std::string &data) {
  25111. #ifdef _WIN32
  25112. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25113. #else
  25114. auto n = ::send(s, data.data(), data.size(), 0);
  25115. #endif
  25116. return n == static_cast<decltype(n)>(data.size());
  25117. };
  25118. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25119. // Every length used here fits the 7-bit length field.
  25120. auto masked_header = [](uint8_t first_byte, size_t len) {
  25121. std::string h;
  25122. h += static_cast<char>(first_byte);
  25123. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25124. h.append(4, '\0'); // mask key
  25125. return h;
  25126. };
  25127. for (int attempt = 0; attempt < attempts; attempt++) {
  25128. peer_stalled = false;
  25129. handler_done = false;
  25130. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25131. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25132. auto se_sock = detail::scope_exit([&] {
  25133. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25134. });
  25135. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25136. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25137. sockaddr_in addr{};
  25138. addr.sin_family = AF_INET;
  25139. addr.sin_port = htons(static_cast<uint16_t>(port));
  25140. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25141. ASSERT_EQ(
  25142. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25143. << "attempt " << attempt;
  25144. ASSERT_TRUE(send_bytes(sock,
  25145. "GET /ws HTTP/1.1\r\n"
  25146. "Host: 127.0.0.1\r\n"
  25147. "Upgrade: websocket\r\n"
  25148. "Connection: Upgrade\r\n"
  25149. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25150. "Sec-WebSocket-Version: 13\r\n"
  25151. "\r\n"))
  25152. << "attempt " << attempt;
  25153. std::string response;
  25154. while (response.find("\r\n\r\n") == std::string::npos) {
  25155. char buf[512];
  25156. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25157. if (n <= 0) { break; }
  25158. response.append(buf, static_cast<size_t>(n));
  25159. }
  25160. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25161. << "attempt " << attempt;
  25162. // Send the header of a Binary message but only the first prefix_len bytes
  25163. // of its payload, leaving the reader thread stalled inside the payload.
  25164. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25165. expected.substr(0, prefix_len)))
  25166. << "attempt " << attempt;
  25167. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25168. peer_stalled = true;
  25169. // Let close() send its Close frame and park in its own read before the
  25170. // rest of the payload arrives, so both threads are waiting for it.
  25171. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25172. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25173. close_frame += static_cast<char>(0x03); // status 1000
  25174. close_frame += static_cast<char>(0xE8);
  25175. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25176. << "attempt " << attempt;
  25177. // Closing the peer releases the reader thread even on the buggy path,
  25178. // where it waits for bytes another thread already consumed.
  25179. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25180. detail::close_socket(sock);
  25181. sock = INVALID_SOCKET;
  25182. wait_for(handler_done);
  25183. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25184. }
  25185. std::lock_guard<std::mutex> guard(received_mutex);
  25186. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25187. << "a message in flight when close() ran was dropped";
  25188. for (size_t i = 0; i < received.size(); i++) {
  25189. EXPECT_EQ(expected, received[i]) << "message " << i;
  25190. }
  25191. }
  25192. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25193. // returning the socket, or INVALID_SOCKET.
  25194. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25195. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25196. if (sock == INVALID_SOCKET) { return sock; }
  25197. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25198. sockaddr_in addr{};
  25199. addr.sin_family = AF_INET;
  25200. addr.sin_port = htons(static_cast<uint16_t>(port));
  25201. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25202. std::string req = "GET " + path +
  25203. " HTTP/1.1\r\n"
  25204. "Host: 127.0.0.1\r\n"
  25205. "Upgrade: websocket\r\n"
  25206. "Connection: Upgrade\r\n"
  25207. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25208. "Sec-WebSocket-Version: 13\r\n"
  25209. "\r\n";
  25210. std::string res;
  25211. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25212. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25213. static_cast<ssize_t>(req.size())) {
  25214. char c;
  25215. while (res.find("\r\n\r\n") == std::string::npos &&
  25216. ::recv(sock, &c, 1, 0) == 1) {
  25217. res += c;
  25218. }
  25219. }
  25220. if (res.find(" 101 ") == std::string::npos) {
  25221. detail::close_socket(sock);
  25222. return INVALID_SOCKET;
  25223. }
  25224. return sock;
  25225. }
  25226. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25227. // The payload must fit the 7-bit length field.
  25228. static std::string masked_frame(uint8_t first_byte,
  25229. const std::string &payload) {
  25230. std::string f;
  25231. f += static_cast<char>(first_byte);
  25232. f += static_cast<char>(0x80 | payload.size());
  25233. f.append(4, '\0');
  25234. return f + payload;
  25235. }
  25236. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25237. std::atomic<bool> done{false};
  25238. std::string received;
  25239. Server svr;
  25240. svr.set_websocket_ping_interval(0);
  25241. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25242. std::string msg;
  25243. if (ws.read(msg) == ws::Binary) { received = msg; }
  25244. done = true;
  25245. });
  25246. auto port = svr.bind_to_any_port("127.0.0.1");
  25247. std::thread t([&]() { svr.listen_after_bind(); });
  25248. auto se = detail::scope_exit([&] {
  25249. svr.stop();
  25250. t.join();
  25251. });
  25252. svr.wait_until_ready();
  25253. auto sock = connect_raw_websocket(port, "/ws");
  25254. ASSERT_NE(INVALID_SOCKET, sock);
  25255. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25256. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25257. masked_frame(0x89, "p") + // FIN + Ping
  25258. masked_frame(0x80, "lo"); // FIN + Continuation
  25259. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25260. for (int i = 0; i < 500 && !done; i++) {
  25261. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25262. }
  25263. ASSERT_TRUE(done);
  25264. EXPECT_EQ("Hello", received);
  25265. // The Ping between the fragments is answered with a Pong.
  25266. char pong[3];
  25267. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25268. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25269. }
  25270. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25271. Server svr;
  25272. svr.set_websocket_ping_interval(-1);
  25273. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25274. std::string msg;
  25275. while (ws.read(msg)) {}
  25276. });
  25277. auto port = svr.bind_to_any_port("127.0.0.1");
  25278. std::thread t([&]() { svr.listen_after_bind(); });
  25279. auto se = detail::scope_exit([&] {
  25280. svr.stop();
  25281. t.join();
  25282. });
  25283. svr.wait_until_ready();
  25284. auto sock = connect_raw_websocket(port, "/ws");
  25285. ASSERT_NE(INVALID_SOCKET, sock);
  25286. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25287. // Nothing comes while the client stays quiet.
  25288. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25289. char c;
  25290. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25291. }
  25292. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25293. // and that has to end a read() already waiting on the peer, on every platform.
  25294. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25295. // The peer sends no pings, and its handler never calls read(), which is
  25296. // where pongs are written.
  25297. std::mutex mutex;
  25298. std::condition_variable cv;
  25299. auto release = false;
  25300. svr.set_websocket_ping_interval(0);
  25301. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25302. std::unique_lock<std::mutex> lock(mutex);
  25303. cv.wait(lock, [&] { return release; });
  25304. });
  25305. auto port = svr.bind_to_any_port(HOST);
  25306. std::thread t([&]() { svr.listen_after_bind(); });
  25307. auto se = detail::scope_exit([&] {
  25308. {
  25309. std::lock_guard<std::mutex> lock(mutex);
  25310. release = true;
  25311. }
  25312. cv.notify_all();
  25313. svr.stop();
  25314. t.join();
  25315. });
  25316. svr.wait_until_ready();
  25317. ws::WebSocketClient client(std::string(scheme) +
  25318. "://localhost:" + std::to_string(port) + "/ws");
  25319. #ifdef CPPHTTPLIB_SSL_ENABLED
  25320. client.enable_server_certificate_verification(false);
  25321. #endif
  25322. // A ping a second, given up on after two go unanswered: about 3s
  25323. client.set_websocket_ping_interval(1);
  25324. client.set_websocket_max_missed_pongs(2);
  25325. // Well past that, so that a read the timeout ends instead stands out
  25326. client.set_read_timeout(10);
  25327. ASSERT_TRUE(client.connect());
  25328. auto start = std::chrono::steady_clock::now();
  25329. std::string msg;
  25330. EXPECT_EQ(ws::Fail, client.read(msg));
  25331. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25332. std::chrono::steady_clock::now() - start)
  25333. .count(),
  25334. 6000);
  25335. EXPECT_FALSE(client.is_open());
  25336. }
  25337. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25338. Server svr;
  25339. check_pong_timeout_ends_read(svr, "ws");
  25340. }
  25341. #ifdef CPPHTTPLIB_SSL_ENABLED
  25342. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25344. ASSERT_TRUE(svr.is_valid());
  25345. check_pong_timeout_ends_read(svr, "wss");
  25346. }
  25347. #endif
  25348. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25349. Server svr;
  25350. svr.set_websocket_ping_interval(0);
  25351. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25352. std::string msg;
  25353. while (ws.read(msg)) {}
  25354. });
  25355. auto port = svr.bind_to_any_port("127.0.0.1");
  25356. std::thread t([&]() { svr.listen_after_bind(); });
  25357. auto se = detail::scope_exit([&] {
  25358. svr.stop();
  25359. t.join();
  25360. });
  25361. svr.wait_until_ready();
  25362. // Each Close payload and the reply it should get: an echo when valid, 1002
  25363. // otherwise.
  25364. std::vector<std::pair<std::string, std::string>> cases = {
  25365. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25366. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25367. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25368. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25369. };
  25370. // Also between the fragments of a message.
  25371. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25372. for (const auto &c : cases) {
  25373. auto sock = connect_raw_websocket(port, "/ws");
  25374. ASSERT_NE(INVALID_SOCKET, sock);
  25375. auto frames = prefix + masked_frame(0x88, c.first);
  25376. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25377. std::string reply;
  25378. char buf[256];
  25379. while (reply.size() < 2 + c.second.size()) {
  25380. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25381. if (n <= 0) { break; }
  25382. reply.append(buf, static_cast<size_t>(n));
  25383. }
  25384. detail::close_socket(sock);
  25385. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25386. c.second,
  25387. reply);
  25388. }
  25389. }
  25390. }
  25391. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25392. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25393. protected:
  25394. void SetUp() override {
  25395. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25396. SERVER_PRIVATE_KEY_FILE);
  25397. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25398. std::string msg;
  25399. ws::ReadResult ret;
  25400. while ((ret = ws.read(msg))) {
  25401. if (ret == ws::Binary) {
  25402. ws.send(msg.data(), msg.size());
  25403. } else {
  25404. ws.send(msg);
  25405. }
  25406. }
  25407. });
  25408. port_ = server_->bind_to_any_port(HOST);
  25409. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25410. server_->wait_until_ready();
  25411. }
  25412. void TearDown() override {
  25413. server_->stop();
  25414. if (server_thread_.joinable()) { server_thread_.join(); }
  25415. }
  25416. std::unique_ptr<SSLServer> server_;
  25417. std::thread server_thread_;
  25418. int port_ = 0;
  25419. };
  25420. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25421. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25422. {
  25423. ws::WebSocketClient client(url);
  25424. client.enable_server_certificate_verification(false);
  25425. auto calls = 0;
  25426. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25427. calls++;
  25428. return false;
  25429. });
  25430. EXPECT_FALSE(client.connect());
  25431. EXPECT_GT(calls, 0);
  25432. }
  25433. {
  25434. ws::WebSocketClient client(url);
  25435. client.enable_server_certificate_verification(false);
  25436. client.set_session_verifier([](tls::session_t) {
  25437. return SSLVerifierResponse::CertificateRejected;
  25438. });
  25439. EXPECT_FALSE(client.connect());
  25440. }
  25441. {
  25442. ws::WebSocketClient client(url);
  25443. client.enable_server_certificate_verification(false);
  25444. client.set_session_verifier([](tls::session_t) {
  25445. return SSLVerifierResponse::CertificateAccepted;
  25446. });
  25447. EXPECT_TRUE(client.connect());
  25448. }
  25449. }
  25450. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25451. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25452. "/ws-echo");
  25453. client.enable_server_certificate_verification(false);
  25454. ASSERT_TRUE(client.connect());
  25455. ASSERT_TRUE(client.is_open());
  25456. ASSERT_TRUE(client.send("Hello WSS"));
  25457. std::string msg;
  25458. EXPECT_EQ(ws::Text, client.read(msg));
  25459. EXPECT_EQ("Hello WSS", msg);
  25460. client.close();
  25461. }
  25462. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25463. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25464. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25465. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25466. // client (without calling close() first) is the only path that runs
  25467. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25468. // bug exactly.
  25469. //
  25470. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25471. // when linked against an instrumented libssl; run under Valgrind to catch it
  25472. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25473. // suite (the freed session otherwise stalls on the close handshake) — this test
  25474. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25475. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25476. {
  25477. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25478. "/ws-echo");
  25479. client.enable_server_certificate_verification(false);
  25480. client.set_read_timeout(2, 0);
  25481. client.set_write_timeout(2, 0);
  25482. ASSERT_TRUE(client.connect());
  25483. ASSERT_TRUE(client.is_open());
  25484. ASSERT_TRUE(client.send("still open"));
  25485. // Intentionally do NOT call client.close(): leaving scope runs
  25486. // shutdown_and_close() with the WebSocket still open, which must send the
  25487. // close frame while the TLS session is still alive.
  25488. }
  25489. }
  25490. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25491. // shutdown_and_close() at the start of connect(), reproducing the same
  25492. // use-after-free within the test body rather than at scope exit. The second
  25493. // connect must succeed and echo, proving the close handshake ran over a live
  25494. // session. See the note above about memory-tool requirements.
  25495. TEST_F(WebSocketSSLIntegrationTest,
  25496. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25497. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25498. "/ws-echo");
  25499. client.enable_server_certificate_verification(false);
  25500. client.set_read_timeout(2, 0);
  25501. client.set_write_timeout(2, 0);
  25502. ASSERT_TRUE(client.connect());
  25503. ASSERT_TRUE(client.is_open());
  25504. ASSERT_TRUE(client.send("still open"));
  25505. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25506. // the still-open connection, which must not touch a freed TLS session.
  25507. ASSERT_TRUE(client.connect());
  25508. ASSERT_TRUE(client.is_open());
  25509. ASSERT_TRUE(client.send("after reconnect"));
  25510. std::string msg;
  25511. EXPECT_EQ(ws::Text, client.read(msg));
  25512. EXPECT_EQ("after reconnect", msg);
  25513. client.close();
  25514. }
  25515. #endif
  25516. #ifdef CPPHTTPLIB_SSL_ENABLED
  25517. class WebSocketSSLCATest : public ::testing::Test {
  25518. protected:
  25519. void SetUp() override {
  25520. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25521. SERVER_PRIVATE_KEY_FILE);
  25522. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25523. std::string msg;
  25524. while (ws.read(msg)) {
  25525. ws.send(msg);
  25526. }
  25527. });
  25528. port_ = server_->bind_to_any_port("127.0.0.1");
  25529. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25530. server_->wait_until_ready();
  25531. }
  25532. void TearDown() override {
  25533. server_->stop();
  25534. if (server_thread_.joinable()) { server_thread_.join(); }
  25535. }
  25536. std::string url() const {
  25537. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25538. }
  25539. std::unique_ptr<SSLServer> server_;
  25540. std::thread server_thread_;
  25541. int port_ = 0;
  25542. };
  25543. // A custom CA loaded as PEM verifies the server with full certificate
  25544. // verification enabled
  25545. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25546. ws::WebSocketClient client(url());
  25547. std::string cert;
  25548. read_file(SERVER_CERT2_FILE, cert);
  25549. client.load_ca_cert_store(cert.c_str(), cert.size());
  25550. ASSERT_TRUE(client.connect());
  25551. ASSERT_TRUE(client.send("hello"));
  25552. std::string msg;
  25553. EXPECT_EQ(ws::Text, client.read(msg));
  25554. EXPECT_EQ("hello", msg);
  25555. client.close();
  25556. }
  25557. // A custom CA that does not cover the server must fail verification (the
  25558. // custom CA is exclusive; system certs are not loaded alongside it)
  25559. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25560. ws::WebSocketClient client(url());
  25561. std::string cert;
  25562. read_file(CLIENT_CA_CERT_FILE, cert);
  25563. client.load_ca_cert_store(cert.c_str(), cert.size());
  25564. auto res = client.connect();
  25565. ASSERT_FALSE(res);
  25566. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25567. EXPECT_EQ(-1, res.status());
  25568. EXPECT_NE(0u, res.ssl_backend_error());
  25569. }
  25570. // The same CA as a file path rather than PEM in memory
  25571. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25572. ws::WebSocketClient client(url());
  25573. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25574. ASSERT_TRUE(client.connect());
  25575. ASSERT_TRUE(client.send("hello"));
  25576. std::string msg;
  25577. EXPECT_EQ(ws::Text, client.read(msg));
  25578. EXPECT_EQ("hello", msg);
  25579. client.close();
  25580. }
  25581. // ...and a CA file that does not cover the server still fails, so it is the
  25582. // path above that decides the outcome
  25583. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25584. ws::WebSocketClient client(url());
  25585. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25586. ASSERT_FALSE(client.connect());
  25587. }
  25588. // Regression test: reconnecting with a native custom CA store used to reuse
  25589. // a store handle the previous TLS context had already freed (use-after-free
  25590. // under the OpenSSL backend). The context now lives as long as the client.
  25591. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25592. ws::WebSocketClient client(url());
  25593. std::string cert;
  25594. read_file(SERVER_CERT2_FILE, cert);
  25595. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25596. ASSERT_TRUE(client.connect());
  25597. client.close();
  25598. ASSERT_TRUE(client.connect());
  25599. ASSERT_TRUE(client.send("again"));
  25600. std::string msg;
  25601. EXPECT_EQ(ws::Text, client.read(msg));
  25602. EXPECT_EQ("again", msg);
  25603. client.close();
  25604. }
  25605. // Regression test: a certificate with a trusted chain but no identity match
  25606. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25607. // verification entirely for IP hosts, so this connection succeeded there.
  25608. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25609. // chain verification while the identity check must still fail.
  25610. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25612. ASSERT_TRUE(svr.is_valid());
  25613. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25614. std::string msg;
  25615. while (ws.read(msg)) {
  25616. ws.send(msg);
  25617. }
  25618. });
  25619. auto port = svr.bind_to_any_port("127.0.0.1");
  25620. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25621. auto se = detail::scope_exit([&] {
  25622. svr.stop();
  25623. t.join();
  25624. });
  25625. svr.wait_until_ready();
  25626. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25627. "/echo");
  25628. std::string cert;
  25629. read_file(SERVER_CERT_FILE, cert);
  25630. client.load_ca_cert_store(cert.c_str(), cert.size());
  25631. ASSERT_FALSE(client.connect());
  25632. }
  25633. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25634. // SNI, so nothing binds the host name to the TLS session. These bind the
  25635. // server to "localhost" instead, the only shape that exercises the SNI and
  25636. // hostname-verification path with certificate verification left enabled.
  25637. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25638. protected:
  25639. void Start(const char *cert_file) {
  25640. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25641. SERVER_PRIVATE_KEY_FILE);
  25642. ASSERT_TRUE(server_->is_valid());
  25643. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25644. std::string msg;
  25645. while (ws.read(msg)) {
  25646. ws.send(msg);
  25647. }
  25648. });
  25649. port_ = server_->bind_to_any_port("localhost");
  25650. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25651. server_->wait_until_ready();
  25652. }
  25653. void TearDown() override {
  25654. if (server_) { server_->stop(); }
  25655. if (server_thread_.joinable()) { server_thread_.join(); }
  25656. }
  25657. std::string url() const {
  25658. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25659. }
  25660. std::unique_ptr<SSLServer> server_;
  25661. std::thread server_thread_;
  25662. int port_ = 0;
  25663. };
  25664. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25665. // out and the connection is usable
  25666. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25667. Start(SERVER_CERT2_FILE);
  25668. ws::WebSocketClient client(url());
  25669. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25670. ASSERT_TRUE(client.connect());
  25671. ASSERT_TRUE(client.send("hello"));
  25672. std::string msg;
  25673. EXPECT_EQ(ws::Text, client.read(msg));
  25674. EXPECT_EQ("hello", msg);
  25675. client.close();
  25676. }
  25677. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25678. // while the identity check must still reject "localhost"
  25679. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25680. Start(SERVER_CERT_FILE);
  25681. ws::WebSocketClient client(url());
  25682. client.set_ca_cert_path(SERVER_CERT_FILE);
  25683. auto res = client.connect();
  25684. ASSERT_FALSE(res);
  25685. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25686. EXPECT_EQ(-1, res.status());
  25687. }
  25688. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25689. // disabled: the chain is still checked, only the identity check is skipped
  25690. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25691. Start(SERVER_CERT_FILE);
  25692. ws::WebSocketClient client(url());
  25693. client.set_ca_cert_path(SERVER_CERT_FILE);
  25694. client.enable_server_hostname_verification(false);
  25695. ASSERT_TRUE(client.connect());
  25696. ASSERT_TRUE(client.send("hello"));
  25697. std::string msg;
  25698. EXPECT_EQ(ws::Text, client.read(msg));
  25699. EXPECT_EQ("hello", msg);
  25700. client.close();
  25701. }
  25702. // A CA that did not sign the server certificate fails the chain, even though
  25703. // the name would match
  25704. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25705. Start(SERVER_CERT2_FILE);
  25706. ws::WebSocketClient client(url());
  25707. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25708. ASSERT_FALSE(client.connect());
  25709. }
  25710. // With verification disabled, neither the chain nor the name is checked
  25711. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25712. Start(SERVER_CERT_FILE);
  25713. ws::WebSocketClient client(url());
  25714. client.enable_server_certificate_verification(false);
  25715. ASSERT_TRUE(client.connect());
  25716. ASSERT_TRUE(client.send("hello"));
  25717. std::string msg;
  25718. EXPECT_EQ(ws::Text, client.read(msg));
  25719. EXPECT_EQ("hello", msg);
  25720. client.close();
  25721. }
  25722. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25723. protected:
  25724. void SetUp() override {
  25725. server_ = httplib::detail::make_unique<SSLServer>(
  25726. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25727. ASSERT_TRUE(server_->is_valid());
  25728. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25729. std::string msg;
  25730. while (ws.read(msg)) {
  25731. ws.send(msg);
  25732. }
  25733. });
  25734. port_ = server_->bind_to_any_port("localhost");
  25735. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25736. server_->wait_until_ready();
  25737. }
  25738. void TearDown() override {
  25739. server_->stop();
  25740. if (server_thread_.joinable()) { server_thread_.join(); }
  25741. }
  25742. std::string url() const {
  25743. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25744. }
  25745. void ConnectWithClientCert(const std::string &client_cert_file,
  25746. const std::string &client_private_key_file,
  25747. const char *private_key_password) {
  25748. std::string cert_pem, key_pem;
  25749. read_file(client_cert_file, cert_pem);
  25750. read_file(client_private_key_file, key_pem);
  25751. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25752. key_pem.c_str(), key_pem.size(),
  25753. private_key_password};
  25754. ConnectWithPem(pem);
  25755. }
  25756. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25757. ws::WebSocketClient client(url(), pem);
  25758. ASSERT_TRUE(client.is_valid());
  25759. client.enable_server_certificate_verification(false);
  25760. ASSERT_TRUE(client.connect());
  25761. ASSERT_TRUE(client.send("hello"));
  25762. std::string msg;
  25763. EXPECT_EQ(ws::Text, client.read(msg));
  25764. EXPECT_EQ("hello", msg);
  25765. client.close();
  25766. }
  25767. std::unique_ptr<SSLServer> server_;
  25768. std::thread server_thread_;
  25769. int port_ = 0;
  25770. };
  25771. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25772. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25773. }
  25774. // Control for the tests above: the fixture's server really does require a
  25775. // client certificate, so it is the PEM the constructor installed that decides
  25776. // the outcome.
  25777. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25778. ws::WebSocketClient client(url());
  25779. ASSERT_TRUE(client.is_valid());
  25780. client.enable_server_certificate_verification(false);
  25781. EXPECT_FALSE(client.connect());
  25782. }
  25783. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25784. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25785. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25786. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25787. }
  25788. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25789. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25790. std::string cert_pem, key_pem;
  25791. read_file(CLIENT_CERT_FILE, cert_pem);
  25792. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25793. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25794. std::vector<char> key(key_pem.begin(), key_pem.end());
  25795. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25796. key.size(), nullptr};
  25797. ConnectWithPem(pem);
  25798. }
  25799. #endif
  25800. #if !defined(_WIN32)
  25801. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25802. auto secret_dir = std::string("./symlink_test_secret");
  25803. auto served_dir = std::string("./symlink_test_served");
  25804. auto secret_file = secret_dir + "/secret.txt";
  25805. auto symlink_path = served_dir + "/escape";
  25806. // Setup: create directories and files
  25807. mkdir(secret_dir.c_str(), 0755);
  25808. mkdir(served_dir.c_str(), 0755);
  25809. {
  25810. std::ofstream ofs(secret_file);
  25811. ofs << "SECRET_DATA";
  25812. }
  25813. // Create symlink using absolute path so it resolves correctly
  25814. #ifdef PATH_MAX
  25815. char abs_secret[PATH_MAX];
  25816. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25817. #else
  25818. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25819. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25820. ASSERT_NE(nullptr, abs_secret);
  25821. #endif
  25822. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25823. auto se = detail::scope_exit([&] {
  25824. unlink(symlink_path.c_str());
  25825. unlink(secret_file.c_str());
  25826. rmdir(served_dir.c_str());
  25827. rmdir(secret_dir.c_str());
  25828. });
  25829. Server svr;
  25830. svr.set_mount_point("/", served_dir);
  25831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25832. auto se2 = detail::scope_exit([&] {
  25833. svr.stop();
  25834. listen_thread.join();
  25835. });
  25836. svr.wait_until_ready();
  25837. Client cli("localhost", PORT);
  25838. // Symlink pointing outside base dir should be blocked
  25839. auto res = cli.Get("/escape/secret.txt");
  25840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25841. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25842. }
  25843. #endif
  25844. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25845. // "GET /smuggled" request), reads the first response, and only then sends the
  25846. // embedded request as the body. Returns how many times /smuggled ran.
  25847. //
  25848. // The body is sent AFTER receiving the first response (as in the original
  25849. // PoC) so that the stream_line_reader cannot buffer it together with the
  25850. // headers of the first request.
  25851. static int count_smuggled_requests(const std::string &outer_head,
  25852. std::string &first_response) {
  25853. Server svr;
  25854. svr.set_mount_point("/", "./www");
  25855. std::atomic<int> smuggled_count(0);
  25856. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25857. smuggled_count++;
  25858. res.set_content("oops", "text/plain");
  25859. });
  25860. svr.Post("/post", [&](const Request &req, Response &res) {
  25861. res.set_content(req.body, "text/plain");
  25862. });
  25863. auto port = svr.bind_to_any_port("localhost");
  25864. thread t = thread([&] { svr.listen_after_bind(); });
  25865. auto se = detail::scope_exit([&] {
  25866. svr.stop();
  25867. t.join();
  25868. });
  25869. svr.wait_until_ready();
  25870. auto error = Error::Success;
  25871. auto sock = detail::create_client_socket(
  25872. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25873. /*connection_timeout_sec=*/2, 0,
  25874. /*read_timeout_sec=*/2, 0,
  25875. /*write_timeout_sec=*/2, 0, std::string(), error);
  25876. EXPECT_NE(INVALID_SOCKET, sock);
  25877. if (sock == INVALID_SOCKET) { return -1; }
  25878. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25879. // The "smuggled" request will be sent as the body of the outer request
  25880. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25881. "Host: localhost\r\n"
  25882. "Connection: close\r\n"
  25883. "\r\n";
  25884. auto head = outer_head;
  25885. auto len = std::to_string(smuggled.size());
  25886. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25887. pos = head.find("{len}", pos + len.size())) {
  25888. head.replace(pos, 5, len);
  25889. }
  25890. // Step 1: Send only the outer request headers (no body yet)
  25891. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25892. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25893. // Step 2: Read the first response
  25894. char buf[4096];
  25895. for (;;) {
  25896. auto n = recv(sock, buf, sizeof(buf), 0);
  25897. if (n <= 0) break;
  25898. first_response.append(buf, static_cast<size_t>(n));
  25899. // Stop once we have a complete response (headers + body)
  25900. auto hdr_end = first_response.find("\r\n\r\n");
  25901. if (hdr_end != std::string::npos) {
  25902. // Check for Content-Length to know when the body is complete
  25903. auto cl_pos = first_response.find("Content-Length:");
  25904. if (cl_pos != std::string::npos) {
  25905. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25906. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25907. auto cl = std::stoul(
  25908. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25909. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25910. } else {
  25911. break; // No Content-Length, assume headers-only response
  25912. }
  25913. }
  25914. }
  25915. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25916. // vulnerable server the keep-alive loop reads this as a second request. The
  25917. // server may already have closed the connection, so the result is ignored.
  25918. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25919. // Half-close so that a server which drained the body sees EOF and closes,
  25920. // instead of the read below waiting for the read timeout.
  25921. #ifdef _WIN32
  25922. ::shutdown(sock, SD_SEND);
  25923. #else
  25924. ::shutdown(sock, SHUT_WR);
  25925. #endif
  25926. // Step 4: Read until the server closes the connection
  25927. for (;;) {
  25928. auto n = recv(sock, buf, sizeof(buf), 0);
  25929. if (n <= 0) break;
  25930. }
  25931. return smuggled_count.load();
  25932. }
  25933. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25934. // A GET request with Content-Length to a static file handler must have its
  25935. // body drained before the keep-alive connection is reused. Otherwise the
  25936. // unread body bytes are interpreted as the next HTTP request.
  25937. std::string first_response;
  25938. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25939. "Host: localhost\r\n"
  25940. "Content-Length: {len}\r\n"
  25941. "\r\n",
  25942. first_response));
  25943. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25944. }
  25945. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25946. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25947. // be answered with 400 and the connection closed. Treating it as "no body"
  25948. // leaves the body to be parsed as the next request.
  25949. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25950. const char *targets[] = {
  25951. "GET /file", // handler that never reads the body
  25952. "GET /not-found", // no handler matches (404)
  25953. "POST /post", // handler that reads the body
  25954. };
  25955. for (auto target : targets) {
  25956. for (auto value : values) {
  25957. std::string first_response;
  25958. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25959. " HTTP/1.1\r\n"
  25960. "Host: localhost\r\n"
  25961. "Content-Length: " +
  25962. value + "\r\n\r\n",
  25963. first_response))
  25964. << target << " with Content-Length: " << value;
  25965. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25966. << target << " with Content-Length: " << value;
  25967. }
  25968. }
  25969. }
  25970. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25971. // A 400 for an unparseable request line leaves the rest of the message
  25972. // unread, so the connection must be closed rather than reused.
  25973. std::string first_response;
  25974. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25975. "Host: localhost\r\n"
  25976. "Content-Length: {len}\r\n"
  25977. "\r\n",
  25978. first_response));
  25979. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25980. }
  25981. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25982. // Same as above for a header block that fails to parse.
  25983. std::string first_response;
  25984. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25985. "Host: localhost\r\n"
  25986. "Bad Header\r\n"
  25987. "Content-Length: {len}\r\n"
  25988. "\r\n",
  25989. first_response));
  25990. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25991. }
  25992. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25993. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25994. // server must not read another request on that connection, even when the
  25995. // request had no body to drain.
  25996. std::string first_response;
  25997. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25998. "Host: localhost\r\n"
  25999. "\r\n",
  26000. first_response));
  26001. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26002. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26003. }
  26004. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26005. // A content reader that stops early leaves the stream inside the body.
  26006. // Draining the whole Content-Length from there, or reading the body again,
  26007. // reads into the next request, and whatever follows is parsed as a request
  26008. // of its own.
  26009. Server svr;
  26010. std::atomic<int> smuggled_count(0);
  26011. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26012. svr.Post("/upload", [](const Request &req, Response &res,
  26013. const ContentReader &content_reader) {
  26014. // Stop at the last chunk, so the whole body has been read however it
  26015. // arrives.
  26016. auto length = req.get_header_value_u64("Content-Length");
  26017. size_t total = 0;
  26018. auto consumed = content_reader([&](const char *, size_t n) {
  26019. total += n;
  26020. return total < length;
  26021. });
  26022. EXPECT_FALSE(consumed);
  26023. if (req.has_param("retry")) {
  26024. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26025. }
  26026. // Replace the 400 the aborted read set, which would close the connection.
  26027. res.set_redirect("/done");
  26028. });
  26029. auto port = svr.bind_to_any_port(HOST);
  26030. thread t = thread([&] { svr.listen_after_bind(); });
  26031. auto se = detail::scope_exit([&] {
  26032. svr.stop();
  26033. t.join();
  26034. });
  26035. svr.wait_until_ready();
  26036. // A front end sees the second request as a POST whose body is the GET. The
  26037. // first body is as long as the POST's headers, so draining it again reads
  26038. // exactly those and leaves the GET to be parsed next.
  26039. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26040. "Host: localhost\r\n"
  26041. "\r\n";
  26042. std::string second_head = "POST /post HTTP/1.1\r\n"
  26043. "Host: localhost\r\n"
  26044. "Content-Length: " +
  26045. std::to_string(inner.size()) +
  26046. "\r\n"
  26047. "\r\n";
  26048. for (auto target : {"/upload", "/upload?retry"}) {
  26049. smuggled_count = 0;
  26050. std::string request = "POST " + std::string(target) +
  26051. " HTTP/1.1\r\n"
  26052. "Host: localhost\r\n"
  26053. "Content-Length: " +
  26054. std::to_string(second_head.size()) +
  26055. "\r\n"
  26056. "\r\n" +
  26057. std::string(second_head.size(), 'A') + second_head +
  26058. inner;
  26059. std::string response;
  26060. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26061. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26062. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26063. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26064. EXPECT_EQ(0, smuggled_count.load()) << target;
  26065. }
  26066. }
  26067. // An error response closes the connection anyway, so the body is left unread
  26068. // with a redirect, such as one to a login page.
  26069. static void serve_redirects(Server &svr,
  26070. const std::function<void(int)> &client) {
  26071. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26072. res.set_redirect("/login");
  26073. return Server::HandlerResponse::Handled;
  26074. });
  26075. auto port = svr.bind_to_any_port(HOST);
  26076. ASSERT_GT(port, 0);
  26077. thread t = thread([&] { svr.listen_after_bind(); });
  26078. auto se = detail::scope_exit([&] {
  26079. svr.stop();
  26080. t.join();
  26081. ASSERT_FALSE(svr.is_running());
  26082. });
  26083. svr.wait_until_ready();
  26084. client(port);
  26085. }
  26086. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26087. Server svr;
  26088. serve_redirects(svr, [](int port) {
  26089. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26090. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26091. std::to_string(body.size()) + "\r\n\r\n" + body +
  26092. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26093. std::string resp;
  26094. ASSERT_TRUE(send_request(1, req, &resp, port));
  26095. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26096. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26097. });
  26098. }
  26099. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26100. Server svr;
  26101. svr.set_read_timeout(0, 200000);
  26102. serve_redirects(svr, [](int port) {
  26103. // A byte every 100 ms keeps each read within the read timeout, but not the
  26104. // body as a whole, so the server closes and the bytes sent after that fail.
  26105. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26106. "Content-Length: 10\r\n\r\n"};
  26107. parts.resize(11, "x");
  26108. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26109. });
  26110. }
  26111. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26112. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26113. // must be rejected with 400 Bad Request.
  26114. Server svr;
  26115. svr.Post("/test", [&](const Request &, Response &res) {
  26116. res.set_content("ok", "text/plain");
  26117. });
  26118. thread t = thread([&] { svr.listen(HOST, PORT); });
  26119. auto se = detail::scope_exit([&] {
  26120. svr.stop();
  26121. t.join();
  26122. ASSERT_FALSE(svr.is_running());
  26123. });
  26124. svr.wait_until_ready();
  26125. // Exact "chunked"
  26126. {
  26127. auto req = "POST /test HTTP/1.1\r\n"
  26128. "Host: localhost\r\n"
  26129. "Content-Length: 5\r\n"
  26130. "Transfer-Encoding: chunked\r\n"
  26131. "Connection: close\r\n"
  26132. "\r\n"
  26133. "hello";
  26134. std::string response;
  26135. ASSERT_TRUE(send_request(1, req, &response));
  26136. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26137. response.substr(0, response.find("\r\n")));
  26138. }
  26139. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26140. {
  26141. auto req = "POST /test HTTP/1.1\r\n"
  26142. "Host: localhost\r\n"
  26143. "Content-Length: 5\r\n"
  26144. "Transfer-Encoding: gzip, chunked\r\n"
  26145. "Connection: close\r\n"
  26146. "\r\n"
  26147. "hello";
  26148. std::string response;
  26149. ASSERT_TRUE(send_request(1, req, &response));
  26150. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26151. response.substr(0, response.find("\r\n")));
  26152. }
  26153. }
  26154. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26155. Server svr;
  26156. svr.Post("/test", [&](const Request &, Response &res) {
  26157. res.set_content("ok", "text/plain");
  26158. });
  26159. thread t = thread([&] { svr.listen(HOST, PORT); });
  26160. auto se = detail::scope_exit([&] {
  26161. svr.stop();
  26162. t.join();
  26163. ASSERT_FALSE(svr.is_running());
  26164. });
  26165. svr.wait_until_ready();
  26166. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26167. // length cannot be determined, so the server must answer 400 and close
  26168. // rather than treat the request as bodyless and leave the body in the
  26169. // socket for the next request to pick up.
  26170. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26171. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26172. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26173. std::string response;
  26174. ASSERT_TRUE(send_request(1, req, &response));
  26175. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26176. response.substr(0, response.find("\r\n")))
  26177. << transfer_encoding;
  26178. }
  26179. // RFC 9110 5.3: the codings may also be split across several
  26180. // Transfer-Encoding lines, which combine in the order they were received.
  26181. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26182. // just like the single-line "chunked, gzip" above.
  26183. {
  26184. auto req = "POST /test HTTP/1.1\r\n"
  26185. "Host: localhost\r\n"
  26186. "Transfer-Encoding: chunked\r\n"
  26187. "Transfer-Encoding: gzip\r\n"
  26188. "\r\n"
  26189. "0\r\n\r\n";
  26190. std::string response;
  26191. ASSERT_TRUE(send_request(1, req, &response));
  26192. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26193. response.substr(0, response.find("\r\n")));
  26194. }
  26195. }
  26196. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26197. Server svr;
  26198. svr.Post("/test", [&](const Request &, Response &res) {
  26199. res.set_content("ok", "text/plain");
  26200. });
  26201. auto port = svr.bind_to_any_port(HOST);
  26202. ASSERT_GT(port, 0);
  26203. thread t = thread([&] { svr.listen_after_bind(); });
  26204. auto se = detail::scope_exit([&] {
  26205. svr.stop();
  26206. t.join();
  26207. ASSERT_FALSE(svr.is_running());
  26208. });
  26209. svr.wait_until_ready();
  26210. for (auto transfer_encoding :
  26211. {"Transfer-Encoding: gzip, chunked\r\n",
  26212. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26213. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26214. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26215. transfer_encoding + "\r\n0\r\n\r\n";
  26216. std::string response;
  26217. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26218. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26219. response.substr(0, response.find("\r\n")))
  26220. << transfer_encoding;
  26221. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26222. << transfer_encoding;
  26223. }
  26224. }
  26225. // Regression for issue #2450: a DELETE without Content-Length on a
  26226. // keep-alive connection must not let the post-response drain consume the
  26227. // next request's bytes.
  26228. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26229. Server svr;
  26230. std::atomic<int> delete_count(0);
  26231. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26232. delete_count++;
  26233. res.status = StatusCode::NoContent_204;
  26234. });
  26235. auto port = svr.bind_to_any_port(HOST);
  26236. thread t = thread([&] { svr.listen_after_bind(); });
  26237. auto se = detail::scope_exit([&] {
  26238. svr.stop();
  26239. t.join();
  26240. });
  26241. svr.wait_until_ready();
  26242. auto error = Error::Success;
  26243. auto sock = detail::create_client_socket(
  26244. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26245. /*connection_timeout_sec=*/2, 0,
  26246. /*read_timeout_sec=*/2, 0,
  26247. /*write_timeout_sec=*/2, 0, std::string(), error);
  26248. ASSERT_NE(INVALID_SOCKET, sock);
  26249. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26250. auto send_request_and_read_response = [&](const std::string &req,
  26251. std::string &out) -> bool {
  26252. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26253. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26254. char buf[4096];
  26255. for (;;) {
  26256. auto n = recv(sock, buf, sizeof(buf), 0);
  26257. if (n <= 0) { return !out.empty(); }
  26258. out.append(buf, static_cast<size_t>(n));
  26259. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26260. }
  26261. };
  26262. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26263. "Host: localhost\r\n"
  26264. "\r\n";
  26265. std::string resp1;
  26266. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26267. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26268. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26269. "Host: localhost\r\n"
  26270. "Connection: close\r\n"
  26271. "\r\n";
  26272. std::string resp2;
  26273. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26274. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26275. EXPECT_EQ(2, delete_count.load());
  26276. }
  26277. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26278. Server svr;
  26279. svr.Post("/ingest", [&](const Request &, Response &res,
  26280. const ContentReader &content_reader) {
  26281. auto consumed = content_reader([](const char *, size_t) { return false; });
  26282. EXPECT_FALSE(consumed);
  26283. res.status = StatusCode::Conflict_409;
  26284. res.set_header("Connection", "close");
  26285. });
  26286. auto port = svr.bind_to_any_port(HOST);
  26287. thread t = thread([&] { svr.listen_after_bind(); });
  26288. auto se = detail::scope_exit([&] {
  26289. svr.stop();
  26290. t.join();
  26291. });
  26292. svr.wait_until_ready();
  26293. auto error = Error::Success;
  26294. auto sock = detail::create_client_socket(
  26295. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26296. /*connection_timeout_sec=*/2, 0,
  26297. /*read_timeout_sec=*/1, 0,
  26298. /*write_timeout_sec=*/2, 0, std::string(), error);
  26299. ASSERT_NE(INVALID_SOCKET, sock);
  26300. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26301. std::string request = "POST /ingest HTTP/1.1\r\n"
  26302. "Host: localhost\r\n"
  26303. "Transfer-Encoding: chunked\r\n"
  26304. "\r\n"
  26305. "4\r\n"
  26306. "data\r\n";
  26307. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26308. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26309. std::string response;
  26310. ssize_t received = 0;
  26311. do {
  26312. char buf[4096];
  26313. received = recv(sock, buf, sizeof(buf), 0);
  26314. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26315. } while (received > 0);
  26316. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26317. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26318. EXPECT_EQ(0, received);
  26319. }
  26320. namespace no_proxy_test {
  26321. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26322. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26323. // calling listen().
  26324. class ScopedServer {
  26325. public:
  26326. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26327. ~ScopedServer() {
  26328. svr_.stop();
  26329. if (th_.joinable()) { th_.join(); }
  26330. }
  26331. Server &svr() { return svr_; }
  26332. int port() const { return port_; }
  26333. void listen() {
  26334. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26335. svr_.wait_until_ready();
  26336. }
  26337. private:
  26338. Server svr_;
  26339. std::thread th_;
  26340. int port_ = 0;
  26341. };
  26342. class ProxyAndTargetServers {
  26343. public:
  26344. ProxyAndTargetServers() {
  26345. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26346. proxy_hits_++;
  26347. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26348. res.set_content("via-proxy", "text/plain");
  26349. });
  26350. target_.Get(".*", [this](const Request &req, Response &res) {
  26351. target_hits_++;
  26352. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26353. res.set_content("direct", "text/plain");
  26354. });
  26355. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26356. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26357. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26358. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26359. proxy_mock_.wait_until_ready();
  26360. target_.wait_until_ready();
  26361. }
  26362. ~ProxyAndTargetServers() {
  26363. proxy_mock_.stop();
  26364. target_.stop();
  26365. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26366. if (target_thread_.joinable()) { target_thread_.join(); }
  26367. }
  26368. Server &proxy_mock() { return proxy_mock_; }
  26369. Server &target() { return target_; }
  26370. int proxy_port() const { return proxy_port_; }
  26371. int target_port() const { return target_port_; }
  26372. int proxy_hits() const { return proxy_hits_.load(); }
  26373. int target_hits() const { return target_hits_.load(); }
  26374. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26375. void reset_counters() {
  26376. proxy_hits_ = 0;
  26377. target_hits_ = 0;
  26378. last_had_proxy_authz_ = false;
  26379. }
  26380. private:
  26381. Server proxy_mock_;
  26382. Server target_;
  26383. std::thread proxy_thread_;
  26384. std::thread target_thread_;
  26385. int proxy_port_ = 0;
  26386. int target_port_ = 0;
  26387. std::atomic<int> proxy_hits_{0};
  26388. std::atomic<int> target_hits_{0};
  26389. std::atomic<bool> last_had_proxy_authz_{false};
  26390. };
  26391. inline std::unique_ptr<Client> make_client(const std::string &host,
  26392. ProxyAndTargetServers &s) {
  26393. auto cli = detail::make_unique<Client>(host, s.target_port());
  26394. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26395. cli->set_proxy("127.0.0.1", s.proxy_port());
  26396. return cli;
  26397. }
  26398. } // namespace no_proxy_test
  26399. using no_proxy_test::make_client;
  26400. using no_proxy_test::ProxyAndTargetServers;
  26401. // A stream request carries the credentials a buffered request does
  26402. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26403. no_proxy_test::ScopedServer origin;
  26404. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26405. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26406. });
  26407. origin.listen();
  26408. Client cli("127.0.0.1", origin.port());
  26409. cli.set_basic_auth("user", "pass");
  26410. auto handle = cli.open_stream("GET", "/x");
  26411. ASSERT_TRUE(handle.is_valid());
  26412. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26413. Client bearer("127.0.0.1", origin.port());
  26414. bearer.set_bearer_token_auth("tok");
  26415. auto handle2 = bearer.open_stream("GET", "/x");
  26416. ASSERT_TRUE(handle2.is_valid());
  26417. EXPECT_EQ("Bearer tok", read_all(handle2));
  26418. }
  26419. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26420. // takes its own credentials, as for a buffered request
  26421. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26422. std::string target, authz, proxy_authz;
  26423. no_proxy_test::ScopedServer proxy;
  26424. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26425. target = req.target;
  26426. authz = req.get_header_value("Authorization");
  26427. proxy_authz = req.get_header_value("Proxy-Authorization");
  26428. res.set_content("ok", "text/plain");
  26429. });
  26430. proxy.listen();
  26431. Client cli("origin.example", 8080);
  26432. cli.set_proxy("127.0.0.1", proxy.port());
  26433. cli.set_proxy_basic_auth("puser", "ppass");
  26434. cli.set_basic_auth("user", "pass");
  26435. auto handle = cli.open_stream("GET", "/x");
  26436. ASSERT_TRUE(handle.is_valid());
  26437. EXPECT_EQ("ok", read_all(handle));
  26438. EXPECT_EQ("http://origin.example:8080/x", target);
  26439. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26440. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26441. }
  26442. // In absolute-form the path follows the authority, so a path that does not
  26443. // begin with '/' would make the proxy connect to another host
  26444. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26445. std::vector<std::string> targets;
  26446. no_proxy_test::ScopedServer proxy;
  26447. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26448. targets.push_back(req.target);
  26449. res.set_content("ok", "text/plain");
  26450. });
  26451. proxy.listen();
  26452. Client cli("origin.example", 8080);
  26453. cli.set_proxy("127.0.0.1", proxy.port());
  26454. cli.set_basic_auth("user", "pass");
  26455. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26456. auto res = cli.Get(path);
  26457. EXPECT_FALSE(res) << path;
  26458. auto handle = cli.open_stream("GET", path);
  26459. EXPECT_FALSE(handle.is_valid()) << path;
  26460. }
  26461. EXPECT_TRUE(targets.empty());
  26462. auto res = cli.Get("/x");
  26463. ASSERT_TRUE(res);
  26464. ASSERT_EQ(1u, targets.size());
  26465. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26466. }
  26467. TEST(NoProxyTest, ExactHostnameBypasses) {
  26468. ProxyAndTargetServers s;
  26469. auto cli = make_client("example.com", s);
  26470. cli->set_no_proxy({"example.com"});
  26471. auto res = cli->Get("/");
  26472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26473. EXPECT_EQ(0, s.proxy_hits());
  26474. EXPECT_EQ(1, s.target_hits());
  26475. }
  26476. TEST(NoProxyTest, SubdomainBypasses) {
  26477. ProxyAndTargetServers s;
  26478. auto cli = make_client("foo.example.com", s);
  26479. cli->set_no_proxy({"example.com"});
  26480. auto res = cli->Get("/");
  26481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26482. EXPECT_EQ(0, s.proxy_hits());
  26483. EXPECT_EQ(1, s.target_hits());
  26484. }
  26485. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26486. // Regression guard: "evilexample.com" must not be considered a subdomain
  26487. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26488. // check would let traffic bypass the proxy and leak credentials direct
  26489. // to the attacker host.
  26490. ProxyAndTargetServers s;
  26491. auto cli = make_client("evilexample.com", s);
  26492. cli->set_no_proxy({"example.com"});
  26493. auto res = cli->Get("/");
  26494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26495. EXPECT_GE(s.proxy_hits(), 1);
  26496. EXPECT_EQ(0, s.target_hits());
  26497. }
  26498. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26499. ProxyAndTargetServers s;
  26500. auto cli = make_client("example.com.evil.com", s);
  26501. cli->set_no_proxy({"example.com"});
  26502. auto res = cli->Get("/");
  26503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26504. EXPECT_GE(s.proxy_hits(), 1);
  26505. EXPECT_EQ(0, s.target_hits());
  26506. }
  26507. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26508. ProxyAndTargetServers s;
  26509. auto cli = make_client("example.com", s);
  26510. cli->set_no_proxy({".example.com"});
  26511. auto res = cli->Get("/");
  26512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26513. EXPECT_EQ(0, s.proxy_hits());
  26514. EXPECT_EQ(1, s.target_hits());
  26515. }
  26516. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26517. ProxyAndTargetServers s;
  26518. auto cli = make_client("Example.COM", s);
  26519. cli->set_no_proxy({"EXAMPLE.com"});
  26520. auto res = cli->Get("/");
  26521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26522. EXPECT_EQ(0, s.proxy_hits());
  26523. EXPECT_EQ(1, s.target_hits());
  26524. }
  26525. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26526. ProxyAndTargetServers s;
  26527. auto cli = make_client("example.com.", s);
  26528. cli->set_no_proxy({"example.com"});
  26529. auto res = cli->Get("/");
  26530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26531. EXPECT_EQ(0, s.proxy_hits());
  26532. EXPECT_EQ(1, s.target_hits());
  26533. }
  26534. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26535. // Trailing dots must be normalized on BOTH sides — host and entry.
  26536. // An implementation that only strips the host-side trailing dot would
  26537. // fail to match host "example.com" against entry "example.com." because
  26538. // a literal substring search would compare 11 chars against 12.
  26539. ProxyAndTargetServers s;
  26540. auto cli = make_client("example.com", s);
  26541. cli->set_no_proxy({"example.com."});
  26542. auto res = cli->Get("/");
  26543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26544. EXPECT_EQ(0, s.proxy_hits());
  26545. EXPECT_EQ(1, s.target_hits());
  26546. }
  26547. TEST(NoProxyTest, WildcardBypassesEverything) {
  26548. ProxyAndTargetServers s;
  26549. auto cli = make_client("anything.invalid.test", s);
  26550. cli->set_no_proxy({"*"});
  26551. auto res = cli->Get("/");
  26552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26553. EXPECT_EQ(0, s.proxy_hits());
  26554. EXPECT_EQ(1, s.target_hits());
  26555. }
  26556. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26557. ProxyAndTargetServers s;
  26558. Client cli("127.0.0.1", s.target_port());
  26559. cli.set_proxy("127.0.0.1", s.proxy_port());
  26560. cli.set_no_proxy({"127.0.0.1"});
  26561. auto res = cli.Get("/");
  26562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26563. EXPECT_EQ(0, s.proxy_hits());
  26564. EXPECT_EQ(1, s.target_hits());
  26565. }
  26566. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26567. ProxyAndTargetServers s;
  26568. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26569. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26570. cli.set_proxy("127.0.0.1", s.proxy_port());
  26571. cli.set_no_proxy({"::1"});
  26572. auto res = cli.Get("/");
  26573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26574. EXPECT_EQ(0, s.proxy_hits());
  26575. EXPECT_EQ(1, s.target_hits());
  26576. }
  26577. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26578. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26579. // must still be recognized as IPv6 for CIDR matching. Implementations
  26580. // that detect IPv6 only when the host begins with '[' would parse the
  26581. // host as a hostname and miss the match.
  26582. ProxyAndTargetServers s;
  26583. Client cli("fe80::1", s.target_port());
  26584. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26585. cli.set_proxy("127.0.0.1", s.proxy_port());
  26586. cli.set_no_proxy({"fe80::/10"});
  26587. auto res = cli.Get("/");
  26588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26589. EXPECT_EQ(0, s.proxy_hits());
  26590. EXPECT_EQ(1, s.target_hits());
  26591. }
  26592. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26593. ProxyAndTargetServers s;
  26594. Client cli("::1", s.target_port());
  26595. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26596. cli.set_proxy("127.0.0.1", s.proxy_port());
  26597. cli.set_no_proxy({"[::1]"});
  26598. auto res = cli.Get("/");
  26599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26600. EXPECT_EQ(0, s.proxy_hits());
  26601. EXPECT_EQ(1, s.target_hits());
  26602. }
  26603. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26604. ProxyAndTargetServers s;
  26605. Client cli("fe80::1", s.target_port());
  26606. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26607. cli.set_proxy("127.0.0.1", s.proxy_port());
  26608. cli.set_no_proxy({"[fe80::]/10"});
  26609. auto res = cli.Get("/");
  26610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26611. EXPECT_EQ(0, s.proxy_hits());
  26612. EXPECT_EQ(1, s.target_hits());
  26613. }
  26614. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26615. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26616. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26617. // tricks via address-family conversion.
  26618. ProxyAndTargetServers s;
  26619. Client cli("::ffff:127.0.0.1", s.target_port());
  26620. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26621. cli.set_proxy("127.0.0.1", s.proxy_port());
  26622. cli.set_no_proxy({"127.0.0.1"});
  26623. auto res = cli.Get("/");
  26624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26625. EXPECT_GE(s.proxy_hits(), 1);
  26626. EXPECT_EQ(0, s.target_hits());
  26627. }
  26628. TEST(NoProxyTest, IPv4CidrMatch) {
  26629. ProxyAndTargetServers s;
  26630. Client cli("127.0.0.1", s.target_port());
  26631. cli.set_proxy("127.0.0.1", s.proxy_port());
  26632. cli.set_no_proxy({"127.0.0.0/8"});
  26633. auto res = cli.Get("/");
  26634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26635. EXPECT_EQ(0, s.proxy_hits());
  26636. EXPECT_EQ(1, s.target_hits());
  26637. }
  26638. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26639. ProxyAndTargetServers s;
  26640. Client cli("127.0.0.1", s.target_port());
  26641. cli.set_proxy("127.0.0.1", s.proxy_port());
  26642. cli.set_no_proxy({"10.0.0.0/8"});
  26643. auto res = cli.Get("/");
  26644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26645. EXPECT_GE(s.proxy_hits(), 1);
  26646. EXPECT_EQ(0, s.target_hits());
  26647. }
  26648. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26649. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26650. // IPv4 target matches.
  26651. ProxyAndTargetServers s;
  26652. Client cli("127.0.0.1", s.target_port());
  26653. cli.set_proxy("127.0.0.1", s.proxy_port());
  26654. cli.set_no_proxy({"0.0.0.0/0"});
  26655. auto res = cli.Get("/");
  26656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26657. EXPECT_EQ(0, s.proxy_hits());
  26658. EXPECT_EQ(1, s.target_hits());
  26659. }
  26660. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26661. ProxyAndTargetServers s;
  26662. Client cli("127.0.0.1", s.target_port());
  26663. cli.set_proxy("127.0.0.1", s.proxy_port());
  26664. cli.set_no_proxy({"127.0.0.1"});
  26665. auto res = cli.Get("/");
  26666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26667. EXPECT_EQ(0, s.proxy_hits());
  26668. EXPECT_EQ(1, s.target_hits());
  26669. }
  26670. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26671. ProxyAndTargetServers s;
  26672. Client cli("127.0.0.1", s.target_port());
  26673. cli.set_proxy("127.0.0.1", s.proxy_port());
  26674. cli.set_no_proxy({"127.0.0.0/33"});
  26675. auto res = cli.Get("/");
  26676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26677. EXPECT_GE(s.proxy_hits(), 1);
  26678. EXPECT_EQ(0, s.target_hits());
  26679. }
  26680. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26681. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26682. ProxyAndTargetServers s;
  26683. Client cli("127.0.0.1", s.target_port());
  26684. cli.set_proxy("127.0.0.1", s.proxy_port());
  26685. cli.set_no_proxy({"127.0.0.1/"});
  26686. auto res = cli.Get("/");
  26687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26688. EXPECT_GE(s.proxy_hits(), 1);
  26689. EXPECT_EQ(0, s.target_hits());
  26690. }
  26691. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26692. ProxyAndTargetServers s;
  26693. auto cli = make_client("internal.corp", s);
  26694. cli->set_proxy_basic_auth("u", "p");
  26695. cli->set_no_proxy({"internal.corp"});
  26696. auto res = cli->Get("/");
  26697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26698. EXPECT_EQ(1, s.target_hits());
  26699. EXPECT_EQ(0, s.proxy_hits());
  26700. EXPECT_FALSE(s.last_had_proxy_authz())
  26701. << "Proxy-Authorization must not be sent direct to the target";
  26702. }
  26703. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26704. ProxyAndTargetServers s;
  26705. auto cli = make_client("public.example", s);
  26706. cli->set_proxy_basic_auth("u", "p");
  26707. cli->set_no_proxy({"internal.corp"}); // does not match
  26708. auto res = cli->Get("/");
  26709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26710. EXPECT_GE(s.proxy_hits(), 1);
  26711. EXPECT_TRUE(s.last_had_proxy_authz());
  26712. }
  26713. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26714. std::atomic<int> hits{0};
  26715. std::atomic<int> hits_with_authz{0};
  26716. no_proxy_test::ScopedServer proxy_mock;
  26717. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26718. hits++;
  26719. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26720. if (req.target.find("/redir") != std::string::npos) {
  26721. res.set_redirect("http://other.example/landed");
  26722. } else {
  26723. res.set_content("via-proxy", "text/plain");
  26724. }
  26725. });
  26726. proxy_mock.listen();
  26727. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26728. hits = 0;
  26729. hits_with_authz = 0;
  26730. Client cli("public.example", 80);
  26731. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26732. cli.set_proxy_basic_auth(c.first, c.second);
  26733. cli.set_follow_location(true);
  26734. // The redirect to another host goes through the proxy as well
  26735. auto res = cli.Get("/redir");
  26736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26737. EXPECT_EQ(2, hits.load());
  26738. EXPECT_EQ(2, hits_with_authz.load());
  26739. }
  26740. }
  26741. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26742. ProxyAndTargetServers s;
  26743. auto cli = make_client("anything.test", s);
  26744. auto res = cli->Get("/");
  26745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26746. EXPECT_GE(s.proxy_hits(), 1);
  26747. EXPECT_EQ(0, s.target_hits());
  26748. }
  26749. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26750. ProxyAndTargetServers s;
  26751. auto cli = make_client("example.com", s);
  26752. cli->set_no_proxy({"example.com:8080"});
  26753. auto res = cli->Get("/");
  26754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26755. EXPECT_GE(s.proxy_hits(), 1);
  26756. EXPECT_EQ(0, s.target_hits());
  26757. }
  26758. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26759. ProxyAndTargetServers s;
  26760. auto cli = make_client("anything.test", s);
  26761. cli->set_no_proxy({"", " ", "\t"});
  26762. auto res = cli->Get("/");
  26763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26764. EXPECT_GE(s.proxy_hits(), 1);
  26765. EXPECT_EQ(0, s.target_hits());
  26766. }
  26767. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26768. // An entry with leading/trailing whitespace must still match — env-style
  26769. // values are commonly pasted with stray spaces and an implementation
  26770. // that feeds the raw token directly to inet_pton would fail to match
  26771. // valid CIDRs because of the spaces.
  26772. ProxyAndTargetServers s;
  26773. Client cli("127.0.0.1", s.target_port());
  26774. cli.set_proxy("127.0.0.1", s.proxy_port());
  26775. cli.set_no_proxy({" 127.0.0.0/8 "});
  26776. auto res = cli.Get("/");
  26777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26778. EXPECT_EQ(0, s.proxy_hits());
  26779. EXPECT_EQ(1, s.target_hits());
  26780. }
  26781. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26782. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26783. // go direct and must NOT carry Proxy-Authorization.
  26784. std::atomic<int> proxy_hits{0};
  26785. std::atomic<int> target_hits{0};
  26786. std::atomic<bool> target_saw_authz{false};
  26787. no_proxy_test::ScopedServer proxy_mock, target;
  26788. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26789. proxy_hits++;
  26790. res.status = 302;
  26791. res.set_header("Location", "http://127.0.0.1:" +
  26792. std::to_string(target.port()) + "/landed");
  26793. });
  26794. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26795. target_hits++;
  26796. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26797. res.set_content("direct", "text/plain");
  26798. });
  26799. proxy_mock.listen();
  26800. target.listen();
  26801. Client cli("public.example", target.port());
  26802. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26803. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26804. cli.set_proxy_basic_auth("u", "p");
  26805. cli.set_no_proxy({"127.0.0.1"});
  26806. cli.set_follow_location(true);
  26807. auto res = cli.Get("/redir");
  26808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26809. EXPECT_GE(proxy_hits.load(), 1);
  26810. EXPECT_GE(target_hits.load(), 1);
  26811. EXPECT_FALSE(target_saw_authz.load());
  26812. }
  26813. #ifdef CPPHTTPLIB_SSL_ENABLED
  26814. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26815. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26816. // proxy creds would be sent to the (possibly hostile) origin.
  26817. std::atomic<int> target_hits{0};
  26818. std::atomic<bool> target_saw_proxy_authz{false};
  26819. no_proxy_test::ScopedServer target;
  26820. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26821. target_hits++;
  26822. if (req.has_header("Proxy-Authorization")) {
  26823. target_saw_proxy_authz = true;
  26824. }
  26825. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26826. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26827. "nonce=\"abc\", algorithm=MD5");
  26828. });
  26829. target.listen();
  26830. // The proxy address is set to the target's port: the bypass MUST kick in;
  26831. // if it doesn't, the test still routes "via proxy" to the same server and
  26832. // the Proxy-Authorization assertion below catches the leak.
  26833. Client cli("evil.example", target.port());
  26834. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26835. cli.set_proxy("127.0.0.1", target.port());
  26836. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26837. cli.set_no_proxy({"evil.example"});
  26838. auto res = cli.Get("/x");
  26839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26840. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26841. EXPECT_EQ(1, target_hits.load());
  26842. EXPECT_FALSE(target_saw_proxy_authz.load());
  26843. }
  26844. #endif
  26845. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26846. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26847. std::atomic<int> proxy_hits{0};
  26848. std::atomic<int> bypass_hits{0};
  26849. std::atomic<bool> proxy_saw_c_url{false};
  26850. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26851. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26852. proxy_hits++;
  26853. if (req.path.find("/start") != std::string::npos) {
  26854. res.status = 302;
  26855. res.set_header("Location", "http://127.0.0.1:" +
  26856. std::to_string(bypass_server.port()) +
  26857. "/middle");
  26858. return;
  26859. }
  26860. if (req.path.find("/end") != std::string::npos) {
  26861. proxy_saw_c_url = true;
  26862. res.set_content("c-via-proxy", "text/plain");
  26863. return;
  26864. }
  26865. res.set_content("unexpected", "text/plain");
  26866. });
  26867. // public.example's "advertised" port is arbitrary (the request never lands
  26868. // there — it goes through the proxy), but use a dynamic value to stay
  26869. // friendly with sharded parallel runs.
  26870. int public_port = bypass_server.port();
  26871. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26872. bypass_hits++;
  26873. res.status = 302;
  26874. res.set_header("Location", "http://public.example:" +
  26875. std::to_string(public_port) + "/end");
  26876. });
  26877. proxy_mock.listen();
  26878. bypass_server.listen();
  26879. Client cli("public.example", public_port);
  26880. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26881. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26882. cli.set_no_proxy({"127.0.0.1"});
  26883. cli.set_follow_location(true);
  26884. auto res = cli.Get("/start");
  26885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26886. EXPECT_EQ(StatusCode::OK_200, res->status);
  26887. EXPECT_EQ("c-via-proxy", res->body);
  26888. EXPECT_GE(proxy_hits.load(), 2);
  26889. EXPECT_GE(bypass_hits.load(), 1);
  26890. EXPECT_TRUE(proxy_saw_c_url.load());
  26891. }
  26892. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26893. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26894. // request reconnects to the correct endpoint.
  26895. std::atomic<int> proxy_hits{0};
  26896. std::atomic<int> target_hits{0};
  26897. no_proxy_test::ScopedServer proxy_mock, target;
  26898. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26899. proxy_hits++;
  26900. res.set_content("via-proxy", "text/plain");
  26901. });
  26902. target.svr().Get(".*", [&](const Request &, Response &res) {
  26903. target_hits++;
  26904. res.set_content("direct", "text/plain");
  26905. });
  26906. proxy_mock.listen();
  26907. target.listen();
  26908. Client cli("public.example", target.port());
  26909. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26910. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26911. cli.set_keep_alive(true);
  26912. auto res1 = cli.Get("/a");
  26913. ASSERT_TRUE(res1);
  26914. EXPECT_EQ("via-proxy", res1->body);
  26915. EXPECT_EQ(1, proxy_hits.load());
  26916. EXPECT_EQ(0, target_hits.load());
  26917. cli.set_no_proxy({"public.example"});
  26918. auto res2 = cli.Get("/b");
  26919. ASSERT_TRUE(res2);
  26920. EXPECT_EQ("direct", res2->body);
  26921. EXPECT_EQ(1, proxy_hits.load());
  26922. EXPECT_EQ(1, target_hits.load());
  26923. }
  26924. // Forward declarations (see the base64_encode note).
  26925. namespace httplib {
  26926. namespace detail {
  26927. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26928. int shutdown_socket(socket_t sock) noexcept;
  26929. } // namespace detail
  26930. } // namespace httplib
  26931. namespace proxy_tunnel_test {
  26932. const char *const kTunnelEstablished =
  26933. "HTTP/1.1 200 Connection established\r\n\r\n";
  26934. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26935. using ConnectReply = std::function<std::string(const std::string &head)>;
  26936. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26937. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26938. class ScopedConnectProxy {
  26939. public:
  26940. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26941. : forward_port_(forward_port), reply_(std::move(reply)) {
  26942. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26943. if (listen_sock_ == INVALID_SOCKET) { return; }
  26944. auto a = loopback(0);
  26945. auto addr = reinterpret_cast<sockaddr *>(&a);
  26946. socklen_t alen = sizeof(a);
  26947. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26948. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26949. ::listen(listen_sock_, 4) != 0) {
  26950. return;
  26951. }
  26952. port_ = ntohs(a.sin_port);
  26953. th_ = std::thread([this] { run(); });
  26954. }
  26955. ~ScopedConnectProxy() {
  26956. if (th_.joinable()) {
  26957. stop_ = true;
  26958. auto wake = connect_to(port_);
  26959. th_.join();
  26960. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26961. }
  26962. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26963. }
  26964. int port() const { return port_; }
  26965. int connect_hits() const { return connect_hits_.load(); }
  26966. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26967. std::string connect_request() const {
  26968. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26969. return connect_request_;
  26970. }
  26971. private:
  26972. static sockaddr_in loopback(int port) {
  26973. sockaddr_in a{};
  26974. a.sin_family = AF_INET;
  26975. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26976. a.sin_port = htons(static_cast<unsigned short>(port));
  26977. return a;
  26978. }
  26979. static socket_t connect_to(int port) {
  26980. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26981. if (sock == INVALID_SOCKET) { return sock; }
  26982. auto a = loopback(port);
  26983. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26984. detail::close_socket(sock);
  26985. return INVALID_SOCKET;
  26986. }
  26987. return sock;
  26988. }
  26989. static bool send_all(socket_t sock, const char *data, size_t size) {
  26990. while (size > 0) {
  26991. auto n = detail::send_socket(sock, data, size, 0);
  26992. if (n <= 0) { return false; }
  26993. data += n;
  26994. size -= static_cast<size_t>(n);
  26995. }
  26996. return true;
  26997. }
  26998. void run() {
  26999. for (;;) {
  27000. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27001. if (stop_) {
  27002. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27003. return;
  27004. }
  27005. if (client == INVALID_SOCKET) { continue; }
  27006. serve(client);
  27007. detail::close_socket(client);
  27008. }
  27009. }
  27010. void serve(socket_t client) {
  27011. std::string head;
  27012. char buf[2048];
  27013. while (head.find("\r\n\r\n") == std::string::npos) {
  27014. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27015. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27016. if (n <= 0) { return; }
  27017. head.append(buf, static_cast<size_t>(n));
  27018. }
  27019. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27020. connect_hits_++;
  27021. {
  27022. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27023. connect_request_ = head;
  27024. }
  27025. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27026. if (!send_all(client, res.data(), res.size()) ||
  27027. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27028. return;
  27029. }
  27030. auto origin = connect_to(forward_port_);
  27031. if (origin == INVALID_SOCKET) { return; }
  27032. // When either side stops, shut both down so the other pump returns too.
  27033. auto pump = [&](socket_t from, socket_t to) {
  27034. char b[8192];
  27035. for (;;) {
  27036. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27037. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27038. }
  27039. detail::shutdown_socket(client);
  27040. detail::shutdown_socket(origin);
  27041. };
  27042. std::thread up([&] { pump(client, origin); });
  27043. pump(origin, client);
  27044. up.join();
  27045. detail::close_socket(origin);
  27046. }
  27047. int forward_port_;
  27048. ConnectReply reply_;
  27049. socket_t listen_sock_ = INVALID_SOCKET;
  27050. int port_ = 0;
  27051. std::thread th_;
  27052. std::atomic<bool> stop_{false};
  27053. std::atomic<int> connect_hits_{0};
  27054. mutable std::mutex connect_request_mutex_;
  27055. std::string connect_request_;
  27056. };
  27057. } // namespace proxy_tunnel_test
  27058. #ifdef CPPHTTPLIB_SSL_ENABLED
  27059. namespace proxy_tunnel_test {
  27060. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27061. class ScopedSSLServer {
  27062. public:
  27063. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27064. port_ = svr_.bind_to_any_port("127.0.0.1");
  27065. }
  27066. ~ScopedSSLServer() {
  27067. svr_.stop();
  27068. if (th_.joinable()) { th_.join(); }
  27069. }
  27070. SSLServer &svr() { return svr_; }
  27071. int port() const { return port_; }
  27072. void listen() {
  27073. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27074. svr_.wait_until_ready();
  27075. }
  27076. private:
  27077. SSLServer svr_;
  27078. std::thread th_;
  27079. int port_ = 0;
  27080. };
  27081. // Sends one request through the CONNECT proxy to the TLS origin with a
  27082. // credential configured for each hop, and checks that each credential reaches
  27083. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27084. // origin's (every header in origin_headers) on the tunnelled request.
  27085. void CredentialsStayWithTheirHop(
  27086. const std::function<void(SSLClient &)> &set_credentials,
  27087. const std::string &scheme,
  27088. const std::vector<std::string> &origin_headers = {"Authorization"},
  27089. bool stream = false) {
  27090. std::atomic<int> origin_hits{0};
  27091. std::atomic<bool> origin_saw_proxy_authz{false};
  27092. std::atomic<bool> origin_saw_headers{false};
  27093. ScopedSSLServer origin;
  27094. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27095. origin_hits++;
  27096. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27097. origin_saw_headers =
  27098. std::all_of(origin_headers.begin(), origin_headers.end(),
  27099. [&](const std::string &h) { return req.has_header(h); });
  27100. res.set_content("ok", "text/plain");
  27101. });
  27102. origin.listen();
  27103. ScopedConnectProxy proxy(origin.port());
  27104. ASSERT_NE(0, proxy.port());
  27105. // Pinned to 127.0.0.1 for the same reason as the test below.
  27106. SSLClient cli("127.0.0.1", origin.port());
  27107. cli.enable_server_certificate_verification(false);
  27108. cli.set_proxy("127.0.0.1", proxy.port());
  27109. set_credentials(cli);
  27110. if (stream) {
  27111. auto handle = cli.open_stream("GET", "/x");
  27112. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27113. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27114. } else {
  27115. auto res = cli.Get("/x");
  27116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27117. EXPECT_EQ(StatusCode::OK_200, res->status);
  27118. }
  27119. EXPECT_EQ(1, origin_hits.load());
  27120. EXPECT_EQ(1, proxy.connect_hits());
  27121. EXPECT_TRUE(origin_saw_headers.load());
  27122. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27123. << "Proxy-Authorization must not be sent inside the tunnel";
  27124. auto connect_req = proxy.connect_request();
  27125. EXPECT_NE(std::string::npos,
  27126. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27127. for (const auto &h : origin_headers) {
  27128. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27129. << h << " must not be sent to the proxy on CONNECT";
  27130. }
  27131. }
  27132. } // namespace proxy_tunnel_test
  27133. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27134. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27135. [](SSLClient &cli) {
  27136. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27137. cli.set_basic_auth("origin-user", "origin-pass");
  27138. },
  27139. "Basic");
  27140. }
  27141. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27142. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27143. [](SSLClient &cli) {
  27144. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27145. cli.set_basic_auth("origin-user", "origin-pass");
  27146. },
  27147. "Basic", {"Authorization"}, true);
  27148. }
  27149. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27150. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27151. [](SSLClient &cli) {
  27152. cli.set_proxy_bearer_token_auth("proxy-token");
  27153. cli.set_bearer_token_auth("origin-token");
  27154. },
  27155. "Bearer");
  27156. }
  27157. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27158. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27159. [](SSLClient &cli) {
  27160. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27161. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27162. {"Cookie", "sid=origin-session"},
  27163. {"X-Api-Key", "origin-key"}});
  27164. },
  27165. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27166. }
  27167. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27168. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27169. // retry; otherwise proxy creds would be sent to the origin.
  27170. std::atomic<int> origin_hits{0};
  27171. std::atomic<bool> origin_saw_proxy_authz{false};
  27172. proxy_tunnel_test::ScopedSSLServer origin;
  27173. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27174. origin_hits++;
  27175. if (req.has_header("Proxy-Authorization")) {
  27176. origin_saw_proxy_authz = true;
  27177. }
  27178. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27179. res.set_header("Proxy-Authenticate",
  27180. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27181. "algorithm=MD5");
  27182. });
  27183. origin.listen();
  27184. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27185. ASSERT_NE(0, proxy.port());
  27186. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27187. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27188. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27189. // and answer with its own status, making this test flaky.
  27190. SSLClient cli("127.0.0.1", origin.port());
  27191. cli.enable_server_certificate_verification(false);
  27192. cli.set_proxy("127.0.0.1", proxy.port());
  27193. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27194. auto res = cli.Get("/x");
  27195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27196. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27197. EXPECT_EQ(1, origin_hits.load());
  27198. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27199. EXPECT_EQ(1, proxy.connect_hits());
  27200. }
  27201. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27202. std::string origin_sni;
  27203. std::string origin_host;
  27204. proxy_tunnel_test::ScopedSSLServer origin;
  27205. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27206. origin_sni = req.sni();
  27207. origin_host = req.get_header_value("Host");
  27208. res.set_content("ok", "text/plain");
  27209. });
  27210. origin.listen();
  27211. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27212. ASSERT_NE(0, proxy.port());
  27213. SSLClient cli("origin.example", origin.port());
  27214. cli.enable_server_certificate_verification(false);
  27215. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27216. cli.set_proxy("127.0.0.1", proxy.port());
  27217. auto res = cli.Get("/x");
  27218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27219. EXPECT_EQ(StatusCode::OK_200, res->status);
  27220. auto port = std::to_string(origin.port());
  27221. auto target = "127.0.0.1:" + port;
  27222. auto connect_req = proxy.connect_request();
  27223. EXPECT_EQ(1, proxy.connect_hits());
  27224. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27225. EXPECT_NE(std::string::npos,
  27226. connect_req.find("\r\nHost: " + target + "\r\n"));
  27227. EXPECT_EQ("origin.example", origin_sni);
  27228. EXPECT_EQ("origin.example:" + port, origin_host);
  27229. }
  27230. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27231. proxy_tunnel_test::ScopedSSLServer origin;
  27232. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27233. res.set_content("ok", "text/plain");
  27234. });
  27235. origin.listen();
  27236. proxy_tunnel_test::ScopedConnectProxy proxy(
  27237. origin.port(), [](const std::string &head) -> std::string {
  27238. if (head.find(
  27239. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27240. std::string::npos) {
  27241. return proxy_tunnel_test::kTunnelEstablished;
  27242. }
  27243. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27244. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27245. "nonce=\"abc\", algorithm=MD5\r\n"
  27246. "Content-Length: 0\r\n\r\n";
  27247. });
  27248. ASSERT_NE(0, proxy.port());
  27249. SSLClient cli("origin.example", origin.port());
  27250. cli.enable_server_certificate_verification(false);
  27251. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27252. cli.set_proxy("127.0.0.1", proxy.port());
  27253. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27254. auto res = cli.Get("/x");
  27255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27256. EXPECT_EQ(StatusCode::OK_200, res->status);
  27257. // The retried CONNECT is the one the proxy saw last.
  27258. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27259. auto connect_req = proxy.connect_request();
  27260. EXPECT_EQ(2, proxy.connect_hits());
  27261. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27262. EXPECT_NE(std::string::npos,
  27263. connect_req.find("\r\nHost: " + target + "\r\n"));
  27264. }
  27265. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27266. proxy_tunnel_test::ScopedSSLServer origin;
  27267. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27268. res.set_content("ok", "text/plain");
  27269. });
  27270. origin.listen();
  27271. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27272. ASSERT_NE(0, proxy.port());
  27273. SSLClient cli("origin.example", origin.port());
  27274. cli.enable_server_certificate_verification(false);
  27275. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27276. cli.set_proxy("127.0.0.1", proxy.port());
  27277. auto res = cli.Get("/x");
  27278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27279. EXPECT_EQ(StatusCode::OK_200, res->status);
  27280. auto target = "origin.example:" + std::to_string(origin.port());
  27281. auto connect_req = proxy.connect_request();
  27282. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27283. EXPECT_NE(std::string::npos,
  27284. connect_req.find("\r\nHost: " + target + "\r\n"));
  27285. }
  27286. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27287. proxy_tunnel_test::ScopedSSLServer origin;
  27288. auto port = std::to_string(origin.port());
  27289. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27290. res.set_redirect("https://next.example:" + port + "/y");
  27291. });
  27292. origin.svr().Get("/y", [](const Request &, Response &res) {
  27293. res.set_content("ok", "text/plain");
  27294. });
  27295. origin.listen();
  27296. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27297. ASSERT_NE(0, proxy.port());
  27298. SSLClient cli("origin.example", origin.port());
  27299. cli.enable_server_certificate_verification(false);
  27300. cli.set_tunnel_hostname_addr_map(
  27301. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27302. cli.set_proxy("127.0.0.1", proxy.port());
  27303. cli.set_follow_location(true);
  27304. auto res = cli.Get("/x");
  27305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27306. EXPECT_EQ("ok", res->body);
  27307. // The last CONNECT is the redirect client's.
  27308. ASSERT_EQ(2, proxy.connect_hits());
  27309. auto target = "127.0.0.1:" + port;
  27310. auto connect_req = proxy.connect_request();
  27311. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27312. EXPECT_NE(std::string::npos,
  27313. connect_req.find("\r\nHost: " + target + "\r\n"));
  27314. }
  27315. #endif
  27316. namespace proxy_tunnel_test {
  27317. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27318. // anything else gets a 407 with `challenge`.
  27319. ConnectReply require_proxy_auth(const std::string &expected,
  27320. const std::string &challenge) {
  27321. return [=](const std::string &head) -> std::string {
  27322. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27323. std::string::npos) {
  27324. return kTunnelEstablished;
  27325. }
  27326. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27327. "Proxy-Authenticate: " +
  27328. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27329. };
  27330. }
  27331. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27332. // request, then echoes.
  27333. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27334. ws.send(
  27335. "authorization:" + req.get_header_value("Authorization") +
  27336. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27337. std::string msg;
  27338. while (ws.read(msg)) {
  27339. ws.send(msg);
  27340. }
  27341. }
  27342. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27343. class ScopedWebSocketOrigin {
  27344. public:
  27345. ScopedWebSocketOrigin() {
  27346. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27347. server_.listen();
  27348. }
  27349. int port() const { return server_.port(); }
  27350. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27351. std::string url() const {
  27352. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27353. }
  27354. private:
  27355. no_proxy_test::ScopedServer server_;
  27356. };
  27357. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27358. // passed as a constructor header, and checks that each reaches only its hop.
  27359. void WebSocketCredentialsStayWithTheirHop(
  27360. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27361. const std::string &proxy_authz, const std::string &origin_authz) {
  27362. ScopedWebSocketOrigin origin;
  27363. ScopedConnectProxy proxy(
  27364. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27365. ASSERT_NE(0, proxy.port());
  27366. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27367. client.set_proxy("127.0.0.1", proxy.port());
  27368. set_proxy_credentials(client);
  27369. auto res = client.connect();
  27370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27371. std::string msg;
  27372. ASSERT_TRUE(client.read(msg));
  27373. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27374. client.close();
  27375. EXPECT_EQ(1, proxy.connect_hits());
  27376. EXPECT_EQ(std::string::npos,
  27377. proxy.connect_request().find("\r\nAuthorization: "))
  27378. << "origin credentials must not be sent to the proxy";
  27379. }
  27380. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27381. void WebSocketSetterCredentialsStayWithTheirHop(
  27382. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27383. const std::string &proxy_authz, const std::string &origin_authz) {
  27384. ScopedWebSocketOrigin origin;
  27385. ScopedConnectProxy proxy(
  27386. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27387. ASSERT_NE(0, proxy.port());
  27388. ws::WebSocketClient client(origin.url());
  27389. client.set_proxy("127.0.0.1", proxy.port());
  27390. set_credentials(client);
  27391. auto res = client.connect();
  27392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27393. std::string msg;
  27394. ASSERT_TRUE(client.read(msg));
  27395. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27396. client.close();
  27397. EXPECT_EQ(1, proxy.connect_hits());
  27398. EXPECT_EQ(std::string::npos,
  27399. proxy.connect_request().find("\r\nAuthorization: "))
  27400. << "origin credentials must not be sent to the proxy";
  27401. }
  27402. } // namespace proxy_tunnel_test
  27403. namespace {
  27404. // Connects `client` and returns the Authorization header its upgrade
  27405. // request carried, or "<failed>" when the connection could not be opened.
  27406. std::string websocket_authorization(ws::WebSocketClient &client) {
  27407. if (!client.connect()) { return "<failed>"; }
  27408. std::string msg;
  27409. if (!client.read(msg)) { return "<failed>"; }
  27410. client.close();
  27411. auto prefix = std::string("authorization:");
  27412. auto end = msg.find("|proxy-authorization:");
  27413. return msg.substr(prefix.size(), end - prefix.size());
  27414. }
  27415. } // namespace
  27416. TEST(WebSocketClientAuthTest, BasicAuth) {
  27417. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27418. ws::WebSocketClient client(origin.url());
  27419. client.set_basic_auth("user", "pass");
  27420. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27421. websocket_authorization(client));
  27422. }
  27423. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27424. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27425. ws::WebSocketClient client(origin.url());
  27426. client.set_basic_auth("user", "");
  27427. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27428. websocket_authorization(client));
  27429. }
  27430. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27431. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27432. ws::WebSocketClient client(origin.url());
  27433. client.set_bearer_token_auth("token123");
  27434. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27435. }
  27436. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27437. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27438. ws::WebSocketClient client(origin.url());
  27439. client.set_bearer_token_auth("token123");
  27440. client.set_basic_auth("user", "pass");
  27441. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27442. websocket_authorization(client));
  27443. }
  27444. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27445. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27446. ws::WebSocketClient client(origin.url(),
  27447. {{"Authorization", "Bearer from-header"}});
  27448. client.set_bearer_token_auth("from-setter");
  27449. client.set_basic_auth("user", "pass");
  27450. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27451. }
  27452. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27453. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27454. ws::WebSocketClient client(origin.url());
  27455. EXPECT_EQ("", websocket_authorization(client));
  27456. client.set_bearer_token_auth("first");
  27457. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27458. client.set_bearer_token_auth("second");
  27459. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27460. client.set_bearer_token_auth("");
  27461. EXPECT_EQ("", websocket_authorization(client));
  27462. }
  27463. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27464. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27465. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27466. ASSERT_NE(0, proxy.port());
  27467. ws::WebSocketClient client(origin.url());
  27468. client.set_proxy("127.0.0.1", proxy.port());
  27469. auto res = client.connect();
  27470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27471. std::string msg;
  27472. ASSERT_TRUE(client.read(msg));
  27473. ASSERT_TRUE(client.send("hello"));
  27474. ASSERT_TRUE(client.read(msg));
  27475. EXPECT_EQ("hello", msg);
  27476. client.close();
  27477. EXPECT_EQ(1, proxy.connect_hits());
  27478. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27479. auto connect_req = proxy.connect_request();
  27480. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27481. EXPECT_NE(std::string::npos,
  27482. connect_req.find("\r\nHost: " + target + "\r\n"));
  27483. }
  27484. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27485. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27486. [](ws::WebSocketClient &cli) {
  27487. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27488. },
  27489. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27490. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27491. }
  27492. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27493. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27494. [](ws::WebSocketClient &cli) {
  27495. cli.set_proxy_bearer_token_auth("proxy-token");
  27496. },
  27497. "Bearer proxy-token", "Bearer origin-token");
  27498. }
  27499. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27500. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27501. [](ws::WebSocketClient &cli) {
  27502. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27503. cli.set_basic_auth("origin-user", "origin-pass");
  27504. },
  27505. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27506. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27507. }
  27508. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27509. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27510. [](ws::WebSocketClient &cli) {
  27511. cli.set_proxy_bearer_token_auth("proxy-token");
  27512. cli.set_bearer_token_auth("origin-token");
  27513. },
  27514. "Bearer proxy-token", "Bearer origin-token");
  27515. }
  27516. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27517. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27518. proxy_tunnel_test::ScopedConnectProxy proxy(
  27519. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27520. "Basic " + detail::base64_encode("proxy-user:"),
  27521. "Basic realm=\"proxy\""));
  27522. ASSERT_NE(0, proxy.port());
  27523. ws::WebSocketClient client(origin.url());
  27524. client.set_proxy("127.0.0.1", proxy.port());
  27525. client.set_proxy_basic_auth("proxy-user", "");
  27526. auto res = client.connect();
  27527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27528. client.close();
  27529. EXPECT_EQ(1, proxy.connect_hits());
  27530. }
  27531. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27532. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27533. proxy_tunnel_test::ScopedConnectProxy proxy(
  27534. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27535. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27536. ASSERT_NE(0, proxy.port());
  27537. ws::WebSocketClient client(origin.url());
  27538. client.set_proxy("127.0.0.1", proxy.port());
  27539. auto res = client.connect();
  27540. EXPECT_FALSE(res);
  27541. EXPECT_EQ(Error::ProxyConnection, res.error());
  27542. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27543. EXPECT_EQ("Basic realm=\"proxy\"",
  27544. res.get_header_value("Proxy-Authenticate"));
  27545. EXPECT_FALSE(client.is_open());
  27546. }
  27547. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27548. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27549. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27550. ASSERT_NE(0, proxy.port());
  27551. ws::WebSocketClient client(origin.url());
  27552. client.set_proxy("127.0.0.1", proxy.port());
  27553. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27554. client.set_no_proxy({"127.0.0.1"});
  27555. auto res = client.connect();
  27556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27557. std::string msg;
  27558. ASSERT_TRUE(client.read(msg));
  27559. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27560. << "proxy credentials must not reach a bypassed origin";
  27561. client.close();
  27562. EXPECT_EQ(0, proxy.connect_hits());
  27563. }
  27564. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27565. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27566. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27567. ASSERT_NE(0, proxy.port());
  27568. ws::WebSocketClient client(origin.url());
  27569. client.set_proxy("127.0.0.1", proxy.port());
  27570. ASSERT_TRUE(client.connect());
  27571. ASSERT_TRUE(client.connect());
  27572. client.close();
  27573. EXPECT_EQ(2, proxy.connect_hits());
  27574. }
  27575. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27576. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27577. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27578. ASSERT_NE(0, proxy.port());
  27579. auto port = std::to_string(origin.port());
  27580. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27581. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27582. client.set_proxy("127.0.0.1", proxy.port());
  27583. auto res = client.connect();
  27584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27585. std::string msg;
  27586. ASSERT_TRUE(client.read(msg));
  27587. client.close();
  27588. EXPECT_EQ(1, proxy.connect_hits());
  27589. auto target = "127.0.0.1:" + port;
  27590. auto connect_req = proxy.connect_request();
  27591. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27592. EXPECT_NE(std::string::npos,
  27593. connect_req.find("\r\nHost: " + target + "\r\n"));
  27594. }
  27595. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27596. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27597. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27598. ASSERT_NE(0, proxy.port());
  27599. auto port = std::to_string(origin.port());
  27600. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27601. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27602. client.set_proxy("127.0.0.1", proxy.port());
  27603. auto res = client.connect();
  27604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27605. client.close();
  27606. auto target = "origin.example:" + port;
  27607. auto connect_req = proxy.connect_request();
  27608. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27609. EXPECT_NE(std::string::npos,
  27610. connect_req.find("\r\nHost: " + target + "\r\n"));
  27611. }
  27612. #ifdef CPPHTTPLIB_SSL_ENABLED
  27613. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27614. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27615. proxy_tunnel_test::ScopedConnectProxy proxy(
  27616. origin.port(), [](const std::string &head) -> std::string {
  27617. if (head.find(
  27618. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27619. std::string::npos) {
  27620. return proxy_tunnel_test::kTunnelEstablished;
  27621. }
  27622. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27623. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27624. "nonce=\"abc\", algorithm=MD5\r\n"
  27625. "Content-Length: 0\r\n\r\n";
  27626. });
  27627. ASSERT_NE(0, proxy.port());
  27628. ws::WebSocketClient client(origin.url());
  27629. client.set_proxy("127.0.0.1", proxy.port());
  27630. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27631. auto res = client.connect();
  27632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27633. std::string msg;
  27634. ASSERT_TRUE(client.read(msg));
  27635. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27636. client.close();
  27637. EXPECT_EQ(2, proxy.connect_hits());
  27638. }
  27639. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27640. proxy_tunnel_test::ScopedSSLServer origin;
  27641. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27642. origin.listen();
  27643. proxy_tunnel_test::ScopedConnectProxy proxy(
  27644. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27645. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27646. ASSERT_NE(0, proxy.port());
  27647. ws::WebSocketClient client(
  27648. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27649. client.enable_server_certificate_verification(false);
  27650. client.set_proxy("127.0.0.1", proxy.port());
  27651. client.set_proxy_bearer_token_auth("proxy-token");
  27652. auto res = client.connect();
  27653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27654. std::string msg;
  27655. ASSERT_TRUE(client.read(msg));
  27656. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27657. << "Proxy-Authorization must not be sent inside the tunnel";
  27658. client.close();
  27659. EXPECT_EQ(1, proxy.connect_hits());
  27660. }
  27661. #endif