1
0

test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584
  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(GetAddrInfoDanglingRefTest, LongTimeout) {
  2388. auto host = "unresolvableaddress.local";
  2389. auto path = std::string{"/"};
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. auto port = 443;
  2392. SSLClient cli(host, port);
  2393. #else
  2394. auto port = 80;
  2395. Client cli(host, port);
  2396. #endif
  2397. cli.set_connection_timeout(1);
  2398. {
  2399. auto res = cli.Get(path);
  2400. ASSERT_FALSE(res);
  2401. }
  2402. std::this_thread::sleep_for(std::chrono::seconds(8));
  2403. }
  2404. #if defined(__linux__) && defined(__GLIBC__) && \
  2405. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2406. // Forward declaration: in split builds split.py strips `inline` and moves the
  2407. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2408. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2409. // against the symbol in both header-only and split builds.
  2410. namespace httplib {
  2411. namespace detail {
  2412. int getaddrinfo_with_timeout(const char *node, const char *service,
  2413. const struct addrinfo *hints,
  2414. struct addrinfo **res, time_t timeout_sec);
  2415. } // namespace detail
  2416. } // namespace httplib
  2417. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2418. //
  2419. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2420. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2421. // gai_suspend() call hits the connection timeout the function calls
  2422. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2423. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2424. // still alive and still references the now-destroyed stack frame.
  2425. //
  2426. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2427. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2428. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2429. // and runs them in a container.
  2430. namespace {
  2431. bool should_run_issue_2431_tests() {
  2432. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2433. return v && *v && std::string(v) != "0";
  2434. }
  2435. std::string unique_unresolvable_host(int n) {
  2436. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2437. // glibc still asks the configured nameserver — which is exactly the path
  2438. // we want to exercise. A unique label per call avoids the resolver cache.
  2439. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2440. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2441. std::to_string(n) + ".invalid";
  2442. }
  2443. } // namespace
  2444. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2445. if (!should_run_issue_2431_tests()) {
  2446. GTEST_SKIP()
  2447. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2448. }
  2449. for (int i = 0; i < 8; ++i) {
  2450. struct addrinfo hints;
  2451. memset(&hints, 0, sizeof(hints));
  2452. hints.ai_family = AF_UNSPEC;
  2453. hints.ai_socktype = SOCK_STREAM;
  2454. auto host = unique_unresolvable_host(i);
  2455. struct addrinfo *result = nullptr;
  2456. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2457. &result, /*timeout_sec=*/1);
  2458. if (rc == 0 && result) { freeaddrinfo(result); }
  2459. }
  2460. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2461. // stack region they still believe holds their gaicb.
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2465. if (!should_run_issue_2431_tests()) {
  2466. GTEST_SKIP()
  2467. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2468. }
  2469. std::atomic<bool> stop{false};
  2470. std::vector<std::thread> threads;
  2471. for (int t = 0; t < 8; ++t) {
  2472. threads.emplace_back([t, &stop] {
  2473. int i = 0;
  2474. while (!stop.load(std::memory_order_relaxed)) {
  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(t * 100000 + 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. });
  2486. }
  2487. std::this_thread::sleep_for(std::chrono::seconds(8));
  2488. stop.store(true, std::memory_order_relaxed);
  2489. for (auto &th : threads) {
  2490. th.join();
  2491. }
  2492. std::this_thread::sleep_for(std::chrono::seconds(3));
  2493. }
  2494. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2495. if (!should_run_issue_2431_tests()) {
  2496. GTEST_SKIP()
  2497. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2498. }
  2499. std::atomic<bool> stop{false};
  2500. std::vector<std::thread> threads;
  2501. for (int t = 0; t < 8; ++t) {
  2502. threads.emplace_back([t, &stop] {
  2503. int i = 0;
  2504. while (!stop.load(std::memory_order_relaxed)) {
  2505. auto host = unique_unresolvable_host(t * 100000 + i++);
  2506. Client cli(host, 80);
  2507. cli.set_connection_timeout(1, 0);
  2508. cli.set_read_timeout(1, 0);
  2509. cli.set_write_timeout(1, 0);
  2510. (void)cli.Get("/");
  2511. }
  2512. });
  2513. }
  2514. std::this_thread::sleep_for(std::chrono::seconds(8));
  2515. stop.store(true, std::memory_order_relaxed);
  2516. for (auto &th : threads) {
  2517. th.join();
  2518. }
  2519. std::this_thread::sleep_for(std::chrono::seconds(3));
  2520. }
  2521. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2522. TEST(ConnectionErrorTest, InvalidHost) {
  2523. auto host = "-abcde.com";
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(2));
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::Connection, res.error());
  2535. }
  2536. TEST(ConnectionErrorTest, InvalidHost2) {
  2537. auto host = "httpcan.org/";
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. SSLClient cli(host);
  2540. #else
  2541. Client cli(host);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. auto res = cli.Get("/");
  2545. ASSERT_TRUE(!res);
  2546. EXPECT_EQ(Error::Connection, res.error());
  2547. }
  2548. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2549. auto host = "httpcan.org/";
  2550. #ifdef CPPHTTPLIB_SSL_ENABLED
  2551. SSLClient cli(host);
  2552. #else
  2553. Client cli(host);
  2554. #endif
  2555. cli.set_connection_timeout(std::chrono::seconds(2));
  2556. auto res = cli.Get("/");
  2557. ASSERT_TRUE(!res);
  2558. stringstream s;
  2559. s << "error code: " << res.error();
  2560. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2561. }
  2562. TEST(ConnectionErrorTest, InvalidPort) {
  2563. auto host = "localhost";
  2564. auto port = 44380;
  2565. #ifdef CPPHTTPLIB_SSL_ENABLED
  2566. SSLClient cli(host, port);
  2567. #else
  2568. Client cli(host, port);
  2569. #endif
  2570. cli.set_connection_timeout(std::chrono::seconds(2));
  2571. auto res = cli.Get("/");
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_TRUE(Error::Connection == res.error() ||
  2574. Error::ConnectionTimeout == res.error());
  2575. }
  2576. TEST(ConnectionErrorTest, Timeout_Online) {
  2577. auto host = "google.com";
  2578. #ifdef CPPHTTPLIB_SSL_ENABLED
  2579. auto port = 44380;
  2580. SSLClient cli(host, port);
  2581. #else
  2582. auto port = 8080;
  2583. Client cli(host, port);
  2584. #endif
  2585. cli.set_connection_timeout(std::chrono::seconds(2));
  2586. // only probe one address type so that the error reason
  2587. // correlates to the timed-out IPv4, not the unsupported
  2588. // IPv6 connection attempt
  2589. cli.set_address_family(AF_INET);
  2590. auto res = cli.Get("/");
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2593. }
  2594. TEST(CancelTest, NoCancel_Online) {
  2595. auto host = "httpbingo.org";
  2596. auto path = std::string{"/range/32"};
  2597. #ifdef CPPHTTPLIB_SSL_ENABLED
  2598. auto port = 443;
  2599. SSLClient cli(host, port);
  2600. #else
  2601. auto port = 80;
  2602. Client cli(host, port);
  2603. #endif
  2604. cli.set_connection_timeout(std::chrono::seconds(5));
  2605. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. }
  2610. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2611. // Use /bytes with a large payload so that the DownloadProgress callback
  2612. // (which only fires for Content-Length responses) is invoked before the
  2613. // entire body is received, giving cancellation a chance to fire.
  2614. auto host = "httpbingo.org";
  2615. auto path = std::string{"/bytes/524288"};
  2616. #ifdef CPPHTTPLIB_SSL_ENABLED
  2617. auto port = 443;
  2618. SSLClient cli(host, port);
  2619. #else
  2620. auto port = 80;
  2621. Client cli(host, port);
  2622. #endif
  2623. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayload_Online) {
  2629. auto host = "httpbingo.org";
  2630. auto path = std::string{"/bytes/524288"};
  2631. #ifdef CPPHTTPLIB_SSL_ENABLED
  2632. auto port = 443;
  2633. SSLClient cli(host, port);
  2634. #else
  2635. auto port = 80;
  2636. Client cli(host, port);
  2637. #endif
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. uint32_t count = 0;
  2640. auto res =
  2641. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, NoCancelPost) {
  2646. Server svr;
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content("Hello World!", "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_connection_timeout(std::chrono::seconds(5));
  2659. auto res =
  2660. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2661. "application/json", [](uint64_t, uint64_t) { return true; });
  2662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2663. EXPECT_EQ("Hello World!", res->body);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. }
  2666. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2667. Server svr;
  2668. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return false; });
  2683. ASSERT_TRUE(!res);
  2684. EXPECT_EQ(Error::Canceled, res.error());
  2685. }
  2686. TEST(CancelTest, WithCancelLargePayloadPost) {
  2687. Server svr;
  2688. svr.set_payload_max_length(200 * 1024 * 1024);
  2689. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content(LARGE_DATA, "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_payload_max_length(200 * 1024 * 1024);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, NoCancelPut) {
  2709. Server svr;
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!", "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_connection_timeout(std::chrono::seconds(5));
  2722. auto res =
  2723. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2724. "application/json", [](uint64_t, uint64_t) { return true; });
  2725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2726. EXPECT_EQ("Hello World!", res->body);
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2730. Server svr;
  2731. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return false; });
  2746. ASSERT_TRUE(!res);
  2747. EXPECT_EQ(Error::Canceled, res.error());
  2748. }
  2749. TEST(CancelTest, WithCancelLargePayloadPut) {
  2750. Server svr;
  2751. svr.set_payload_max_length(200 * 1024 * 1024);
  2752. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content(LARGE_DATA, "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_payload_max_length(200 * 1024 * 1024);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, NoCancelPatch) {
  2772. Server svr;
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_connection_timeout(std::chrono::seconds(5));
  2785. auto res =
  2786. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2787. "application/json", [](uint64_t, uint64_t) { return true; });
  2788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2789. EXPECT_EQ("Hello World!", res->body);
  2790. EXPECT_EQ(StatusCode::OK_200, res->status);
  2791. }
  2792. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2793. Server svr;
  2794. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return false; });
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::Canceled, res.error());
  2811. }
  2812. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2813. Server svr;
  2814. svr.set_payload_max_length(200 * 1024 * 1024);
  2815. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(LARGE_DATA, "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_payload_max_length(200 * 1024 * 1024);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, NoCancelDelete) {
  2835. Server svr;
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content("Hello World!", "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_connection_timeout(std::chrono::seconds(5));
  2848. auto res =
  2849. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2850. "application/json", [](uint64_t, uint64_t) { return true; });
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ("Hello World!", res->body);
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2856. Server svr;
  2857. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2858. res.set_content("Hello World!", "text/plain");
  2859. });
  2860. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. Client cli(HOST, PORT);
  2868. cli.set_connection_timeout(std::chrono::seconds(5));
  2869. auto res =
  2870. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2871. "application/json", [](uint64_t, uint64_t) { return false; });
  2872. ASSERT_TRUE(!res);
  2873. EXPECT_EQ(Error::Canceled, res.error());
  2874. }
  2875. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2876. Server svr;
  2877. svr.set_payload_max_length(200 * 1024 * 1024);
  2878. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2879. res.set_content(LARGE_DATA, "text/plain");
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, PORT);
  2889. cli.set_payload_max_length(200 * 1024 * 1024);
  2890. cli.set_connection_timeout(std::chrono::seconds(5));
  2891. auto res =
  2892. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2893. "application/json", [](uint64_t, uint64_t) { return false; });
  2894. ASSERT_TRUE(!res);
  2895. EXPECT_EQ(Error::Canceled, res.error());
  2896. }
  2897. // One stop() from another thread ends a request that waits for the response
  2898. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2899. Server svr;
  2900. std::atomic<bool> received{false};
  2901. std::atomic<bool> done{false};
  2902. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2903. received.store(true);
  2904. while (!done.load()) {
  2905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2906. }
  2907. res.set_content("Hello World!", "text/plain");
  2908. });
  2909. auto port = svr.bind_to_any_port(HOST);
  2910. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2911. Client cli(HOST, port);
  2912. cli.set_read_timeout(std::chrono::seconds(30));
  2913. std::future<Result> request;
  2914. auto se = detail::scope_exit([&] {
  2915. done.store(true);
  2916. svr.stop();
  2917. thread.join();
  2918. ASSERT_FALSE(svr.is_running());
  2919. });
  2920. svr.wait_until_ready();
  2921. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  2922. for (int i = 0; i < 500 && !received.load(); ++i) {
  2923. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2924. }
  2925. ASSERT_TRUE(received.load());
  2926. // Let the client block in the wait for the response
  2927. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2928. auto start = std::chrono::steady_clock::now();
  2929. cli.stop();
  2930. ASSERT_EQ(std::future_status::ready,
  2931. request.wait_for(std::chrono::seconds(5)));
  2932. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  2933. auto res = request.get();
  2934. ASSERT_TRUE(!res);
  2935. EXPECT_EQ(Error::Read, res.error());
  2936. }
  2937. static std::string remove_whitespace(const std::string &input) {
  2938. std::string output;
  2939. output.reserve(input.size());
  2940. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2941. [](unsigned char c) { return !std::isspace(c); });
  2942. return output;
  2943. }
  2944. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2945. auto host = "httpbingo.org";
  2946. auto path = std::string{"/basic-auth/hello/world"};
  2947. #ifdef CPPHTTPLIB_SSL_ENABLED
  2948. auto port = 443;
  2949. SSLClient cli(host, port);
  2950. #else
  2951. auto port = 80;
  2952. Client cli(host, port);
  2953. #endif
  2954. {
  2955. auto res = cli.Get(path);
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2958. }
  2959. {
  2960. auto res = cli.Get(
  2961. path, Headers{make_basic_authentication_header("hello", "world")});
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. auto body = remove_whitespace(res->body);
  2964. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2965. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2966. EXPECT_EQ(StatusCode::OK_200, res->status);
  2967. }
  2968. {
  2969. cli.set_basic_auth("hello", "world");
  2970. auto res = cli.Get(path);
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. auto body = remove_whitespace(res->body);
  2973. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2974. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. }
  2977. {
  2978. cli.set_basic_auth("hello", "bad");
  2979. auto res = cli.Get(path);
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2982. }
  2983. {
  2984. cli.set_basic_auth("bad", "world");
  2985. auto res = cli.Get(path);
  2986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2987. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2988. }
  2989. }
  2990. #ifdef CPPHTTPLIB_SSL_ENABLED
  2991. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2992. auto host = "httpbingo.org";
  2993. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2994. auto paths = std::vector<std::string>{
  2995. "/digest-auth/auth/hello/world/MD5",
  2996. "/digest-auth/auth/hello/world/SHA-256",
  2997. };
  2998. auto port = 443;
  2999. SSLClient cli(host, port);
  3000. {
  3001. auto res = cli.Get(unauth_path);
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3004. }
  3005. {
  3006. cli.set_digest_auth("hello", "world");
  3007. for (const auto &path : paths) {
  3008. auto res = cli.Get(path.c_str());
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. auto body = remove_whitespace(res->body);
  3011. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3012. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. }
  3015. cli.set_digest_auth("hello", "bad");
  3016. for (const auto &path : paths) {
  3017. auto res = cli.Get(path.c_str());
  3018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3019. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3020. }
  3021. }
  3022. }
  3023. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3024. // comma-separated list of challenges, and each challenge may itself carry a
  3025. // comma-separated auth-param list, so a server can legally offer Basic
  3026. // before Digest, either as two field lines or packed into one. Runs one 401
  3027. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3028. // value() joins them in receipt order) and checks that the retry carries a
  3029. // well-formed Digest Authorization header naming expected_realm.
  3030. static void
  3031. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3032. const std::string &expected_realm) {
  3033. std::atomic<int> hits{0};
  3034. Server svr;
  3035. svr.Get("/x", [&](const Request &req, Response &res) {
  3036. if (++hits == 1) {
  3037. res.status = StatusCode::Unauthorized_401;
  3038. for (const auto &challenge : challenges) {
  3039. res.set_header("WWW-Authenticate", challenge);
  3040. }
  3041. } else {
  3042. auto authorization = req.get_header_value("Authorization");
  3043. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3044. EXPECT_NE(std::string::npos,
  3045. authorization.find("realm=\"" + expected_realm + "\""));
  3046. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3047. res.set_content("ok", "text/plain");
  3048. }
  3049. });
  3050. auto port = svr.bind_to_any_port(HOST);
  3051. std::thread t([&]() { svr.listen_after_bind(); });
  3052. auto se = detail::scope_exit([&] {
  3053. svr.stop();
  3054. t.join();
  3055. });
  3056. svr.wait_until_ready();
  3057. Client cli(HOST, port);
  3058. cli.set_digest_auth("hello", "world");
  3059. auto res = cli.Get("/x");
  3060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3061. EXPECT_EQ(2, hits.load());
  3062. }
  3063. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3064. static const char *kDigestChallenge =
  3065. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3066. "algorithm=MD5";
  3067. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3068. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3069. "testrealm");
  3070. }
  3071. // Same challenge list with the schemes in the opposite order, to make sure
  3072. // the fix above didn't just special-case "Basic first".
  3073. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3074. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3075. "testrealm");
  3076. }
  3077. // A comma inside a quoted auth-param value must not be mistaken for the
  3078. // separator between two challenges (or two auth-params).
  3079. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3080. run_digest_challenge_list_test(
  3081. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3082. "algorithm=MD5"},
  3083. "test,realm");
  3084. }
  3085. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3086. // the params and leaves out the fragment.
  3087. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3088. Server svr;
  3089. std::string uri, target;
  3090. svr.Get("/a b", [&](const Request &req, Response &res) {
  3091. auto auth = req.get_header_value("Authorization");
  3092. if (auth.empty()) {
  3093. res.status = StatusCode::Unauthorized_401;
  3094. res.set_header("WWW-Authenticate",
  3095. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3096. return;
  3097. }
  3098. auto b = auth.find("uri=\"") + 5;
  3099. uri = auth.substr(b, auth.find('"', b) - b);
  3100. target = req.target;
  3101. });
  3102. auto port = svr.bind_to_any_port(HOST);
  3103. std::thread t([&]() { svr.listen_after_bind(); });
  3104. auto se = detail::scope_exit([&] {
  3105. svr.stop();
  3106. t.join();
  3107. });
  3108. svr.wait_until_ready();
  3109. Client cli(HOST, port);
  3110. cli.set_digest_auth("hello", "world");
  3111. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3113. EXPECT_EQ("/a%20b?x=1", target);
  3114. EXPECT_EQ(target, uri);
  3115. }
  3116. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3117. // make_digest_authentication_header() dereferences both unconditionally, so
  3118. // a server sending a challenge missing either one must not be treated as
  3119. // usable -- doing so used to crash the client with std::out_of_range.
  3120. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3121. Server svr;
  3122. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3123. res.status = StatusCode::Unauthorized_401;
  3124. res.set_header("WWW-Authenticate", challenge);
  3125. });
  3126. auto port = svr.bind_to_any_port(HOST);
  3127. std::thread t([&]() { svr.listen_after_bind(); });
  3128. auto se = detail::scope_exit([&] {
  3129. svr.stop();
  3130. t.join();
  3131. });
  3132. svr.wait_until_ready();
  3133. Client cli(HOST, port);
  3134. cli.set_digest_auth("hello", "world");
  3135. auto res = cli.Get("/x");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3138. }
  3139. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3140. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3141. }
  3142. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3143. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3144. }
  3145. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3146. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3147. }
  3148. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3149. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3150. // when storing the values, so the header builder has to re-escape them (and
  3151. // keep algorithm a bare token); otherwise the value breaks out of its
  3152. // quoted-string and injects extra auth-params into the client's Authorization.
  3153. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3154. std::atomic<int> hits{0};
  3155. std::string authorization;
  3156. Server svr;
  3157. svr.Get("/x", [&](const Request &req, Response &res) {
  3158. if (++hits == 1) {
  3159. res.status = StatusCode::Unauthorized_401;
  3160. // On the wire the quotes embedded in the values are backslash-escaped.
  3161. res.set_header("WWW-Authenticate",
  3162. "Digest realm=\"testrealm\", "
  3163. "nonce=\"n\\\"; injected=\\\"x\", "
  3164. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3165. } else {
  3166. authorization = req.get_header_value("Authorization");
  3167. res.set_content("ok", "text/plain");
  3168. }
  3169. });
  3170. auto port = svr.bind_to_any_port(HOST);
  3171. std::thread t([&]() { svr.listen_after_bind(); });
  3172. auto se = detail::scope_exit([&] {
  3173. svr.stop();
  3174. t.join();
  3175. });
  3176. svr.wait_until_ready();
  3177. Client cli(HOST, port);
  3178. cli.set_digest_auth("hello", "world");
  3179. auto res = cli.Get("/x");
  3180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3181. EXPECT_EQ(2, hits.load());
  3182. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3183. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3184. // inside its quoted-string rather than starting an "injected" auth-param.
  3185. EXPECT_NE(std::string::npos,
  3186. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3187. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3188. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3189. }
  3190. #endif
  3191. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3192. auto host = "google.com";
  3193. auto another_host = "example.com";
  3194. auto wrong_ip = "0.0.0.0";
  3195. #ifdef CPPHTTPLIB_SSL_ENABLED
  3196. SSLClient cli(host);
  3197. #else
  3198. Client cli(host);
  3199. #endif
  3200. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3201. auto res = cli.Get("/");
  3202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3203. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3204. }
  3205. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3206. auto host = "google.com";
  3207. auto wrong_ip = "0.0.0.0";
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. SSLClient cli(host);
  3210. #else
  3211. Client cli(host);
  3212. #endif
  3213. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3214. auto res = cli.Get("/");
  3215. ASSERT_TRUE(!res);
  3216. EXPECT_EQ(Error::Connection, res.error());
  3217. }
  3218. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3219. // A mapped value that is not an IP literal must be resolved. "localhost"
  3220. // resolves from the hosts file, so this test needs no external DNS.
  3221. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3222. auto host = "target.invalid";
  3223. Server svr;
  3224. std::string received_host;
  3225. svr.Get("/hi", [&](const Request &req, Response &res) {
  3226. received_host = req.get_header_value("Host");
  3227. res.set_content("Hello World!", "text/plain");
  3228. });
  3229. auto port = svr.bind_to_any_port(HOST);
  3230. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3231. auto se = detail::scope_exit([&] {
  3232. svr.stop();
  3233. thread.join();
  3234. ASSERT_FALSE(svr.is_running());
  3235. });
  3236. svr.wait_until_ready();
  3237. Client cli(host, port);
  3238. cli.set_direct_hostname_addr_map({{host, HOST}});
  3239. auto res = cli.Get("/hi");
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. // The mapping only redirects the connection; the identity stays host_.
  3243. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3244. }
  3245. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3246. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3247. auto host = "target.invalid";
  3248. Server svr;
  3249. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3250. res.set_content("Hello World!", "text/plain");
  3251. });
  3252. auto port = svr.bind_to_any_port("127.0.0.1");
  3253. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. thread.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. svr.wait_until_ready();
  3260. Client cli(host, port);
  3261. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3262. auto res = cli.Get("/hi");
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3267. // An empty mapped value must leave host_ as the connection target. Without
  3268. // that guard the empty value would become the host argument, getaddrinfo
  3269. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3270. // loopback - silently connecting somewhere the caller never asked for.
  3271. // The server listens on loopback, so such a fallback would succeed and is
  3272. // therefore observable as a failure of this test.
  3273. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3274. Server svr;
  3275. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3276. res.set_content("Hello World!", "text/plain");
  3277. });
  3278. auto port = svr.bind_to_any_port(HOST);
  3279. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3280. auto se = detail::scope_exit([&] {
  3281. svr.stop();
  3282. thread.join();
  3283. ASSERT_FALSE(svr.is_running());
  3284. });
  3285. svr.wait_until_ready();
  3286. Client cli(blackhole, port);
  3287. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3288. cli.set_connection_timeout(1);
  3289. auto res = cli.Get("/hi");
  3290. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3291. }
  3292. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3293. auto host = "target.invalid";
  3294. Server svr;
  3295. std::string received_host;
  3296. svr.Get("/hi", [&](const Request &req, Response &res) {
  3297. received_host = req.get_header_value("Host");
  3298. res.set_content("Hello World!", "text/plain");
  3299. });
  3300. auto port = svr.bind_to_any_port("127.0.0.1");
  3301. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3302. auto se = detail::scope_exit([&] {
  3303. svr.stop();
  3304. thread.join();
  3305. ASSERT_FALSE(svr.is_running());
  3306. });
  3307. svr.wait_until_ready();
  3308. Client cli(host, port);
  3309. #pragma GCC diagnostic push
  3310. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3311. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3312. #pragma GCC diagnostic pop
  3313. auto res = cli.Get("/hi");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3317. }
  3318. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3319. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3320. Server svr;
  3321. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3322. res.set_content("Hello World!", "text/plain");
  3323. });
  3324. auto port = svr.bind_to_any_port("127.0.0.1");
  3325. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3326. auto se = detail::scope_exit([&] {
  3327. svr.stop();
  3328. thread.join();
  3329. ASSERT_FALSE(svr.is_running());
  3330. });
  3331. svr.wait_until_ready();
  3332. Client cli("127.0.0.1", port);
  3333. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3334. cli.set_connection_timeout(1);
  3335. auto res = cli.Get("/hi");
  3336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3337. EXPECT_EQ(StatusCode::OK_200, res->status);
  3338. }
  3339. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3340. auto host = "httpbingo.org";
  3341. auto path = std::string{"/absolute-redirect/3"};
  3342. #ifdef CPPHTTPLIB_SSL_ENABLED
  3343. SSLClient cli(host);
  3344. #else
  3345. Client cli(host);
  3346. #endif
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get(path);
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. }
  3352. TEST(RedirectTest, Redirect_Online) {
  3353. auto host = "httpbingo.org";
  3354. auto path = std::string{"/redirect/3"};
  3355. #ifdef CPPHTTPLIB_SSL_ENABLED
  3356. SSLClient cli(host);
  3357. #else
  3358. Client cli(host);
  3359. #endif
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get(path);
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. }
  3365. TEST(RelativeRedirectTest, Redirect_Online) {
  3366. auto host = "httpbingo.org";
  3367. auto path = std::string{"/relative-redirect/3"};
  3368. #ifdef CPPHTTPLIB_SSL_ENABLED
  3369. SSLClient cli(host);
  3370. #else
  3371. Client cli(host);
  3372. #endif
  3373. cli.set_follow_location(true);
  3374. auto res = cli.Get(path);
  3375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3376. EXPECT_EQ(StatusCode::OK_200, res->status);
  3377. }
  3378. TEST(TooManyRedirectTest, Redirect_Online) {
  3379. auto host = "httpbingo.org";
  3380. auto path = std::string{"/redirect/21"};
  3381. #ifdef CPPHTTPLIB_SSL_ENABLED
  3382. SSLClient cli(host);
  3383. #else
  3384. Client cli(host);
  3385. #endif
  3386. cli.set_follow_location(true);
  3387. auto res = cli.Get(path);
  3388. ASSERT_TRUE(!res);
  3389. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3390. }
  3391. #ifdef CPPHTTPLIB_SSL_ENABLED
  3392. TEST(YahooRedirectTest, Redirect_Online) {
  3393. Client cli("yahoo.com");
  3394. auto res = cli.Get("/");
  3395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3396. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3397. cli.set_follow_location(true);
  3398. res = cli.Get("/");
  3399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3400. EXPECT_EQ(StatusCode::OK_200, res->status);
  3401. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3402. }
  3403. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3404. #define REDIR_HOST "httpbingo.org"
  3405. #define REDIR_PATH "/redirect-to"
  3406. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3407. SSLClient cli(REDIR_HOST);
  3408. cli.set_follow_location(true);
  3409. auto res =
  3410. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. }
  3414. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3415. SSLClient cli(REDIR_HOST);
  3416. cli.set_follow_location(true);
  3417. Params params;
  3418. params.emplace("url", "http://example.com");
  3419. params.emplace("status_code", "302");
  3420. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3422. EXPECT_EQ(StatusCode::OK_200, res->status);
  3423. }
  3424. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3425. SSLClient cli(REDIR_HOST);
  3426. cli.set_follow_location(true);
  3427. Params params;
  3428. params.emplace("url", "http://example.com");
  3429. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. }
  3433. TEST(UrlWithSpace, Redirect_Online) {
  3434. SSLClient cli("edge.forgecdn.net");
  3435. cli.set_follow_location(true);
  3436. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::OK_200, res->status);
  3439. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3440. }
  3441. #endif
  3442. #if !defined(_WIN32) && !defined(_WIN64)
  3443. TEST(ReceiveSignals, Signal) {
  3444. auto setupSignalHandlers = []() {
  3445. struct sigaction act;
  3446. sigemptyset(&act.sa_mask);
  3447. act.sa_flags = SA_SIGINFO;
  3448. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3449. switch (sig) {
  3450. case SIGINT:
  3451. default: break;
  3452. }
  3453. };
  3454. ::sigaction(SIGINT, &act, nullptr);
  3455. };
  3456. Server svr;
  3457. int port = 0;
  3458. auto thread = std::thread([&]() {
  3459. setupSignalHandlers();
  3460. port = svr.bind_to_any_port(HOST);
  3461. svr.listen_after_bind();
  3462. });
  3463. auto se = detail::scope_exit([&] {
  3464. svr.stop();
  3465. thread.join();
  3466. ASSERT_FALSE(svr.is_running());
  3467. });
  3468. svr.wait_until_ready();
  3469. ASSERT_TRUE(svr.is_running());
  3470. pthread_kill(thread.native_handle(), SIGINT);
  3471. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3472. ASSERT_TRUE(svr.is_running());
  3473. }
  3474. #endif
  3475. TEST(RedirectToDifferentPort, Redirect) {
  3476. Server svr1;
  3477. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3478. res.set_content("Hello World!", "text/plain");
  3479. });
  3480. int svr1_port = 0;
  3481. auto thread1 = std::thread([&]() {
  3482. svr1_port = svr1.bind_to_any_port(HOST);
  3483. svr1.listen_after_bind();
  3484. });
  3485. Server svr2;
  3486. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3487. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3488. });
  3489. int svr2_port = 0;
  3490. auto thread2 = std::thread([&]() {
  3491. svr2_port = svr2.bind_to_any_port(HOST);
  3492. svr2.listen_after_bind();
  3493. });
  3494. auto se = detail::scope_exit([&] {
  3495. svr2.stop();
  3496. thread2.join();
  3497. svr1.stop();
  3498. thread1.join();
  3499. ASSERT_FALSE(svr2.is_running());
  3500. ASSERT_FALSE(svr1.is_running());
  3501. });
  3502. svr1.wait_until_ready();
  3503. svr2.wait_until_ready();
  3504. Client cli("localhost", svr2_port);
  3505. cli.set_follow_location(true);
  3506. auto res = cli.Get("/2");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("Hello World!", res->body);
  3510. }
  3511. // GET /redir on one server redirects to /target on another port, so the
  3512. // client follows it with a new client.
  3513. static Result
  3514. GetThroughRedirectToDifferentPort(Server::Handler target,
  3515. const std::function<void(Client &)> &setup,
  3516. const Headers &headers = Headers()) {
  3517. Server target_svr;
  3518. target_svr.Get("/target", target);
  3519. int target_port = 0;
  3520. auto target_thread = std::thread([&]() {
  3521. target_port = target_svr.bind_to_any_port(HOST);
  3522. target_svr.listen_after_bind();
  3523. });
  3524. Server origin_svr;
  3525. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3526. res.set_redirect(
  3527. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3528. });
  3529. int origin_port = 0;
  3530. auto origin_thread = std::thread([&]() {
  3531. origin_port = origin_svr.bind_to_any_port(HOST);
  3532. origin_svr.listen_after_bind();
  3533. });
  3534. auto se = detail::scope_exit([&] {
  3535. origin_svr.stop();
  3536. origin_thread.join();
  3537. target_svr.stop();
  3538. target_thread.join();
  3539. });
  3540. target_svr.wait_until_ready();
  3541. origin_svr.wait_until_ready();
  3542. Client cli("localhost", origin_port);
  3543. cli.set_follow_location(true);
  3544. setup(cli);
  3545. return cli.Get("/redir", headers);
  3546. }
  3547. static void
  3548. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3549. std::string captured_authorization;
  3550. auto result = GetThroughRedirectToDifferentPort(
  3551. [&](const Request &req, Response &res) {
  3552. captured_authorization = req.get_header_value("Authorization");
  3553. res.set_content("OK", "text/plain");
  3554. },
  3555. set_auth);
  3556. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3557. EXPECT_EQ(StatusCode::OK_200, result->status);
  3558. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3559. EXPECT_TRUE(captured_authorization.empty());
  3560. }
  3561. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3562. TestDoNotForwardCredentialsOnRedirect(
  3563. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3564. }
  3565. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3566. TestDoNotForwardCredentialsOnRedirect(
  3567. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3568. }
  3569. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3570. std::string captured_cookie;
  3571. auto result = GetThroughRedirectToDifferentPort(
  3572. [&](const Request &req, Response &res) {
  3573. captured_cookie = req.get_header_value("Cookie");
  3574. res.set_content("OK", "text/plain");
  3575. },
  3576. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3577. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3578. EXPECT_EQ(StatusCode::OK_200, result->status);
  3579. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3580. EXPECT_TRUE(captured_cookie.empty());
  3581. }
  3582. TEST(RedirectToSamePort, ForwardCookie) {
  3583. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3584. // header so that ordinary session flows keep working.
  3585. Server svr;
  3586. std::string captured_cookie;
  3587. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3588. res.set_redirect("/target", 302);
  3589. });
  3590. svr.Get("/target", [&](const Request &req, Response &res) {
  3591. captured_cookie = req.get_header_value("Cookie");
  3592. res.set_content("OK", "text/plain");
  3593. });
  3594. auto port = svr.bind_to_any_port(HOST);
  3595. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3596. auto se = detail::scope_exit([&] {
  3597. svr.stop();
  3598. thread.join();
  3599. ASSERT_FALSE(svr.is_running());
  3600. });
  3601. svr.wait_until_ready();
  3602. Client cli(HOST, port);
  3603. cli.set_follow_location(true);
  3604. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3605. auto res = cli.Get("/redir", headers);
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3609. }
  3610. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3611. std::string authorization;
  3612. std::string trace_id;
  3613. auto result = GetThroughRedirectToDifferentPort(
  3614. [&](const Request &req, Response &res) {
  3615. authorization = req.get_header_value("Authorization");
  3616. trace_id = req.get_header_value("X-Trace-Id");
  3617. res.set_content("OK", "text/plain");
  3618. },
  3619. [](Client &cli) {
  3620. cli.set_default_headers(
  3621. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3622. });
  3623. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3624. EXPECT_EQ(StatusCode::OK_200, result->status);
  3625. // Like a header given with the request, a default one goes along unless it
  3626. // carries credentials (RFC 9110 15.4).
  3627. EXPECT_TRUE(authorization.empty());
  3628. EXPECT_EQ("42", trace_id);
  3629. }
  3630. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3631. auto result = GetThroughRedirectToDifferentPort(
  3632. [](const Request &, Response &res) {
  3633. res.set_content(std::string(2048, 'x'), "text/plain");
  3634. },
  3635. [](Client &cli) { cli.set_payload_max_length(1024); });
  3636. EXPECT_FALSE(result);
  3637. }
  3638. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3639. auto result = GetThroughRedirectToDifferentPort(
  3640. [](const Request &req, Response &res) {
  3641. // Answer after a second, or once the client gives up.
  3642. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3644. }
  3645. res.set_content("late", "text/plain");
  3646. },
  3647. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3648. ASSERT_FALSE(result);
  3649. EXPECT_EQ(Error::Read, result.error());
  3650. }
  3651. #ifdef CPPHTTPLIB_SSL_ENABLED
  3652. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3653. auto result = GetThroughRedirectToDifferentPort(
  3654. [](const Request &, Response &res) {
  3655. res.status = StatusCode::Unauthorized_401;
  3656. res.set_header("WWW-Authenticate",
  3657. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3658. },
  3659. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3660. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3661. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3662. }
  3663. #endif
  3664. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3665. Server svr;
  3666. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3667. // Port number that overflows int — should not crash
  3668. res.set_redirect("http://localhost:99999999999999999999/target");
  3669. });
  3670. auto port = svr.bind_to_any_port(HOST);
  3671. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3672. auto se = detail::scope_exit([&] {
  3673. svr.stop();
  3674. thread.join();
  3675. ASSERT_FALSE(svr.is_running());
  3676. });
  3677. svr.wait_until_ready();
  3678. Client cli(HOST, port);
  3679. cli.set_follow_location(true);
  3680. auto res = cli.Get("/redir");
  3681. // Should fail gracefully, not crash (no valid response due to bad port)
  3682. EXPECT_FALSE(res);
  3683. }
  3684. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3685. Server svr;
  3686. auto port = svr.bind_to_any_port(HOST);
  3687. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3688. // The server's own port followed by junk must not be followed
  3689. res.set_redirect("http://" + std::string(HOST) + ":" +
  3690. std::to_string(port) + "junk/target");
  3691. });
  3692. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3693. res.set_content("target", "text/plain");
  3694. });
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. Client cli(HOST, port);
  3703. cli.set_follow_location(true);
  3704. auto res = cli.Get("/redir");
  3705. EXPECT_FALSE(res);
  3706. }
  3707. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3708. Server svr;
  3709. std::atomic<bool> followed{false};
  3710. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3711. res.status = StatusCode::NotModified_304;
  3712. res.set_header("Location", "/target");
  3713. });
  3714. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3715. res.status = StatusCode::UseProxy_305;
  3716. res.set_header("Location", "/target");
  3717. });
  3718. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3719. followed = true;
  3720. res.set_content("target", "text/plain");
  3721. });
  3722. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. th.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. Client cli("localhost", PORT);
  3730. cli.set_follow_location(true);
  3731. auto res = cli.Get("/304");
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3734. res = cli.Get("/305");
  3735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3736. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3737. EXPECT_FALSE(followed);
  3738. }
  3739. TEST(RedirectFromPageWithContent, Redirect) {
  3740. Server svr;
  3741. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3742. res.set_content("___", "text/plain");
  3743. res.set_redirect("/2");
  3744. });
  3745. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3746. res.set_content("Hello World!", "text/plain");
  3747. });
  3748. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. th.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli("localhost", PORT);
  3757. cli.set_follow_location(true);
  3758. std::string body;
  3759. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3760. body.append(data, data_length);
  3761. return true;
  3762. });
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. EXPECT_EQ("Hello World!", body);
  3766. }
  3767. {
  3768. Client cli("localhost", PORT);
  3769. std::string body;
  3770. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3771. body.append(data, data_length);
  3772. return true;
  3773. });
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::Found_302, res->status);
  3776. EXPECT_EQ("___", body);
  3777. }
  3778. }
  3779. // A server can close the connection after a request with "Connection: close"
  3780. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3781. // redirected request must go out on a new connection.
  3782. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3783. #ifndef _WIN32
  3784. signal(SIGPIPE, SIG_IGN);
  3785. #endif
  3786. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3787. default_socket_options(srv);
  3788. sockaddr_in addr{};
  3789. addr.sin_family = AF_INET;
  3790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3792. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3793. ASSERT_EQ(0, ::listen(srv, 2));
  3794. auto send_text = [](socket_t sock, const std::string &text) {
  3795. ::send(sock,
  3796. #ifdef _WIN32
  3797. static_cast<const char *>(text.c_str()),
  3798. static_cast<int>(text.size()),
  3799. #else
  3800. text.c_str(), text.size(),
  3801. #endif
  3802. 0);
  3803. };
  3804. auto reused = false;
  3805. auto server_thread = std::thread([&] {
  3806. char buf[4096];
  3807. auto first = ::accept(srv, nullptr, nullptr);
  3808. if (first == INVALID_SOCKET) { return; }
  3809. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3810. ::recv(first, buf, sizeof(buf), 0);
  3811. send_text(
  3812. first,
  3813. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3814. auto next = first;
  3815. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3816. reused = true;
  3817. } else {
  3818. detail::close_socket(first);
  3819. next = ::accept(srv, nullptr, nullptr);
  3820. if (next == INVALID_SOCKET) { return; }
  3821. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3822. ::recv(next, buf, sizeof(buf), 0);
  3823. }
  3824. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3825. "Connection: close\r\n\r\nok");
  3826. detail::close_socket(next);
  3827. });
  3828. Client cli("127.0.0.1", PORT + 2);
  3829. cli.set_follow_location(true);
  3830. cli.set_read_timeout(5, 0);
  3831. auto res = cli.Get("/1");
  3832. server_thread.join();
  3833. detail::close_socket(srv);
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ("ok", res->body);
  3837. EXPECT_FALSE(reused);
  3838. }
  3839. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3840. Server svr;
  3841. auto port_str = std::to_string(PORT);
  3842. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3843. auto expected_host = "[::1]:" + port_str;
  3844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3845. res.set_content("___", "text/plain");
  3846. // res.set_redirect("/2");
  3847. res.set_redirect(redirect_url);
  3848. });
  3849. svr.Get("/2", [&](const Request &req, Response &res) {
  3850. auto host_header = req.headers.find("Host");
  3851. ASSERT_TRUE(host_header != req.headers.end());
  3852. EXPECT_EQ(expected_host, host_header->second);
  3853. res.set_content("Hello World!", "text/plain");
  3854. });
  3855. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3856. auto se = detail::scope_exit([&] {
  3857. svr.stop();
  3858. th.join();
  3859. ASSERT_FALSE(svr.is_running());
  3860. });
  3861. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3862. // actually starts anything, so the condition !svr.is_running() will
  3863. // always remain true, and the loop never stops.
  3864. // This basically counts how many milliseconds have passed since the
  3865. // call to svr.listen(), and if after 5 seconds nothing started yet
  3866. // aborts the test.
  3867. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3868. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3869. ASSERT_LT(milliseconds, 5000U);
  3870. }
  3871. {
  3872. Client cli("::1", PORT);
  3873. cli.set_follow_location(true);
  3874. std::string body;
  3875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3876. body.append(data, data_length);
  3877. return true;
  3878. });
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ(StatusCode::OK_200, res->status);
  3881. EXPECT_EQ("Hello World!", body);
  3882. }
  3883. {
  3884. Client cli("::1", PORT);
  3885. std::string body;
  3886. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3887. body.append(data, data_length);
  3888. return true;
  3889. });
  3890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3891. EXPECT_EQ(StatusCode::Found_302, res->status);
  3892. EXPECT_EQ("___", body);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3896. Server svr;
  3897. svr.Get("/foo", [](const Request &req, Response &res) {
  3898. auto a = req.params.find("a");
  3899. if (a != req.params.end()) {
  3900. res.set_content((*a).second, "text/plain");
  3901. res.status = StatusCode::OK_200;
  3902. } else {
  3903. res.status = StatusCode::BadRequest_400;
  3904. }
  3905. });
  3906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3907. auto se = detail::scope_exit([&] {
  3908. svr.stop();
  3909. thread.join();
  3910. ASSERT_FALSE(svr.is_running());
  3911. });
  3912. svr.wait_until_ready();
  3913. {
  3914. Client cli(HOST, PORT);
  3915. cli.set_path_encode(false);
  3916. auto res = cli.Get("/foo?a=explicitly+encoded");
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ(StatusCode::OK_200, res->status);
  3919. // This expects it back with a space, as the `+` won't have been
  3920. // url-encoded, and server-side the params get decoded turning `+`
  3921. // into spaces.
  3922. EXPECT_EQ("explicitly encoded", res->body);
  3923. }
  3924. }
  3925. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3926. // When path encoding is disabled the client must transmit the supplied
  3927. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3928. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3929. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3930. // than a space (0x20). Assert on the raw wire target to catch this.
  3931. Server svr;
  3932. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3933. svr.Get("/foo", [&](const Request &req, Response &res) {
  3934. EXPECT_EQ(expected_target, req.target);
  3935. res.status = StatusCode::OK_200;
  3936. });
  3937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3938. auto se = detail::scope_exit([&] {
  3939. svr.stop();
  3940. thread.join();
  3941. ASSERT_FALSE(svr.is_running());
  3942. });
  3943. svr.wait_until_ready();
  3944. {
  3945. Client cli(HOST, PORT);
  3946. cli.set_path_encode(false);
  3947. auto res = cli.Get(expected_target.c_str());
  3948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3949. EXPECT_EQ(StatusCode::OK_200, res->status);
  3950. }
  3951. }
  3952. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3953. // `open_stream()` used to skip the path encoding that the buffered send
  3954. // path applies, so the same `path` produced different bytes in the request
  3955. // line depending on which API was used. Assert the two agree.
  3956. Server svr;
  3957. std::string target;
  3958. svr.Get(".*", [&](const Request &req, Response &res) {
  3959. target = req.target;
  3960. res.status = StatusCode::OK_200;
  3961. });
  3962. auto port = svr.bind_to_any_port(HOST);
  3963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3964. auto se = detail::scope_exit([&] {
  3965. svr.stop();
  3966. thread.join();
  3967. ASSERT_FALSE(svr.is_running());
  3968. });
  3969. svr.wait_until_ready();
  3970. struct {
  3971. const char *path;
  3972. const char *expected;
  3973. } cases[] = {
  3974. {"/a b?x=1", "/a%20b?x=1"},
  3975. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3976. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3977. };
  3978. for (const auto &c : cases) {
  3979. Client cli(HOST, port);
  3980. target.clear();
  3981. auto res = cli.Get(c.path);
  3982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3983. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3984. auto buffered_target = target;
  3985. target.clear();
  3986. auto handle = cli.open_stream("GET", c.path);
  3987. EXPECT_TRUE(handle.is_valid())
  3988. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3989. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3990. }
  3991. }
  3992. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3993. // The `set_path_encode(false)` contract — transmit the supplied target
  3994. // verbatim — must hold for the streaming API too.
  3995. Server svr;
  3996. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3997. std::string target;
  3998. svr.Get("/foo", [&](const Request &req, Response &res) {
  3999. target = req.target;
  4000. res.status = StatusCode::OK_200;
  4001. });
  4002. auto port = svr.bind_to_any_port(HOST);
  4003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4004. auto se = detail::scope_exit([&] {
  4005. svr.stop();
  4006. thread.join();
  4007. ASSERT_FALSE(svr.is_running());
  4008. });
  4009. svr.wait_until_ready();
  4010. {
  4011. Client cli(HOST, port);
  4012. cli.set_path_encode(false);
  4013. auto handle = cli.open_stream("GET", expected_target);
  4014. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4015. EXPECT_EQ(expected_target, target);
  4016. }
  4017. }
  4018. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4019. // With path encoding enabled a CR/LF in the target is percent-encoded
  4020. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4021. // write_request_line still backstops `set_path_encode(false)`, which is
  4022. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4023. Server svr;
  4024. // Captured before routing: the decoded path contains a newline, which a
  4025. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4026. std::string target;
  4027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4028. target = req.target;
  4029. res.status = StatusCode::OK_200;
  4030. return Server::HandlerResponse::Handled;
  4031. });
  4032. auto port = svr.bind_to_any_port(HOST);
  4033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4034. auto se = detail::scope_exit([&] {
  4035. svr.stop();
  4036. thread.join();
  4037. ASSERT_FALSE(svr.is_running());
  4038. });
  4039. svr.wait_until_ready();
  4040. {
  4041. Client cli(HOST, port);
  4042. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4043. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4044. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4045. }
  4046. }
  4047. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4048. // Every control character is percent-encoded, not just CR/LF, so the target
  4049. // passes the request-target check in write_request_line.
  4050. Server svr;
  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 res = cli.Get("/a\tb\x1b\x7f");
  4068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4069. EXPECT_EQ("/a%09b%1B%7F", target);
  4070. }
  4071. }
  4072. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4073. // Nothing may reach the wire: a raw CR/LF target would split the request
  4074. // line and inject headers.
  4075. Server svr;
  4076. // Pre-routing so that "not called" means nothing reached the server at all,
  4077. // rather than merely failing to match a handler pattern.
  4078. auto handler_called = false;
  4079. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4080. handler_called = true;
  4081. res.status = StatusCode::OK_200;
  4082. return Server::HandlerResponse::Handled;
  4083. });
  4084. auto port = svr.bind_to_any_port(HOST);
  4085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4086. auto se = detail::scope_exit([&] {
  4087. svr.stop();
  4088. thread.join();
  4089. ASSERT_FALSE(svr.is_running());
  4090. });
  4091. svr.wait_until_ready();
  4092. {
  4093. Client cli(HOST, port);
  4094. cli.set_path_encode(false);
  4095. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4096. EXPECT_FALSE(handle.is_valid());
  4097. EXPECT_EQ(Error::Write, handle.error);
  4098. EXPECT_FALSE(handler_called);
  4099. }
  4100. }
  4101. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4102. // Which of the two branches runs is decided by whether the query component
  4103. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4104. // an empty query and must still fall back to building one from
  4105. // `req.params`, while a non-empty query must win over `req.params`.
  4106. Server svr;
  4107. std::string target;
  4108. svr.Get("/foo", [&](const Request &req, Response &res) {
  4109. target = req.target;
  4110. res.status = StatusCode::OK_200;
  4111. });
  4112. auto port = svr.bind_to_any_port(HOST);
  4113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. thread.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. {
  4121. // Trailing `?` -> empty query component -> `req.params` is used.
  4122. Client cli(HOST, port);
  4123. Request req;
  4124. req.method = "GET";
  4125. req.path = "/foo?";
  4126. req.params.emplace("a", "1");
  4127. target.clear();
  4128. auto res = cli.send(req);
  4129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4130. EXPECT_EQ("/foo?a=1", target);
  4131. }
  4132. {
  4133. // Non-empty query in `req.path` -> `req.params` is not appended.
  4134. Client cli(HOST, port);
  4135. Request req;
  4136. req.method = "GET";
  4137. req.path = "/foo?b=2";
  4138. req.params.emplace("a", "1");
  4139. target.clear();
  4140. auto res = cli.send(req);
  4141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4142. EXPECT_EQ("/foo?b=2", target);
  4143. }
  4144. }
  4145. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4146. Server svr;
  4147. svr.Get("/", [](const Request &req, Response &) {
  4148. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4149. });
  4150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4151. auto se = detail::scope_exit([&] {
  4152. svr.stop();
  4153. thread.join();
  4154. ASSERT_FALSE(svr.is_running());
  4155. });
  4156. svr.wait_until_ready();
  4157. {
  4158. Client cli(HOST, PORT);
  4159. cli.set_path_encode(false);
  4160. auto res = cli.Get("/?something=%0A");
  4161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. }
  4164. }
  4165. TEST(BindServerTest, BindDualStack) {
  4166. Server svr;
  4167. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4168. res.set_content("Hello World!", "text/plain");
  4169. });
  4170. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4171. auto se = detail::scope_exit([&] {
  4172. svr.stop();
  4173. thread.join();
  4174. ASSERT_FALSE(svr.is_running());
  4175. });
  4176. svr.wait_until_ready();
  4177. {
  4178. Client cli("127.0.0.1", PORT);
  4179. auto res = cli.Get("/1");
  4180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4181. EXPECT_EQ(StatusCode::OK_200, res->status);
  4182. EXPECT_EQ("Hello World!", res->body);
  4183. }
  4184. {
  4185. Client cli("::1", PORT);
  4186. auto res = cli.Get("/1");
  4187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("Hello World!", res->body);
  4190. }
  4191. }
  4192. TEST(BindServerTest, BindAndListenSeparately) {
  4193. Server svr;
  4194. int port = svr.bind_to_any_port("0.0.0.0");
  4195. ASSERT_TRUE(svr.is_valid());
  4196. ASSERT_TRUE(port > 0);
  4197. svr.stop();
  4198. }
  4199. // Reports whether anything is still listening on a loopback port. A plain
  4200. // connect() is used instead of a Client request because a socket left bound by
  4201. // mistake accepts the connection into its backlog and never answers, which
  4202. // would hang the test instead of failing it.
  4203. static bool is_loopback_port_accepting(int port) {
  4204. sockaddr_in addr{};
  4205. addr.sin_family = AF_INET;
  4206. addr.sin_port = htons(static_cast<uint16_t>(port));
  4207. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4208. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4209. EXPECT_NE(sock, INVALID_SOCKET);
  4210. if (sock == INVALID_SOCKET) { return false; }
  4211. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4212. static_cast<socklen_t>(sizeof(addr)));
  4213. detail::close_socket(sock);
  4214. return ret == 0;
  4215. }
  4216. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4217. Server svr;
  4218. auto port = svr.bind_to_any_port("127.0.0.1");
  4219. ASSERT_TRUE(port > 0);
  4220. svr.stop();
  4221. // bind_to_any_port() already called listen(2), so until stop() closed the
  4222. // descriptor the port kept accepting connections into the backlog. ASSERT
  4223. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4224. // below blocks forever in the accept loop.
  4225. ASSERT_FALSE(is_loopback_port_accepting(port));
  4226. // Nothing is left to accept on, so listen_after_bind() must report failure
  4227. // instead of returning success without ever serving.
  4228. EXPECT_FALSE(svr.listen_after_bind());
  4229. // The failed listen marks the server decommissioned, so a waiter returns
  4230. // instead of spinning forever.
  4231. svr.wait_until_ready();
  4232. }
  4233. #ifdef CPPHTTPLIB_SSL_ENABLED
  4234. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4236. CLIENT_CA_CERT_DIR);
  4237. int port = svr.bind_to_any_port("0.0.0.0");
  4238. ASSERT_TRUE(svr.is_valid());
  4239. ASSERT_TRUE(port > 0);
  4240. svr.stop();
  4241. }
  4242. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4243. // or a rejected CustomRoute() registration would not stop the server binding.
  4244. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4246. CLIENT_CA_CERT_DIR);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4249. EXPECT_FALSE(svr.is_valid());
  4250. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4251. }
  4252. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4253. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4254. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4255. int port = svr.bind_to_any_port("0.0.0.0");
  4256. ASSERT_TRUE(svr.is_valid());
  4257. ASSERT_TRUE(port > 0);
  4258. svr.stop();
  4259. }
  4260. TEST(BindServerTest, UpdateCertsPem) {
  4261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4262. int port = svr.bind_to_any_port("0.0.0.0");
  4263. ASSERT_TRUE(svr.is_valid());
  4264. ASSERT_TRUE(port > 0);
  4265. // Read PEM files
  4266. std::string cert_pem, key_pem, ca_pem;
  4267. read_file(SERVER_CERT_FILE, cert_pem);
  4268. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4269. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4270. // Update server certificates using PEM API
  4271. ASSERT_TRUE(
  4272. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4273. ASSERT_TRUE(svr.is_valid());
  4274. svr.stop();
  4275. }
  4276. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4277. // Start server with client CA (enables client auth)
  4278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4279. ASSERT_TRUE(svr.is_valid());
  4280. bool handler_called = false;
  4281. svr.Get("/test", [&](const Request &req, Response &res) {
  4282. handler_called = true;
  4283. // Verify client certificate is present
  4284. auto cert = req.peer_cert();
  4285. EXPECT_TRUE(static_cast<bool>(cert));
  4286. res.set_content("ok", "text/plain");
  4287. });
  4288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. t.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. // Read PEM files
  4296. std::string cert_pem, key_pem, ca_pem;
  4297. read_file(SERVER_CERT_FILE, cert_pem);
  4298. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4299. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4300. // Update server certificates and client CA using PEM API while server running
  4301. ASSERT_TRUE(
  4302. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4303. // Connect with client certificate
  4304. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4305. cli.enable_server_certificate_verification(false);
  4306. cli.set_connection_timeout(30);
  4307. auto res = cli.Get("/test");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. ASSERT_EQ(StatusCode::OK_200, res->status);
  4310. ASSERT_TRUE(handler_called);
  4311. EXPECT_EQ("ok", res->body);
  4312. }
  4313. // Puts a CA that did not sign the client's certificate in the old one's place.
  4314. static bool replace_client_ca(SSLServer &svr) {
  4315. std::string cert_pem, key_pem, ca_pem;
  4316. read_file(SERVER_CERT_FILE, cert_pem);
  4317. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4318. read_file(SERVER_CERT2_FILE, ca_pem);
  4319. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4320. ca_pem.c_str());
  4321. }
  4322. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4324. ASSERT_TRUE(svr.is_valid());
  4325. svr.Get("/test", [](const Request &, Response &res) {
  4326. res.set_content("ok", "text/plain");
  4327. });
  4328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. t.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. auto get = [] {
  4336. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4337. cli.enable_server_certificate_verification(false);
  4338. return cli.Get("/test");
  4339. };
  4340. ASSERT_TRUE(get());
  4341. ASSERT_TRUE(replace_client_ca(svr));
  4342. EXPECT_FALSE(get());
  4343. }
  4344. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4345. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4347. ASSERT_TRUE(svr.is_valid());
  4348. tls::set_verify_callback(svr.tls_context(),
  4349. [](const tls::VerifyContext &) -> bool {
  4350. throw std::runtime_error("verify");
  4351. });
  4352. svr.Get("/test", [](const Request &, Response &res) {
  4353. res.set_content("ok", "text/plain");
  4354. });
  4355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. t.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. auto get = [] {
  4363. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4364. cli.enable_server_certificate_verification(false);
  4365. return cli.Get("/test");
  4366. };
  4367. EXPECT_FALSE(get());
  4368. // The handshake is over, so an update does not wait for it.
  4369. std::string cert_pem, key_pem;
  4370. read_file(SERVER_CERT_FILE, cert_pem);
  4371. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4372. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4373. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4374. return v.preverify_ok;
  4375. });
  4376. auto res = get();
  4377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4378. EXPECT_EQ("ok", res->body);
  4379. }
  4380. #endif
  4381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4382. // Sends each request over a new connection with a client certificate,
  4383. // resuming the session of the one before when there is one.
  4384. class ResumingClient {
  4385. public:
  4386. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4387. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4388. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4389. SSL_FILETYPE_PEM);
  4390. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4391. // callback, not through SSL_get1_session().
  4392. SSL_CTX_set_app_data(ctx_, this);
  4393. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4394. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4395. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4396. auto self = static_cast<ResumingClient *>(
  4397. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4398. SSL_SESSION_free(self->session_);
  4399. self->session_ = session;
  4400. return 1; // Keeps the reference
  4401. });
  4402. }
  4403. ~ResumingClient() {
  4404. SSL_SESSION_free(session_);
  4405. SSL_CTX_free(ctx_);
  4406. }
  4407. // Tells whether the request was answered.
  4408. bool get() {
  4409. auto error = Error::Success;
  4410. auto sock = detail::create_client_socket(
  4411. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4412. /*connection_timeout_sec=*/5, 0,
  4413. /*read_timeout_sec=*/5, 0,
  4414. /*write_timeout_sec=*/5, 0, std::string(), error);
  4415. if (sock == INVALID_SOCKET) { return false; }
  4416. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4417. auto ssl = SSL_new(ctx_);
  4418. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4419. SSL_set_fd(ssl, static_cast<int>(sock));
  4420. if (session_) { SSL_set_session(ssl, session_); }
  4421. if (SSL_connect(ssl) != 1) { return false; }
  4422. reused_ = SSL_session_reused(ssl) == 1;
  4423. // Reading the response also takes in a TLS 1.3 session ticket.
  4424. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4425. "Connection: close\r\n\r\n";
  4426. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4427. std::string res;
  4428. char buf[256];
  4429. int n;
  4430. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4431. res.append(buf, static_cast<size_t>(n));
  4432. }
  4433. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4434. SSL_shutdown(ssl);
  4435. return res.find("200 OK") != std::string::npos;
  4436. }
  4437. // Whether the last connection resumed a session
  4438. bool reused() const { return reused_; }
  4439. private:
  4440. SSL_CTX *ctx_;
  4441. SSL_SESSION *session_ = nullptr;
  4442. bool reused_ = false;
  4443. };
  4444. // A client that resumes its session gets through, but not once the client CA
  4445. // has changed, as a resumed session does not show the certificate again.
  4446. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4448. ASSERT_TRUE(svr.is_valid());
  4449. svr.Get("/test", [](const Request &, Response &res) {
  4450. res.set_content("ok", "text/plain");
  4451. });
  4452. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4453. auto se = detail::scope_exit([&] {
  4454. svr.stop();
  4455. t.join();
  4456. ASSERT_FALSE(svr.is_running());
  4457. });
  4458. svr.wait_until_ready();
  4459. ResumingClient cli;
  4460. ASSERT_TRUE(cli.get());
  4461. ASSERT_TRUE(cli.get());
  4462. EXPECT_TRUE(cli.reused());
  4463. ASSERT_TRUE(replace_client_ca(svr));
  4464. EXPECT_FALSE(cli.get());
  4465. }
  4466. // A resumed session does not show the certificate again, so the server does
  4467. // not resume one with a verify callback to run on it.
  4468. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4470. ASSERT_TRUE(svr.is_valid());
  4471. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4472. return v.preverify_ok;
  4473. });
  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_FALSE(cli.reused());
  4488. }
  4489. #endif
  4490. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4491. // wolfSSL shares its session cache between contexts, so a resumed session
  4492. // could carry a client certificate checked against another server's CA, or
  4493. // against a client CA since replaced.
  4494. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4496. ASSERT_TRUE(svr.is_valid());
  4497. // Trusts a CA that did not sign the client's certificate.
  4498. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4499. ASSERT_TRUE(other.is_valid());
  4500. for (auto s : {&svr, &other}) {
  4501. s->Get("/test", [](const Request &, Response &res) {
  4502. res.set_content("ok", "text/plain");
  4503. });
  4504. }
  4505. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4506. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4507. auto se = detail::scope_exit([&] {
  4508. other.stop();
  4509. svr.stop();
  4510. t2.join();
  4511. t.join();
  4512. });
  4513. svr.wait_until_ready();
  4514. other.wait_until_ready();
  4515. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4516. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4517. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4518. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4519. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4520. ASSERT_EQ(WOLFSSL_SUCCESS,
  4521. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4522. WOLFSSL_FILETYPE_PEM));
  4523. WOLFSSL_SESSION *session = nullptr;
  4524. auto session_se = detail::scope_exit([&] {
  4525. if (session) { wolfSSL_SESSION_free(session); }
  4526. });
  4527. // A request over a new connection, resuming `session` when there is one and
  4528. // keeping the connection's own in its place. Tells whether it was answered.
  4529. auto get = [&](int port) {
  4530. auto error = Error::Success;
  4531. auto sock = detail::create_client_socket(
  4532. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4533. /*connection_timeout_sec=*/5, 0,
  4534. /*read_timeout_sec=*/5, 0,
  4535. /*write_timeout_sec=*/5, 0, std::string(), error);
  4536. if (sock == INVALID_SOCKET) { return false; }
  4537. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4538. auto ssl = wolfSSL_new(ctx);
  4539. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4540. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4541. if (session) { wolfSSL_set_session(ssl, session); }
  4542. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4543. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4544. "Connection: close\r\n\r\n";
  4545. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4546. std::string res;
  4547. char buf[256];
  4548. int n;
  4549. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4550. res.append(buf, static_cast<size_t>(n));
  4551. }
  4552. wolfSSL_shutdown(ssl);
  4553. if (session) { wolfSSL_SESSION_free(session); }
  4554. session = wolfSSL_get1_session(ssl);
  4555. return res.find("200 OK") != std::string::npos;
  4556. };
  4557. ASSERT_TRUE(get(PORT));
  4558. EXPECT_FALSE(get(PORT + 1));
  4559. ASSERT_TRUE(get(PORT));
  4560. ASSERT_TRUE(replace_client_ca(svr));
  4561. EXPECT_FALSE(get(PORT));
  4562. }
  4563. #endif
  4564. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4566. ASSERT_TRUE(svr.is_valid());
  4567. svr.Get("/test", [](const Request &, Response &res) {
  4568. res.set_content("ok", "text/plain");
  4569. });
  4570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4571. auto se = detail::scope_exit([&] {
  4572. svr.stop();
  4573. t.join();
  4574. ASSERT_FALSE(svr.is_running());
  4575. });
  4576. svr.wait_until_ready();
  4577. // A connection that sends no ClientHello keeps its handshake in progress,
  4578. // once the server has had a moment to start it.
  4579. auto error = Error::Success;
  4580. auto sock = detail::create_client_socket(
  4581. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4582. /*connection_timeout_sec=*/5, 0,
  4583. /*read_timeout_sec=*/5, 0,
  4584. /*write_timeout_sec=*/5, 0, std::string(), error);
  4585. ASSERT_NE(INVALID_SOCKET, sock);
  4586. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4587. std::string cert_pem, key_pem;
  4588. read_file(SERVER_CERT_FILE, cert_pem);
  4589. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4590. auto update = std::async(std::launch::async, [&]() {
  4591. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4592. });
  4593. EXPECT_EQ(std::future_status::timeout,
  4594. update.wait_for(std::chrono::milliseconds(200)));
  4595. detail::close_socket(sock);
  4596. EXPECT_TRUE(update.get());
  4597. SSLClient cli(HOST, PORT);
  4598. cli.enable_server_certificate_verification(false);
  4599. auto res = cli.Get("/test");
  4600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. #endif
  4604. TEST(ErrorHandlerTest, ContentLength) {
  4605. Server svr;
  4606. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4607. res.status = StatusCode::OK_200;
  4608. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4609. "text/html"); // <= Content-Length still 13
  4610. });
  4611. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4612. res.set_content("Hello World!\n", "text/plain");
  4613. res.status = 524;
  4614. });
  4615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4616. auto se = detail::scope_exit([&] {
  4617. svr.stop();
  4618. thread.join();
  4619. ASSERT_FALSE(svr.is_running());
  4620. });
  4621. svr.wait_until_ready();
  4622. {
  4623. Client cli(HOST, PORT);
  4624. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4626. EXPECT_EQ(StatusCode::OK_200, res->status);
  4627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4628. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4629. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4630. }
  4631. }
  4632. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4633. TEST(ExceptionTest, WithoutExceptionHandler) {
  4634. Server svr;
  4635. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4636. throw std::runtime_error("exception...");
  4637. });
  4638. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4639. throw std::runtime_error("exception\r\n...");
  4640. });
  4641. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4642. auto se = detail::scope_exit([&] {
  4643. svr.stop();
  4644. listen_thread.join();
  4645. ASSERT_FALSE(svr.is_running());
  4646. });
  4647. svr.wait_until_ready();
  4648. Client cli("localhost", PORT);
  4649. {
  4650. auto res = cli.Get("/exception");
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4653. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4654. }
  4655. {
  4656. auto res = cli.Get("/unknown");
  4657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4659. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4660. }
  4661. }
  4662. TEST(ExceptionTest, WithExceptionHandler) {
  4663. Server svr;
  4664. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4665. std::exception_ptr ep) {
  4666. EXPECT_FALSE(ep == nullptr);
  4667. try {
  4668. std::rethrow_exception(ep);
  4669. } catch (std::exception &e) {
  4670. EXPECT_EQ("abc", std::string(e.what()));
  4671. } catch (...) {}
  4672. res.status = StatusCode::InternalServerError_500;
  4673. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4674. "text/html"); // <= Content-Length still 13 at this point
  4675. });
  4676. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4677. res.set_content("Hello World!\n", "text/plain");
  4678. throw std::runtime_error("abc");
  4679. });
  4680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4681. auto se = detail::scope_exit([&] {
  4682. svr.stop();
  4683. thread.join();
  4684. ASSERT_FALSE(svr.is_running());
  4685. });
  4686. svr.wait_until_ready();
  4687. for (size_t i = 0; i < 10; i++) {
  4688. Client cli(HOST, PORT);
  4689. for (size_t j = 0; j < 100; j++) {
  4690. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4692. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4694. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4695. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4696. }
  4697. cli.set_keep_alive(true);
  4698. for (size_t j = 0; j < 100; j++) {
  4699. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4702. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4703. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4704. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4705. }
  4706. }
  4707. }
  4708. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4709. Server svr;
  4710. svr.set_exception_handler(
  4711. [](const Request &, Response &res, std::exception_ptr) {
  4712. res.set_content("oops", "text/plain");
  4713. });
  4714. svr.Get("/throw", [](const Request &, Response &) {
  4715. throw std::runtime_error("throw");
  4716. });
  4717. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4718. res.status = StatusCode::Created_201;
  4719. throw std::runtime_error("created-then-throw");
  4720. });
  4721. auto port = svr.bind_to_any_port(HOST);
  4722. ASSERT_GT(port, 0);
  4723. thread t = thread([&] { svr.listen_after_bind(); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. t.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. Client cli(HOST, port);
  4731. for (auto path : {"/throw", "/created-then-throw"}) {
  4732. auto res = cli.Get(path);
  4733. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4735. }
  4736. }
  4737. TEST(ExceptionTest, AndErrorHandler) {
  4738. Server svr;
  4739. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4740. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4741. });
  4742. svr.set_exception_handler(
  4743. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4744. EXPECT_FALSE(ep == nullptr);
  4745. try {
  4746. std::rethrow_exception(ep);
  4747. } catch (std::exception &e) {
  4748. res.set_content(e.what(), "text/html");
  4749. } catch (...) {}
  4750. res.status = StatusCode::InternalServerError_500;
  4751. });
  4752. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4753. throw std::runtime_error("EXCEPTION");
  4754. });
  4755. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4756. res.set_content("ERROR", "text/html");
  4757. res.status = StatusCode::InternalServerError_500;
  4758. });
  4759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4760. auto se = detail::scope_exit([&] {
  4761. svr.stop();
  4762. thread.join();
  4763. ASSERT_FALSE(svr.is_running());
  4764. });
  4765. svr.wait_until_ready();
  4766. Client cli(HOST, PORT);
  4767. {
  4768. auto res = cli.Get("/exception");
  4769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4770. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4771. EXPECT_EQ("EXCEPTION", res->body);
  4772. }
  4773. {
  4774. auto res = cli.Get("/error");
  4775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4776. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4777. EXPECT_EQ("ERROR", res->body);
  4778. }
  4779. {
  4780. auto res = cli.Get("/invalid");
  4781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4783. EXPECT_EQ("NOT_FOUND", res->body);
  4784. }
  4785. }
  4786. #endif
  4787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4788. // An exception from a user callback outside process_request()'s try/catch
  4789. // used to unwind into the task queue - which does not catch - and terminate
  4790. // the process. Each test below runs the server on a single worker thread: a
  4791. // guard that catches the exception but still loses the thread would otherwise
  4792. // be hidden by a spare worker serving the follow-up request. Note that a
  4793. // regression here aborts the whole test binary rather than failing one test.
  4794. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4795. Server svr;
  4796. svr.new_task_queue = [] { return new ThreadPool(1); };
  4797. std::atomic<int> reported{0};
  4798. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4799. if (err == Error::UserCallbackException) { reported++; }
  4800. });
  4801. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4802. res.set_content_provider(
  4803. 1024, "text/plain",
  4804. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4805. sink.write("hello", 5);
  4806. throw std::runtime_error("from the content provider");
  4807. });
  4808. });
  4809. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4810. res.set_content("ok", "text/plain");
  4811. });
  4812. auto port = svr.bind_to_any_port(HOST);
  4813. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4814. auto se = detail::scope_exit([&] {
  4815. svr.stop();
  4816. listen_thread.join();
  4817. ASSERT_FALSE(svr.is_running());
  4818. });
  4819. svr.wait_until_ready();
  4820. {
  4821. Client cli(HOST, port);
  4822. cli.set_read_timeout(5, 0);
  4823. EXPECT_FALSE(cli.Get("/throw"));
  4824. }
  4825. EXPECT_TRUE(svr.is_running());
  4826. EXPECT_EQ(1, reported.load());
  4827. // A request on a fresh connection is still served.
  4828. {
  4829. Client cli(HOST, port);
  4830. auto res = cli.Get("/ok");
  4831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. EXPECT_EQ("ok", res->body);
  4834. }
  4835. }
  4836. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4837. Server svr;
  4838. svr.new_task_queue = [] { return new ThreadPool(1); };
  4839. std::atomic<bool> should_throw{true};
  4840. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4841. res.set_content("hi", "text/plain");
  4842. });
  4843. svr.set_post_routing_handler(
  4844. [&](const Request & /*req*/, Response & /*res*/) {
  4845. if (should_throw) {
  4846. throw std::runtime_error("from the post-routing handler");
  4847. }
  4848. });
  4849. auto port = svr.bind_to_any_port(HOST);
  4850. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. listen_thread.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. {
  4858. Client cli(HOST, port);
  4859. cli.set_read_timeout(5, 0);
  4860. EXPECT_FALSE(cli.Get("/hi"));
  4861. }
  4862. EXPECT_TRUE(svr.is_running());
  4863. should_throw = false;
  4864. {
  4865. Client cli(HOST, port);
  4866. auto res = cli.Get("/hi");
  4867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ("hi", res->body);
  4870. }
  4871. }
  4872. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4873. // The guard reports the caught exception through the error logger, which is
  4874. // a user callback too. A logger that throws has to be contained as well, or
  4875. // the process would terminate from inside the catch.
  4876. Server svr;
  4877. svr.new_task_queue = [] { return new ThreadPool(1); };
  4878. std::atomic<int> reported{0};
  4879. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4880. if (err == Error::UserCallbackException) {
  4881. reported++;
  4882. throw std::runtime_error("from the error logger");
  4883. }
  4884. });
  4885. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4886. res.set_content_provider(
  4887. 1024, "text/plain",
  4888. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4889. sink.write("hello", 5);
  4890. throw std::runtime_error("from the content provider");
  4891. });
  4892. });
  4893. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4894. res.set_content("ok", "text/plain");
  4895. });
  4896. auto port = svr.bind_to_any_port(HOST);
  4897. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4898. auto se = detail::scope_exit([&] {
  4899. svr.stop();
  4900. listen_thread.join();
  4901. ASSERT_FALSE(svr.is_running());
  4902. });
  4903. svr.wait_until_ready();
  4904. {
  4905. Client cli(HOST, port);
  4906. cli.set_read_timeout(5, 0);
  4907. EXPECT_FALSE(cli.Get("/throw"));
  4908. }
  4909. EXPECT_TRUE(svr.is_running());
  4910. EXPECT_EQ(1, reported.load());
  4911. {
  4912. Client cli(HOST, port);
  4913. auto res = cli.Get("/ok");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("ok", res->body);
  4917. }
  4918. }
  4919. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4920. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4921. // so the exception unwinds through the ws::WebSocket object on its way to
  4922. // the guard. None of the HTTP cases above cross that.
  4923. Server svr;
  4924. svr.new_task_queue = [] { return new ThreadPool(1); };
  4925. std::atomic<int> reported{0};
  4926. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4927. if (err == Error::UserCallbackException) { reported++; }
  4928. });
  4929. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4930. throw std::runtime_error("from the WebSocket handler");
  4931. });
  4932. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4933. res.set_content("ok", "text/plain");
  4934. });
  4935. auto port = svr.bind_to_any_port(HOST);
  4936. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. listen_thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. {
  4944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4945. "/ws");
  4946. auto res = client.connect();
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. // The server dropped the connection instead of dying.
  4949. std::string msg;
  4950. EXPECT_FALSE(client.read(msg));
  4951. client.close();
  4952. }
  4953. EXPECT_TRUE(svr.is_running());
  4954. EXPECT_EQ(1, reported.load());
  4955. {
  4956. Client cli(HOST, port);
  4957. auto res = cli.Get("/ok");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. EXPECT_EQ("ok", res->body);
  4961. }
  4962. }
  4963. #ifdef CPPHTTPLIB_SSL_ENABLED
  4964. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4965. // SSLServer::process_and_close_socket() is a separate overload with its own
  4966. // guard, so it is exercised on its own.
  4967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4968. ASSERT_TRUE(svr.is_valid());
  4969. svr.new_task_queue = [] { return new ThreadPool(1); };
  4970. std::atomic<int> reported{0};
  4971. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4972. if (err == Error::UserCallbackException) { reported++; }
  4973. });
  4974. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4975. res.set_content_provider(
  4976. 1024, "text/plain",
  4977. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4978. sink.write("hello", 5);
  4979. throw std::runtime_error("from the content provider");
  4980. });
  4981. });
  4982. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4983. res.set_content("ok", "text/plain");
  4984. });
  4985. auto port = svr.bind_to_any_port(HOST);
  4986. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4987. auto se = detail::scope_exit([&] {
  4988. svr.stop();
  4989. listen_thread.join();
  4990. ASSERT_FALSE(svr.is_running());
  4991. });
  4992. svr.wait_until_ready();
  4993. {
  4994. SSLClient cli(HOST, port);
  4995. cli.enable_server_certificate_verification(false);
  4996. cli.set_read_timeout(5, 0);
  4997. EXPECT_FALSE(cli.Get("/throw"));
  4998. }
  4999. EXPECT_TRUE(svr.is_running());
  5000. EXPECT_EQ(1, reported.load());
  5001. {
  5002. SSLClient cli(HOST, port);
  5003. cli.enable_server_certificate_verification(false);
  5004. auto res = cli.Get("/ok");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("ok", res->body);
  5008. }
  5009. }
  5010. #endif
  5011. #endif
  5012. TEST(NoContentTest, ContentLength) {
  5013. Server svr;
  5014. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5015. res.status = StatusCode::NoContent_204;
  5016. });
  5017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5018. auto se = detail::scope_exit([&] {
  5019. svr.stop();
  5020. thread.join();
  5021. ASSERT_FALSE(svr.is_running());
  5022. });
  5023. svr.wait_until_ready();
  5024. {
  5025. Client cli(HOST, PORT);
  5026. auto res = cli.Get("/hi");
  5027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5028. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5029. // RFC 9110 8.6: none in a 204 response
  5030. EXPECT_FALSE(res->has_header("Content-Length"));
  5031. }
  5032. }
  5033. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5034. Server svr;
  5035. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5036. res.set_header("Content-Length", "5");
  5037. res.set_content("hello world", "text/plain");
  5038. });
  5039. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5040. // A body that reads as the last chunk, were it taken as chunked
  5041. res.set_header("Transfer-Encoding", "chunked");
  5042. res.set_content("0\r\n\r\n", "text/plain");
  5043. });
  5044. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5045. res.set_header("Content-Length", "2");
  5046. res.set_content_provider(5, "text/plain",
  5047. [](size_t offset, size_t length, DataSink &sink) {
  5048. sink.write(&"hello"[offset], length);
  5049. return true;
  5050. });
  5051. });
  5052. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5053. res.set_header("Content-Length", "1234");
  5054. });
  5055. thread t = thread([&] { svr.listen(HOST, PORT); });
  5056. auto se = detail::scope_exit([&] {
  5057. svr.stop();
  5058. t.join();
  5059. ASSERT_FALSE(svr.is_running());
  5060. });
  5061. svr.wait_until_ready();
  5062. Client cli(HOST, PORT);
  5063. cli.set_read_timeout(1, 0);
  5064. auto expect_body = [&](const Result &res, const std::string &body) {
  5065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5066. EXPECT_EQ(body, res->body);
  5067. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5068. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5069. };
  5070. Headers identity{{"Accept-Encoding", ""}};
  5071. expect_body(cli.Get("/body", identity), "hello world");
  5072. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5073. expect_body(cli.Get("/body",
  5074. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5075. "he");
  5076. expect_body(cli.Get("/provider", identity), "hello");
  5077. expect_body(cli.Get("/empty", identity), "");
  5078. // A HEAD response may give the length of the body a GET would get.
  5079. auto res = cli.Head("/empty");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5082. }
  5083. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5084. Server svr;
  5085. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5086. res.set_content("short", "text/plain");
  5087. });
  5088. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5089. res.body += " with a footer";
  5090. res.set_header("Transfer-Encoding", "chunked");
  5091. });
  5092. thread t = thread([&] { svr.listen(HOST, PORT); });
  5093. auto se = detail::scope_exit([&] {
  5094. svr.stop();
  5095. t.join();
  5096. ASSERT_FALSE(svr.is_running());
  5097. });
  5098. svr.wait_until_ready();
  5099. Client cli(HOST, PORT);
  5100. cli.set_read_timeout(1, 0);
  5101. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5103. EXPECT_EQ("short with a footer", res->body);
  5104. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5105. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5106. }
  5107. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5108. Server svr;
  5109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5110. res.set_header("Content-Length", "3");
  5111. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5112. sink.write("abc", 3);
  5113. sink.done();
  5114. return true;
  5115. });
  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_keep_alive(true);
  5126. auto res = cli.Get("/");
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. EXPECT_EQ("abc", res->body);
  5129. EXPECT_FALSE(res->has_header("Content-Length"));
  5130. EXPECT_EQ("close", res->get_header_value("Connection"));
  5131. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5132. // No body to delimit
  5133. auto head = cli.Head("/");
  5134. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5135. EXPECT_FALSE(head->has_header("Connection"));
  5136. }
  5137. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5138. #ifdef CPPHTTPLIB_SSL_ENABLED
  5139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5140. ASSERT_TRUE(svr.is_valid());
  5141. #else
  5142. Server svr;
  5143. #endif
  5144. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5145. if (req.path == "/routing_handler") {
  5146. res.set_header("PRE_ROUTING", "on");
  5147. res.set_content("Routing Handler", "text/plain");
  5148. return httplib::Server::HandlerResponse::Handled;
  5149. }
  5150. return httplib::Server::HandlerResponse::Unhandled;
  5151. });
  5152. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5153. res.set_content("Error", "text/html");
  5154. });
  5155. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5156. if (req.path == "/routing_handler") {
  5157. res.set_header("POST_ROUTING", "on");
  5158. }
  5159. });
  5160. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5161. res.set_content("Hello World!\n", "text/plain");
  5162. });
  5163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5164. auto se = detail::scope_exit([&] {
  5165. svr.stop();
  5166. thread.join();
  5167. ASSERT_FALSE(svr.is_running());
  5168. });
  5169. svr.wait_until_ready();
  5170. {
  5171. #ifdef CPPHTTPLIB_SSL_ENABLED
  5172. SSLClient cli(HOST, PORT);
  5173. cli.enable_server_certificate_verification(false);
  5174. #else
  5175. Client cli(HOST, PORT);
  5176. #endif
  5177. auto res = cli.Get("/routing_handler");
  5178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("Routing Handler", res->body);
  5181. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5182. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5183. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5184. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5185. }
  5186. {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. SSLClient cli(HOST, PORT);
  5189. cli.enable_server_certificate_verification(false);
  5190. #else
  5191. Client cli(HOST, PORT);
  5192. #endif
  5193. auto res = cli.Get("/hi");
  5194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. EXPECT_EQ("Hello World!\n", res->body);
  5197. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5198. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5199. }
  5200. {
  5201. #ifdef CPPHTTPLIB_SSL_ENABLED
  5202. SSLClient cli(HOST, PORT);
  5203. cli.enable_server_certificate_verification(false);
  5204. #else
  5205. Client cli(HOST, PORT);
  5206. #endif
  5207. auto res = cli.Get("/aaa");
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5210. EXPECT_EQ("Error", res->body);
  5211. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5212. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5213. }
  5214. }
  5215. TEST(RequestHandlerTest, PreRequestHandler) {
  5216. auto route_path = "/user/:user";
  5217. Server svr;
  5218. svr.Get("/hi", [](const Request &, Response &res) {
  5219. res.set_content("hi", "text/plain");
  5220. });
  5221. svr.Get(route_path, [](const Request &req, Response &res) {
  5222. res.set_content(req.path_params.at("user"), "text/plain");
  5223. });
  5224. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5225. if (req.matched_route == route_path) {
  5226. auto user = req.path_params.at("user");
  5227. if (user != "john") {
  5228. res.status = StatusCode::Forbidden_403;
  5229. res.set_content("error", "text/html");
  5230. return Server::HandlerResponse::Handled;
  5231. }
  5232. }
  5233. return Server::HandlerResponse::Unhandled;
  5234. });
  5235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5236. auto se = detail::scope_exit([&] {
  5237. svr.stop();
  5238. thread.join();
  5239. ASSERT_FALSE(svr.is_running());
  5240. });
  5241. svr.wait_until_ready();
  5242. Client cli(HOST, PORT);
  5243. {
  5244. auto res = cli.Get("/hi");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. EXPECT_EQ("hi", res->body);
  5248. }
  5249. {
  5250. auto res = cli.Get("/user/john");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("john", res->body);
  5254. }
  5255. {
  5256. auto res = cli.Get("/user/invalid-user");
  5257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5258. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5259. EXPECT_EQ("error", res->body);
  5260. }
  5261. }
  5262. // The pre-request handler must run before the request body is read, so a
  5263. // rejected request never forces the server to buffer a (potentially large)
  5264. // body. Here the posted body is larger than the payload limit: if the body
  5265. // were read first the server would answer 413, but because the pre-request
  5266. // handler runs first it answers 403 and the body is never read.
  5267. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5268. Server svr;
  5269. svr.set_payload_max_length(8);
  5270. auto handler_ran = false;
  5271. svr.Post("/reject", [&](const Request &req, Response &res) {
  5272. handler_ran = true;
  5273. res.set_content(req.body, "text/plain");
  5274. });
  5275. svr.Post("/accept", [](const Request &req, Response &res) {
  5276. res.set_content(req.body, "text/plain");
  5277. });
  5278. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5279. if (req.matched_route == "/reject") {
  5280. res.status = StatusCode::Forbidden_403;
  5281. res.set_content("denied", "text/plain");
  5282. return Server::HandlerResponse::Handled;
  5283. }
  5284. return Server::HandlerResponse::Unhandled;
  5285. });
  5286. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5287. auto se = detail::scope_exit([&] {
  5288. svr.stop();
  5289. thread.join();
  5290. ASSERT_FALSE(svr.is_running());
  5291. });
  5292. svr.wait_until_ready();
  5293. Client cli(HOST, PORT);
  5294. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5295. // rejects with 403 before the body is read, so 413 is never reached.
  5296. {
  5297. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5300. EXPECT_EQ("denied", res->body);
  5301. EXPECT_FALSE(handler_ran);
  5302. }
  5303. // An approved route still reads the body and enforces the payload limit.
  5304. {
  5305. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5308. }
  5309. }
  5310. TEST(UserDataTest, BasicOperations) {
  5311. httplib::UserData ud;
  5312. // Initially empty
  5313. EXPECT_FALSE(ud.has("key"));
  5314. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5315. // set and get
  5316. ud.set("key", 42);
  5317. EXPECT_TRUE(ud.has("key"));
  5318. auto *p = ud.get<int>("key");
  5319. ASSERT_NE(nullptr, p);
  5320. EXPECT_EQ(42, *p);
  5321. // Type mismatch → nullptr
  5322. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5323. // Overwrite with different type
  5324. ud.set("key", std::string("hello"));
  5325. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5326. auto *s = ud.get<std::string>("key");
  5327. ASSERT_NE(nullptr, s);
  5328. EXPECT_EQ("hello", *s);
  5329. // erase
  5330. ud.erase("key");
  5331. EXPECT_FALSE(ud.has("key"));
  5332. // clear
  5333. ud.set("a", 1);
  5334. ud.set("b", 2);
  5335. ud.clear();
  5336. EXPECT_FALSE(ud.has("a"));
  5337. EXPECT_FALSE(ud.has("b"));
  5338. }
  5339. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5340. struct AuthCtx {
  5341. std::string user_id;
  5342. };
  5343. Server svr;
  5344. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5345. res.user_data.set("auth", AuthCtx{"alice"});
  5346. return Server::HandlerResponse::Unhandled;
  5347. });
  5348. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5349. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5350. ASSERT_NE(nullptr, ctx);
  5351. res.set_content("Hello " + ctx->user_id, "text/plain");
  5352. });
  5353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5354. auto se = detail::scope_exit([&] {
  5355. svr.stop();
  5356. thread.join();
  5357. ASSERT_FALSE(svr.is_running());
  5358. });
  5359. svr.wait_until_ready();
  5360. Client cli(HOST, PORT);
  5361. auto res = cli.Get("/me");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("Hello alice", res->body);
  5365. }
  5366. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5367. struct RoleCtx {
  5368. std::string role;
  5369. };
  5370. Server svr;
  5371. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5372. res.user_data.set("role", RoleCtx{"admin"});
  5373. return Server::HandlerResponse::Unhandled;
  5374. });
  5375. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5376. auto *ctx = res.user_data.get<RoleCtx>("role");
  5377. ASSERT_NE(nullptr, ctx);
  5378. res.set_content(ctx->role, "text/plain");
  5379. });
  5380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5381. auto se = detail::scope_exit([&] {
  5382. svr.stop();
  5383. thread.join();
  5384. ASSERT_FALSE(svr.is_running());
  5385. });
  5386. svr.wait_until_ready();
  5387. Client cli(HOST, PORT);
  5388. auto res = cli.Get("/role");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("admin", res->body);
  5392. }
  5393. TEST(InvalidFormatTest, StatusCode) {
  5394. Server svr;
  5395. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5396. res.set_content("Hello World!\n", "text/plain");
  5397. res.status = 9999; // Status should be a three-digit code...
  5398. });
  5399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5400. auto se = detail::scope_exit([&] {
  5401. svr.stop();
  5402. thread.join();
  5403. ASSERT_FALSE(svr.is_running());
  5404. });
  5405. svr.wait_until_ready();
  5406. {
  5407. Client cli(HOST, PORT);
  5408. auto res = cli.Get("/hi");
  5409. ASSERT_FALSE(res);
  5410. }
  5411. }
  5412. TEST(URLFragmentTest, WithFragment) {
  5413. Server svr;
  5414. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5415. EXPECT_TRUE(req.target == "/hi");
  5416. });
  5417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5418. auto se = detail::scope_exit([&] {
  5419. svr.stop();
  5420. thread.join();
  5421. ASSERT_FALSE(svr.is_running());
  5422. });
  5423. svr.wait_until_ready();
  5424. {
  5425. Client cli(HOST, PORT);
  5426. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5427. EXPECT_TRUE(res);
  5428. EXPECT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli.Get("/hi%23key1=val1=key2=val2");
  5430. EXPECT_TRUE(res);
  5431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5432. }
  5433. }
  5434. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5435. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5436. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5437. Server svr;
  5438. std::vector<std::string> targets;
  5439. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5440. targets.push_back(req.target);
  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. Client cli(HOST, PORT);
  5450. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5451. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5452. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5453. // A '?' after the '#' belongs to the fragment, not to the query.
  5454. Request req;
  5455. req.method = "GET";
  5456. req.path = "/hi#f?x=1";
  5457. req.params.emplace("a", "1");
  5458. Response res;
  5459. auto error = Error::Success;
  5460. EXPECT_TRUE(cli.send(req, res, error));
  5461. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5462. "/hi?a=1"}),
  5463. targets);
  5464. }
  5465. TEST(HeaderWriter, SetHeaderWriter) {
  5466. Server svr;
  5467. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5468. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5469. return detail::write_headers(strm, hdrs);
  5470. });
  5471. svr.Get("/hi", [](const Request &req, Response &res) {
  5472. auto it = req.headers.find("CustomClientHeader");
  5473. EXPECT_TRUE(it != req.headers.end());
  5474. EXPECT_EQ(it->second, "CustomClientValue");
  5475. res.set_content("Hello World!\n", "text/plain");
  5476. });
  5477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5478. auto se = detail::scope_exit([&] {
  5479. svr.stop();
  5480. thread.join();
  5481. ASSERT_FALSE(svr.is_running());
  5482. });
  5483. svr.wait_until_ready();
  5484. {
  5485. Client cli(HOST, PORT);
  5486. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5487. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5488. return detail::write_headers(strm, hdrs);
  5489. });
  5490. auto res = cli.Get("/hi");
  5491. EXPECT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. auto it = res->headers.find("CustomServerHeader");
  5494. EXPECT_TRUE(it != res->headers.end());
  5495. EXPECT_EQ(it->second, "CustomServerValue");
  5496. }
  5497. }
  5498. class ServerTest : public ::testing::Test {
  5499. protected:
  5500. ServerTest()
  5501. : cli_(HOST, PORT)
  5502. #ifdef CPPHTTPLIB_SSL_ENABLED
  5503. ,
  5504. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5505. #endif
  5506. {
  5507. #ifdef CPPHTTPLIB_SSL_ENABLED
  5508. cli_.enable_server_certificate_verification(false);
  5509. #endif
  5510. // Allow LARGE_DATA (100MB) responses
  5511. cli_.set_payload_max_length(200 * 1024 * 1024);
  5512. }
  5513. virtual void SetUp() {
  5514. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5515. svr_.set_payload_max_length(200 * 1024 * 1024);
  5516. svr_.set_mount_point("/", "./www");
  5517. svr_.set_mount_point("/mount", "./www2");
  5518. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5519. svr_.Get("/hi",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. res.set_content("Hello World!", "text/plain");
  5522. })
  5523. .Get("/file_content",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_file_content("./www/dir/test.html");
  5526. })
  5527. .Get("/file_content_with_content_type",
  5528. [&](const Request & /*req*/, Response &res) {
  5529. res.set_file_content("./www/file", "text/plain");
  5530. })
  5531. .Get("/invalid_file_content",
  5532. [&](const Request & /*req*/, Response &res) {
  5533. res.set_file_content("./www/dir/invalid_file_path");
  5534. })
  5535. .Get("/http_response_splitting",
  5536. [&](const Request & /*req*/, Response &res) {
  5537. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5538. EXPECT_EQ(0U, res.headers.size());
  5539. EXPECT_FALSE(res.has_header("a"));
  5540. res.set_header("a", "1\nSet-Cookie: a=1");
  5541. EXPECT_EQ(0U, res.headers.size());
  5542. EXPECT_FALSE(res.has_header("a"));
  5543. res.set_header("a", "1\rSet-Cookie: a=1");
  5544. EXPECT_EQ(0U, res.headers.size());
  5545. EXPECT_FALSE(res.has_header("a"));
  5546. res.set_header("a\r\nb", "0");
  5547. EXPECT_EQ(0U, res.headers.size());
  5548. EXPECT_FALSE(res.has_header("a"));
  5549. res.set_header("a\rb", "0");
  5550. EXPECT_EQ(0U, res.headers.size());
  5551. EXPECT_FALSE(res.has_header("a"));
  5552. res.set_header("a\nb", "0");
  5553. EXPECT_EQ(0U, res.headers.size());
  5554. EXPECT_FALSE(res.has_header("a"));
  5555. res.set_redirect("1\r\nSet-Cookie: a=1");
  5556. EXPECT_EQ(0U, res.headers.size());
  5557. EXPECT_FALSE(res.has_header("Location"));
  5558. })
  5559. .Get("/slow",
  5560. [&](const Request & /*req*/, Response &res) {
  5561. std::this_thread::sleep_for(std::chrono::seconds(4));
  5562. res.set_content("slow", "text/plain");
  5563. })
  5564. #if 0
  5565. .Post("/slowpost",
  5566. [&](const Request & /*req*/, Response &res) {
  5567. std::this_thread::sleep_for(std::chrono::seconds(2));
  5568. res.set_content("slow", "text/plain");
  5569. })
  5570. #endif
  5571. .Get("/remote_addr",
  5572. [&](const Request &req, Response &res) {
  5573. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5574. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5575. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5576. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5577. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5578. #endif
  5579. res.set_content(req.remote_addr, "text/plain");
  5580. })
  5581. .Get("/local_addr",
  5582. [&](const Request &req, Response &res) {
  5583. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5584. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5585. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5586. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5587. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5588. #endif
  5589. auto local_addr = req.local_addr;
  5590. auto local_port = std::to_string(req.local_port);
  5591. res.set_content(local_addr.append(":").append(local_port),
  5592. "text/plain");
  5593. })
  5594. .Get("/endwith%",
  5595. [&](const Request & /*req*/, Response &res) {
  5596. res.set_content("Hello World!", "text/plain");
  5597. })
  5598. .Get("/a\\+\\+b",
  5599. [&](const Request &req, Response &res) {
  5600. ASSERT_TRUE(req.has_param("a +b"));
  5601. auto val = req.get_param_value("a +b");
  5602. res.set_content(val, "text/plain");
  5603. })
  5604. .Get("/", [&](const Request & /*req*/,
  5605. Response &res) { res.set_redirect("/hi"); })
  5606. .Post("/1",
  5607. [](const Request & /*req*/, Response &res) {
  5608. res.set_redirect("/2", StatusCode::SeeOther_303);
  5609. })
  5610. .Get("/2",
  5611. [](const Request & /*req*/, Response &res) {
  5612. res.set_content("redirected.", "text/plain");
  5613. res.status = StatusCode::OK_200;
  5614. })
  5615. .Post("/person",
  5616. [&](const Request &req, Response &res) {
  5617. if (req.has_param("name") && req.has_param("note")) {
  5618. persons_[req.get_param_value("name")] =
  5619. req.get_param_value("note");
  5620. } else {
  5621. res.status = StatusCode::BadRequest_400;
  5622. }
  5623. })
  5624. .Put("/person",
  5625. [&](const Request &req, Response &res) {
  5626. if (req.has_param("name") && req.has_param("note")) {
  5627. persons_[req.get_param_value("name")] =
  5628. req.get_param_value("note");
  5629. } else {
  5630. res.status = StatusCode::BadRequest_400;
  5631. }
  5632. })
  5633. .Get("/person/(.*)",
  5634. [&](const Request &req, Response &res) {
  5635. string name = req.matches[1];
  5636. if (persons_.find(name) != persons_.end()) {
  5637. auto note = persons_[name];
  5638. res.set_content(note, "text/plain");
  5639. } else {
  5640. res.status = StatusCode::NotFound_404;
  5641. }
  5642. })
  5643. .Delete("/person",
  5644. [&](const Request &req, Response &res) {
  5645. if (req.has_param("name")) {
  5646. string name = req.get_param_value("name");
  5647. if (persons_.find(name) != persons_.end()) {
  5648. persons_.erase(name);
  5649. res.set_content("DELETED", "text/plain");
  5650. } else {
  5651. res.status = StatusCode::NotFound_404;
  5652. }
  5653. } else {
  5654. res.status = StatusCode::BadRequest_400;
  5655. }
  5656. })
  5657. .Post("/x-www-form-urlencoded-json",
  5658. [&](const Request &req, Response &res) {
  5659. auto json = req.get_param_value("json");
  5660. ASSERT_EQ(JSON_DATA, json);
  5661. res.set_content(json, "appliation/json");
  5662. res.status = StatusCode::OK_200;
  5663. })
  5664. .Get("/streamed-chunked",
  5665. [&](const Request & /*req*/, Response &res) {
  5666. res.set_chunked_content_provider(
  5667. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5668. sink.os << "123";
  5669. sink.os << "456";
  5670. sink.os << "789";
  5671. sink.done();
  5672. return true;
  5673. });
  5674. })
  5675. .Get("/streamed-chunked-with-prohibited-trailer",
  5676. [&](const Request & /*req*/, Response &res) {
  5677. auto i = new int(0);
  5678. // Declare both a prohibited trailer (Content-Length) and an
  5679. // allowed one
  5680. res.set_header("Trailer", "Content-Length, X-Allowed");
  5681. res.set_chunked_content_provider(
  5682. "text/plain",
  5683. [i](size_t /*offset*/, DataSink &sink) {
  5684. switch (*i) {
  5685. case 0: sink.os << "123"; break;
  5686. case 1: sink.os << "456"; break;
  5687. case 2: sink.os << "789"; break;
  5688. case 3: {
  5689. sink.done_with_trailer(
  5690. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5691. } break;
  5692. }
  5693. (*i)++;
  5694. return true;
  5695. },
  5696. [i](bool success) {
  5697. EXPECT_TRUE(success);
  5698. delete i;
  5699. });
  5700. })
  5701. .Get("/streamed-chunked2",
  5702. [&](const Request & /*req*/, Response &res) {
  5703. auto i = new int(0);
  5704. res.set_chunked_content_provider(
  5705. "text/plain",
  5706. [i](size_t /*offset*/, DataSink &sink) {
  5707. switch (*i) {
  5708. case 0: sink.os << "123"; break;
  5709. case 1: sink.os << "456"; break;
  5710. case 2: sink.os << "789"; break;
  5711. case 3: sink.done(); break;
  5712. }
  5713. (*i)++;
  5714. return true;
  5715. },
  5716. [i](bool success) {
  5717. EXPECT_TRUE(success);
  5718. delete i;
  5719. });
  5720. })
  5721. .Get("/streamed-chunked-with-trailer",
  5722. [&](const Request & /*req*/, Response &res) {
  5723. auto i = new int(0);
  5724. res.set_header("Trailer", "Dummy1, Dummy2");
  5725. res.set_chunked_content_provider(
  5726. "text/plain",
  5727. [i](size_t /*offset*/, DataSink &sink) {
  5728. switch (*i) {
  5729. case 0: sink.os << "123"; break;
  5730. case 1: sink.os << "456"; break;
  5731. case 2: sink.os << "789"; break;
  5732. case 3: {
  5733. sink.done_with_trailer(
  5734. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5735. } break;
  5736. }
  5737. (*i)++;
  5738. return true;
  5739. },
  5740. [i](bool success) {
  5741. EXPECT_TRUE(success);
  5742. delete i;
  5743. });
  5744. })
  5745. .Get("/streamed",
  5746. [&](const Request & /*req*/, Response &res) {
  5747. res.set_content_provider(
  5748. 6, "text/plain",
  5749. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5750. sink.os << (offset < 3 ? "a" : "b");
  5751. return true;
  5752. });
  5753. })
  5754. .Get("/streamed-without-length",
  5755. [&](const Request & /*req*/, Response &res) {
  5756. auto data = new std::string("abcdefg");
  5757. res.set_content_provider(
  5758. "text/plain",
  5759. [data](size_t offset, DataSink &sink) {
  5760. if (offset < data->size()) {
  5761. sink.os << data->substr(offset);
  5762. }
  5763. sink.done();
  5764. return true;
  5765. },
  5766. [data](bool success) {
  5767. EXPECT_TRUE(success);
  5768. delete data;
  5769. });
  5770. })
  5771. .Get("/streamed-with-range",
  5772. [&](const Request &req, Response &res) {
  5773. auto data = new std::string("abcdefg");
  5774. // An explicit status keeps the server from picking the 206 it
  5775. // would otherwise choose for a ranged request, so the response
  5776. // is not a partial representation.
  5777. auto status = req.get_param_value("status");
  5778. if (status == "200") {
  5779. res.status = StatusCode::OK_200;
  5780. } else if (status == "403") {
  5781. res.status = StatusCode::Forbidden_403;
  5782. }
  5783. res.set_content_provider(
  5784. data->size(), "text/plain",
  5785. [data](size_t offset, size_t length, DataSink &sink) {
  5786. size_t DATA_CHUNK_SIZE = 4;
  5787. const auto &d = *data;
  5788. auto out_len =
  5789. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5790. auto ret =
  5791. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5792. EXPECT_TRUE(ret);
  5793. return true;
  5794. },
  5795. [data, &req](bool success) {
  5796. EXPECT_EQ(success, !req.has_param("error"));
  5797. delete data;
  5798. });
  5799. })
  5800. .Get("/streamed-cancel",
  5801. [&](const Request & /*req*/, Response &res) {
  5802. res.set_content_provider(
  5803. size_t(-1), "text/plain",
  5804. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5805. sink.os << "data_chunk";
  5806. return true;
  5807. });
  5808. })
  5809. .Get("/regex-with-delimiter",
  5810. [&](const Request &req, Response & /*res*/) {
  5811. ASSERT_TRUE(req.has_param("key"));
  5812. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5813. })
  5814. .Get("/with-range",
  5815. [&](const Request & /*req*/, Response &res) {
  5816. res.set_content("abcdefg", "text/plain");
  5817. })
  5818. .Get("/test-start-time",
  5819. [&](const Request &req, Response & /*res*/) {
  5820. EXPECT_NE(req.start_time_,
  5821. std::chrono::steady_clock::time_point::min());
  5822. })
  5823. .Get("/with-range-customized-response",
  5824. [&](const Request & /*req*/, Response &res) {
  5825. res.status = StatusCode::BadRequest_400;
  5826. res.set_content(JSON_DATA, "application/json");
  5827. })
  5828. .Post("/chunked",
  5829. [&](const Request &req, Response & /*res*/) {
  5830. EXPECT_EQ(req.body, "dechunked post body");
  5831. })
  5832. .Post("/large-chunked",
  5833. [&](const Request &req, Response & /*res*/) {
  5834. std::string expected(6 * 30 * 1024u, 'a');
  5835. EXPECT_EQ(req.body, expected);
  5836. })
  5837. .Post("/multipart",
  5838. [&](const Request &req, Response & /*res*/) {
  5839. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5840. req.form.get_field_count("text2") +
  5841. req.form.get_field_count("file3") +
  5842. req.form.get_field_count("file4"));
  5843. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5844. req.form.get_file_count("file2"));
  5845. ASSERT_TRUE(!req.form.has_file("???"));
  5846. ASSERT_TRUE(!req.form.has_field("???"));
  5847. ASSERT_TRUE(req.body.empty());
  5848. {
  5849. const auto &text = req.form.get_field("text1");
  5850. EXPECT_EQ("text default", text);
  5851. }
  5852. {
  5853. const auto &text = req.form.get_field("text2");
  5854. EXPECT_EQ("aωb", text);
  5855. }
  5856. {
  5857. const auto &file = req.form.get_file("file1");
  5858. EXPECT_EQ("hello.txt", file.filename);
  5859. EXPECT_EQ("text/plain", file.content_type);
  5860. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5861. }
  5862. {
  5863. const auto &file = req.form.get_file("file2");
  5864. EXPECT_EQ("world.json", file.filename);
  5865. EXPECT_EQ("application/json", file.content_type);
  5866. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5867. }
  5868. {
  5869. const auto &text = req.form.get_field("file3");
  5870. EXPECT_EQ(0u, text.size());
  5871. }
  5872. {
  5873. const auto &text = req.form.get_field("file4");
  5874. EXPECT_EQ(0u, text.size());
  5875. }
  5876. })
  5877. .Post("/multipart/multi_file_values",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5880. req.form.get_field_count("multi_text1"));
  5881. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5882. ASSERT_TRUE(!req.form.has_file("???"));
  5883. ASSERT_TRUE(!req.form.has_field("???"));
  5884. ASSERT_TRUE(req.body.empty());
  5885. {
  5886. const auto &text = req.form.get_field("text");
  5887. EXPECT_EQ("default text", text);
  5888. }
  5889. {
  5890. const auto &text1_values = req.form.get_fields("multi_text1");
  5891. EXPECT_EQ(2u, text1_values.size());
  5892. EXPECT_EQ("aaaaa", text1_values[0]);
  5893. EXPECT_EQ("bbbbb", text1_values[1]);
  5894. }
  5895. {
  5896. const auto &file1_values = req.form.get_files("multi_file1");
  5897. EXPECT_EQ(2u, file1_values.size());
  5898. auto file1 = file1_values[0];
  5899. EXPECT_EQ(file1.filename, "hello.txt");
  5900. EXPECT_EQ(file1.content_type, "text/plain");
  5901. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5902. auto file2 = file1_values[1];
  5903. EXPECT_EQ(file2.filename, "world.json");
  5904. EXPECT_EQ(file2.content_type, "application/json");
  5905. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5906. }
  5907. })
  5908. .Post("/empty",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(req.body, "");
  5911. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5912. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5913. res.set_content("empty", "text/plain");
  5914. })
  5915. .Post("/empty-no-content-type",
  5916. [&](const Request &req, Response &res) {
  5917. EXPECT_EQ(req.body, "");
  5918. EXPECT_FALSE(req.has_header("Content-Type"));
  5919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5920. res.set_content("empty-no-content-type", "text/plain");
  5921. })
  5922. .Post("/path-only",
  5923. [&](const Request &req, Response &res) {
  5924. EXPECT_EQ(req.body, "");
  5925. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5926. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5927. res.set_content("path-only", "text/plain");
  5928. })
  5929. .Post("/path-headers-only",
  5930. [&](const Request &req, Response &res) {
  5931. EXPECT_EQ(req.body, "");
  5932. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5934. EXPECT_EQ("world", req.get_header_value("hello"));
  5935. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5936. res.set_content("path-headers-only", "text/plain");
  5937. })
  5938. .Post("/post-large",
  5939. [&](const Request &req, Response &res) {
  5940. EXPECT_EQ(req.body, LARGE_DATA);
  5941. res.set_content(req.body, "text/plain");
  5942. })
  5943. .Post("/post-loopback",
  5944. [&](const Request &, Response &res,
  5945. ContentReader const &content_reader) {
  5946. std::string body;
  5947. content_reader([&](const char *data, size_t data_length) {
  5948. body.append(data, data_length);
  5949. return true;
  5950. });
  5951. res.set_content(body, "text/plain");
  5952. })
  5953. .Put("/put-loopback",
  5954. [&](const Request &, Response &res,
  5955. ContentReader const &content_reader) {
  5956. std::string body;
  5957. content_reader([&](const char *data, size_t data_length) {
  5958. body.append(data, data_length);
  5959. return true;
  5960. });
  5961. res.set_content(body, "text/plain");
  5962. })
  5963. .Patch("/patch-loopback",
  5964. [&](const Request &, Response &res,
  5965. ContentReader const &content_reader) {
  5966. std::string body;
  5967. content_reader([&](const char *data, size_t data_length) {
  5968. body.append(data, data_length);
  5969. return true;
  5970. });
  5971. res.set_content(body, "text/plain");
  5972. })
  5973. .Put("/empty-no-content-type",
  5974. [&](const Request &req, Response &res) {
  5975. EXPECT_EQ(req.body, "");
  5976. EXPECT_FALSE(req.has_header("Content-Type"));
  5977. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5978. res.set_content("empty-no-content-type", "text/plain");
  5979. })
  5980. .Put("/put",
  5981. [&](const Request &req, Response &res) {
  5982. EXPECT_EQ(req.body, "PUT");
  5983. res.set_content(req.body, "text/plain");
  5984. })
  5985. .Put("/put-large",
  5986. [&](const Request &req, Response &res) {
  5987. EXPECT_EQ(req.body, LARGE_DATA);
  5988. res.set_content(req.body, "text/plain");
  5989. })
  5990. .Patch("/patch",
  5991. [&](const Request &req, Response &res) {
  5992. EXPECT_EQ(req.body, "PATCH");
  5993. res.set_content(req.body, "text/plain");
  5994. })
  5995. .Delete("/delete",
  5996. [&](const Request & /*req*/, Response &res) {
  5997. res.set_content("DELETE", "text/plain");
  5998. })
  5999. .Delete("/delete-body",
  6000. [&](const Request &req, Response &res) {
  6001. EXPECT_EQ(req.body, "content");
  6002. res.set_content(req.body, "text/plain");
  6003. })
  6004. .Options(R"(\*)",
  6005. [&](const Request & /*req*/, Response &res) {
  6006. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6007. })
  6008. .CustomRoute("PROPFIND", "/dav/:id",
  6009. [&](const Request &req, Response &res) {
  6010. res.set_header("x-body-size",
  6011. std::to_string(req.body.size()));
  6012. res.set_header("x-matched-route", req.matched_route);
  6013. res.set_header("x-dav-id", req.path_params.at("id"));
  6014. res.status = StatusCode::MultiStatus_207;
  6015. res.set_content(req.body, "application/xml");
  6016. })
  6017. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6018. [&](const Request &req, Response &res) {
  6019. res.set_header("x-dav-match", req.matches[1]);
  6020. res.status = StatusCode::MultiStatus_207;
  6021. })
  6022. .CustomRoute("MKCOL", "/dav-mkcol",
  6023. [&](const Request &req, Response &res) {
  6024. EXPECT_TRUE(req.body.empty());
  6025. res.status = StatusCode::Created_201;
  6026. })
  6027. .CustomRoute(
  6028. "REPORT", "/dav-report",
  6029. [&](const Request & /*req*/, Response &res,
  6030. const ContentReader &content_reader) {
  6031. std::string body;
  6032. content_reader([&](const char *data, size_t data_length) {
  6033. body.append(data, data_length);
  6034. return true;
  6035. });
  6036. res.set_header("x-body-size", std::to_string(body.size()));
  6037. res.status = StatusCode::MultiStatus_207;
  6038. res.set_content(body, "application/xml");
  6039. })
  6040. .Get("/request-target",
  6041. [&](const Request &req, Response & /*res*/) {
  6042. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6043. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6044. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6045. })
  6046. .Get("/long-query-value",
  6047. [&](const Request &req, Response & /*res*/) {
  6048. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6049. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6050. })
  6051. .Get("/too-long-query-value",
  6052. [&](const Request &req, Response & /*res*/) {
  6053. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6054. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6055. })
  6056. .Get("/array-param",
  6057. [&](const Request &req, Response & /*res*/) {
  6058. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6059. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6060. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6061. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6062. })
  6063. .Get("/array-param-values",
  6064. [&](const Request &req, Response & /*res*/) {
  6065. auto values = req.get_param_values("array");
  6066. EXPECT_EQ(3u, values.size());
  6067. EXPECT_EQ("value1", values[0]);
  6068. EXPECT_EQ("value2", values[1]);
  6069. EXPECT_EQ("value3", values[2]);
  6070. auto empty = req.get_param_values("nonexistent");
  6071. EXPECT_TRUE(empty.empty());
  6072. })
  6073. .Post("/validate-no-multiple-headers",
  6074. [&](const Request &req, Response & /*res*/) {
  6075. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6076. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6077. })
  6078. .Post("/content_receiver",
  6079. [&](const Request &req, Response &res,
  6080. const ContentReader &content_reader) {
  6081. if (req.is_multipart_form_data()) {
  6082. std::vector<FormData> items;
  6083. content_reader(
  6084. [&](const FormData &file) {
  6085. items.push_back(file);
  6086. return true;
  6087. },
  6088. [&](const char *data, size_t data_length) {
  6089. items.back().content.append(data, data_length);
  6090. return true;
  6091. });
  6092. EXPECT_EQ(5u, items.size());
  6093. {
  6094. const auto &file = get_file_value(items, "text1");
  6095. EXPECT_TRUE(file.filename.empty());
  6096. EXPECT_EQ("text default", file.content);
  6097. }
  6098. {
  6099. const auto &file = get_file_value(items, "text2");
  6100. EXPECT_TRUE(file.filename.empty());
  6101. EXPECT_EQ("aωb", file.content);
  6102. }
  6103. {
  6104. const auto &file = get_file_value(items, "file1");
  6105. EXPECT_EQ("hello.txt", file.filename);
  6106. EXPECT_EQ("text/plain", file.content_type);
  6107. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6108. }
  6109. {
  6110. const auto &file = get_file_value(items, "file2");
  6111. EXPECT_EQ("world.json", file.filename);
  6112. EXPECT_EQ("application/json", file.content_type);
  6113. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6114. }
  6115. {
  6116. const auto &file = get_file_value(items, "file3");
  6117. EXPECT_TRUE(file.filename.empty());
  6118. EXPECT_EQ("application/octet-stream", file.content_type);
  6119. EXPECT_EQ(0u, file.content.size());
  6120. }
  6121. } else {
  6122. std::string body;
  6123. content_reader([&](const char *data, size_t data_length) {
  6124. EXPECT_EQ(7U, data_length);
  6125. body.append(data, data_length);
  6126. return true;
  6127. });
  6128. EXPECT_EQ(body, "content");
  6129. res.set_content(body, "text/plain");
  6130. }
  6131. })
  6132. .Put("/content_receiver",
  6133. [&](const Request & /*req*/, Response &res,
  6134. const ContentReader &content_reader) {
  6135. std::string body;
  6136. content_reader([&](const char *data, size_t data_length) {
  6137. body.append(data, data_length);
  6138. return true;
  6139. });
  6140. EXPECT_EQ(body, "content");
  6141. res.set_content(body, "text/plain");
  6142. })
  6143. .Patch("/content_receiver",
  6144. [&](const Request & /*req*/, Response &res,
  6145. const ContentReader &content_reader) {
  6146. std::string body;
  6147. content_reader([&](const char *data, size_t data_length) {
  6148. body.append(data, data_length);
  6149. return true;
  6150. });
  6151. EXPECT_EQ(body, "content");
  6152. res.set_content(body, "text/plain");
  6153. })
  6154. .Post("/query-string-and-body",
  6155. [&](const Request &req, Response & /*res*/) {
  6156. ASSERT_TRUE(req.has_param("key"));
  6157. EXPECT_EQ(req.get_param_value("key"), "value");
  6158. EXPECT_EQ(req.body, "content");
  6159. })
  6160. .Get("/last-request",
  6161. [&](const Request &req, Response & /*res*/) {
  6162. EXPECT_EQ("close", req.get_header_value("Connection"));
  6163. })
  6164. .Get(R"(/redirect/(\d+))",
  6165. [&](const Request &req, Response &res) {
  6166. auto num = std::stoi(req.matches[1]) + 1;
  6167. std::string url = "/redirect/" + std::to_string(num);
  6168. res.set_redirect(url);
  6169. })
  6170. .Post("/binary",
  6171. [&](const Request &req, Response &res) {
  6172. EXPECT_EQ(4U, req.body.size());
  6173. EXPECT_EQ("application/octet-stream",
  6174. req.get_header_value("Content-Type"));
  6175. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6176. res.set_content(req.body, "application/octet-stream");
  6177. })
  6178. .Put("/binary",
  6179. [&](const Request &req, Response &res) {
  6180. EXPECT_EQ(4U, req.body.size());
  6181. EXPECT_EQ("application/octet-stream",
  6182. req.get_header_value("Content-Type"));
  6183. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6184. res.set_content(req.body, "application/octet-stream");
  6185. })
  6186. .Patch("/binary",
  6187. [&](const Request &req, Response &res) {
  6188. EXPECT_EQ(4U, req.body.size());
  6189. EXPECT_EQ("application/octet-stream",
  6190. req.get_header_value("Content-Type"));
  6191. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6192. res.set_content(req.body, "application/octet-stream");
  6193. })
  6194. .Delete("/binary",
  6195. [&](const Request &req, Response &res) {
  6196. EXPECT_EQ(4U, req.body.size());
  6197. EXPECT_EQ("application/octet-stream",
  6198. req.get_header_value("Content-Type"));
  6199. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6200. res.set_content(req.body, "application/octet-stream");
  6201. })
  6202. .Get("/issue1772",
  6203. [&](const Request & /*req*/, Response &res) {
  6204. res.status = 401;
  6205. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6206. })
  6207. .Delete("/issue609",
  6208. [](const httplib::Request &, httplib::Response &res,
  6209. const httplib::ContentReader &) {
  6210. res.set_content("ok", "text/plain");
  6211. })
  6212. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6213. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6214. .Get("/compress",
  6215. [&](const Request & /*req*/, Response &res) {
  6216. res.set_content(
  6217. "12345678901234567890123456789012345678901234567890123456789"
  6218. "01234567890123456789012345678901234567890",
  6219. "text/plain");
  6220. })
  6221. .Get("/compress-with-charset",
  6222. [&](const Request & /*req*/, Response &res) {
  6223. res.set_content(
  6224. "12345678901234567890123456789012345678901234567890123456789"
  6225. "01234567890123456789012345678901234567890",
  6226. "application/json; charset=utf-8");
  6227. })
  6228. .Get("/nocompress",
  6229. [&](const Request & /*req*/, Response &res) {
  6230. res.set_content(
  6231. "12345678901234567890123456789012345678901234567890123456789"
  6232. "01234567890123456789012345678901234567890",
  6233. "application/octet-stream");
  6234. })
  6235. .Post("/compress-multipart",
  6236. [&](const Request &req, Response & /*res*/) {
  6237. EXPECT_EQ(2u, req.form.fields.size());
  6238. ASSERT_TRUE(!req.form.has_field("???"));
  6239. {
  6240. const auto &text = req.form.get_field("key1");
  6241. EXPECT_EQ("test", text);
  6242. }
  6243. {
  6244. const auto &text = req.form.get_field("key2");
  6245. EXPECT_EQ("--abcdefg123", text);
  6246. }
  6247. })
  6248. #endif
  6249. ;
  6250. persons_["john"] = "programmer";
  6251. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6252. svr_.wait_until_ready();
  6253. }
  6254. virtual void TearDown() {
  6255. svr_.stop();
  6256. if (!request_threads_.empty()) {
  6257. std::this_thread::sleep_for(std::chrono::seconds(1));
  6258. for (auto &t : request_threads_) {
  6259. t.join();
  6260. }
  6261. }
  6262. t_.join();
  6263. }
  6264. map<string, string> persons_;
  6265. #ifdef CPPHTTPLIB_SSL_ENABLED
  6266. SSLClient cli_;
  6267. SSLServer svr_;
  6268. #else
  6269. Client cli_;
  6270. Server svr_;
  6271. #endif
  6272. thread t_;
  6273. std::vector<thread> request_threads_;
  6274. };
  6275. TEST_F(ServerTest, GetMethod200) {
  6276. auto res = cli_.Get("/hi");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. EXPECT_EQ("HTTP/1.1", res->version);
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("OK", res->reason);
  6281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6282. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6283. EXPECT_EQ("Hello World!", res->body);
  6284. }
  6285. TEST_F(ServerTest, GetEmptyFile) {
  6286. auto res = cli_.Get("/empty_file");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. EXPECT_EQ(StatusCode::OK_200, res->status);
  6289. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6290. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6291. EXPECT_EQ("", res->body);
  6292. }
  6293. TEST_F(ServerTest, GetFileContent) {
  6294. auto res = cli_.Get("/file_content");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::OK_200, res->status);
  6297. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6298. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetFileContentWithRange) {
  6302. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6306. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6307. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6308. EXPECT_EQ("est", res->body);
  6309. }
  6310. TEST_F(ServerTest, GetFileContentWithContentType) {
  6311. auto res = cli_.Get("/file_content_with_content_type");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6316. EXPECT_EQ("file\n", res->body);
  6317. }
  6318. TEST_F(ServerTest, GetInvalidFileContent) {
  6319. auto res = cli_.Get("/invalid_file_content");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6322. }
  6323. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6324. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ("HTTP/1.1", res->version);
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6329. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6330. EXPECT_EQ("Hello World!", res->body);
  6331. }
  6332. TEST_F(ServerTest, GetMethod302) {
  6333. auto res = cli_.Get("/");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::Found_302, res->status);
  6336. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6337. }
  6338. TEST_F(ServerTest, GetMethod302Redirect) {
  6339. cli_.set_follow_location(true);
  6340. auto res = cli_.Get("/");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ("Hello World!", res->body);
  6344. EXPECT_EQ("/hi", res->location);
  6345. }
  6346. TEST_F(ServerTest, GetMethod404) {
  6347. auto res = cli_.Get("/invalid");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6350. }
  6351. TEST_F(ServerTest, HeadMethod200) {
  6352. auto res = cli_.Head("/hi");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::OK_200, res->status);
  6355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6356. EXPECT_TRUE(res->body.empty());
  6357. }
  6358. TEST_F(ServerTest, HeadMethod200Static) {
  6359. auto res = cli_.Head("/mount/dir/index.html");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6363. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6364. EXPECT_TRUE(res->body.empty());
  6365. }
  6366. TEST_F(ServerTest, HeadMethod404) {
  6367. auto res = cli_.Head("/invalid");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6370. EXPECT_TRUE(res->body.empty());
  6371. }
  6372. TEST_F(ServerTest, GetMethodPersonJohn) {
  6373. auto res = cli_.Get("/person/john");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6377. EXPECT_EQ("programmer", res->body);
  6378. }
  6379. TEST_F(ServerTest, PostMethod1) {
  6380. auto res = cli_.Get("/person/john1");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6383. res = cli_.Post("/person", "name=john1&note=coder",
  6384. "application/x-www-form-urlencoded");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. ASSERT_EQ(StatusCode::OK_200, res->status);
  6387. res = cli_.Get("/person/john1");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. ASSERT_EQ(StatusCode::OK_200, res->status);
  6390. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6391. ASSERT_EQ("coder", res->body);
  6392. }
  6393. TEST_F(ServerTest, PostMethod2) {
  6394. auto res = cli_.Get("/person/john2");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6397. Params params;
  6398. params.emplace("name", "john2");
  6399. params.emplace("note", "coder");
  6400. res = cli_.Post("/person", params);
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. ASSERT_EQ(StatusCode::OK_200, res->status);
  6403. res = cli_.Get("/person/john2");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6407. ASSERT_EQ("coder", res->body);
  6408. }
  6409. TEST_F(ServerTest, PutMethod3) {
  6410. auto res = cli_.Get("/person/john3");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6413. Params params;
  6414. params.emplace("name", "john3");
  6415. params.emplace("note", "coder");
  6416. res = cli_.Put("/person", params);
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. res = cli_.Get("/person/john3");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6423. ASSERT_EQ("coder", res->body);
  6424. }
  6425. TEST_F(ServerTest, DeleteMethod1) {
  6426. auto res = cli_.Get("/person/john4");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6429. Params params;
  6430. params.emplace("name", "john4");
  6431. params.emplace("note", "coder");
  6432. res = cli_.Post("/person", params);
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. ASSERT_EQ(StatusCode::OK_200, res->status);
  6435. res = cli_.Get("/person/john4");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. ASSERT_EQ(StatusCode::OK_200, res->status);
  6438. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6439. ASSERT_EQ("coder", res->body);
  6440. Params delete_params;
  6441. delete_params.emplace("name", "john4");
  6442. res = cli_.Delete("/person", delete_params);
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. ASSERT_EQ(StatusCode::OK_200, res->status);
  6445. ASSERT_EQ("DELETED", res->body);
  6446. res = cli_.Get("/person/john4");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6449. }
  6450. TEST_F(ServerTest, DeleteMethod2) {
  6451. auto res = cli_.Get("/person/john5");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6454. Params params;
  6455. params.emplace("name", "john5");
  6456. params.emplace("note", "developer");
  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/john5");
  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("developer", res->body);
  6465. Params delete_params;
  6466. delete_params.emplace("name", "john5");
  6467. Headers headers;
  6468. headers.emplace("Custom-Header", "test-value");
  6469. res = cli_.Delete("/person", headers, delete_params);
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ("DELETED", res->body);
  6473. res = cli_.Get("/person/john5");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6476. }
  6477. TEST_F(ServerTest, DeleteMethod3) {
  6478. auto res = cli_.Get("/person/john6");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6481. Params params;
  6482. params.emplace("name", "john6");
  6483. params.emplace("note", "tester");
  6484. res = cli_.Post("/person", params);
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. res = cli_.Get("/person/john6");
  6488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6489. ASSERT_EQ(StatusCode::OK_200, res->status);
  6490. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6491. ASSERT_EQ("tester", res->body);
  6492. Params delete_params;
  6493. delete_params.emplace("name", "john6");
  6494. Headers headers;
  6495. headers.emplace("Custom-Header", "test-value");
  6496. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. ASSERT_EQ(StatusCode::OK_200, res->status);
  6499. ASSERT_EQ("DELETED", res->body);
  6500. res = cli_.Get("/person/john6");
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6503. }
  6504. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6505. Params params;
  6506. params.emplace("json", JSON_DATA);
  6507. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(JSON_DATA, res->body);
  6511. }
  6512. TEST_F(ServerTest, PostEmptyContent) {
  6513. auto res = cli_.Post("/empty", "", "text/plain");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. ASSERT_EQ(StatusCode::OK_200, res->status);
  6516. ASSERT_EQ("empty", res->body);
  6517. }
  6518. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6519. auto res = cli_.Post("/empty-no-content-type");
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. ASSERT_EQ(StatusCode::OK_200, res->status);
  6522. ASSERT_EQ("empty-no-content-type", res->body);
  6523. }
  6524. TEST_F(ServerTest, PostPathOnly) {
  6525. auto res = cli_.Post("/path-only");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. ASSERT_EQ(StatusCode::OK_200, res->status);
  6528. ASSERT_EQ("path-only", res->body);
  6529. }
  6530. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6531. auto res = cli_.Post("/path-headers-only",
  6532. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::OK_200, res->status);
  6535. ASSERT_EQ("path-headers-only", res->body);
  6536. }
  6537. TEST_F(ServerTest, PostLarge) {
  6538. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. ASSERT_EQ(StatusCode::OK_200, res->status);
  6541. EXPECT_EQ(LARGE_DATA, res->body);
  6542. }
  6543. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6544. auto res = cli_.Put("/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, GetMethodDir) {
  6550. auto res = cli_.Get("/dir/");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6554. auto body = R"(<html>
  6555. <head>
  6556. </head>
  6557. <body>
  6558. <a href="/dir/test.html">Test</a>
  6559. <a href="/hi">hi</a>
  6560. </body>
  6561. </html>
  6562. )";
  6563. EXPECT_EQ(body, res->body);
  6564. }
  6565. TEST_F(ServerTest, GetMethodDirTest) {
  6566. auto res = cli_.Get("/dir/test.html");
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6570. EXPECT_EQ("test.html", res->body);
  6571. }
  6572. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6573. auto res = cli_.Get("/dir/../dir/test.html");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6576. }
  6577. TEST_F(ServerTest, GetMethodInvalidPath) {
  6578. auto res = cli_.Get("/dir/../test.html");
  6579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6581. }
  6582. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6583. auto res = cli_.Get("/../www/dir/test.html");
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6586. }
  6587. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6588. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6591. }
  6592. TEST_F(ServerTest, GetMethodDirMountTest) {
  6593. auto res = cli_.Get("/mount/dir/test.html");
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. EXPECT_EQ(StatusCode::OK_200, res->status);
  6596. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6597. EXPECT_EQ("test.html", res->body);
  6598. }
  6599. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6600. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6603. }
  6604. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6605. auto res = cli_.Get("/mount/dir/../test.html");
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6608. }
  6609. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6610. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6613. }
  6614. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6615. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6618. }
  6619. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6620. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6623. }
  6624. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6625. auto res = cli_.Get("/mount/%2e%2e%5c/www2/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, GetMethodDirMountWithoutTrailingSlash) {
  6630. auto res = cli_.Get("/mount/dir");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6633. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6634. }
  6635. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6636. auto res = cli_.Get("//dir");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6639. EXPECT_FALSE(res->has_header("Location"));
  6640. }
  6641. TEST_F(ServerTest, PostMethod303) {
  6642. auto res = cli_.Post("/1", "body", "text/plain");
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6645. EXPECT_EQ("/2", res->get_header_value("Location"));
  6646. }
  6647. TEST_F(ServerTest, PostMethod303Redirect) {
  6648. cli_.set_follow_location(true);
  6649. auto res = cli_.Post("/1", "body", "text/plain");
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. EXPECT_EQ("redirected.", res->body);
  6653. EXPECT_EQ("/2", res->location);
  6654. }
  6655. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6656. auto res = cli_.Get("/dir/test.abcde");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6660. EXPECT_EQ("abcde", res->body);
  6661. }
  6662. TEST_F(ServerTest, StaticFileRange) {
  6663. auto res =
  6664. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6667. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6668. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(true, res->has_header("Content-Range"));
  6670. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6671. EXPECT_EQ(std::string("cd"), res->body);
  6672. }
  6673. TEST_F(ServerTest, StaticFileRanges) {
  6674. auto res = cli_.Get("/dir/test.abcde",
  6675. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6678. EXPECT_TRUE(
  6679. res->get_header_value("Content-Type")
  6680. .find(
  6681. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6682. 0);
  6683. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6684. }
  6685. TEST_F(ServerTest, StaticFileRangeHead) {
  6686. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6689. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6690. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6691. EXPECT_EQ(true, res->has_header("Content-Range"));
  6692. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6693. }
  6694. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6695. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6699. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6700. EXPECT_EQ(true, res->has_header("Content-Range"));
  6701. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6702. res->get_header_value("Content-Range"));
  6703. EXPECT_EQ("LAST\n", res->body);
  6704. }
  6705. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6706. auto res =
  6707. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6711. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6712. EXPECT_EQ(true, res->has_header("Content-Range"));
  6713. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6714. }
  6715. TEST_F(ServerTest, StaticFileBigFile) {
  6716. auto res = cli_.Get("/dir/1MB.txt");
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::OK_200, res->status);
  6719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6720. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6721. }
  6722. TEST_F(ServerTest, InvalidBaseDirMount) {
  6723. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6724. }
  6725. TEST_F(ServerTest, Binary) {
  6726. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6727. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6728. "application/octet-stream");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. ASSERT_EQ(StatusCode::OK_200, res->status);
  6731. ASSERT_EQ(4U, res->body.size());
  6732. res = cli_.Put("/binary", binary.data(), binary.size(),
  6733. "application/octet-stream");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. ASSERT_EQ(StatusCode::OK_200, res->status);
  6736. ASSERT_EQ(4U, res->body.size());
  6737. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6738. "application/octet-stream");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. ASSERT_EQ(StatusCode::OK_200, res->status);
  6741. ASSERT_EQ(4U, res->body.size());
  6742. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6743. "application/octet-stream");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. ASSERT_EQ(StatusCode::OK_200, res->status);
  6746. ASSERT_EQ(4U, res->body.size());
  6747. }
  6748. TEST_F(ServerTest, BinaryString) {
  6749. auto binary = std::string("\x00\x01\x02\x03", 4);
  6750. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. ASSERT_EQ(StatusCode::OK_200, res->status);
  6753. ASSERT_EQ(4U, res->body.size());
  6754. res = cli_.Put("/binary", binary, "application/octet-stream");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. ASSERT_EQ(StatusCode::OK_200, res->status);
  6757. ASSERT_EQ(4U, res->body.size());
  6758. res = cli_.Patch("/binary", binary, "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_.Delete("/binary", binary, "application/octet-stream");
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. ASSERT_EQ(StatusCode::OK_200, res->status);
  6765. ASSERT_EQ(4U, res->body.size());
  6766. }
  6767. TEST_F(ServerTest, EmptyRequest) {
  6768. auto res = cli_.Get("");
  6769. ASSERT_TRUE(!res);
  6770. EXPECT_EQ(Error::Connection, res.error());
  6771. }
  6772. TEST_F(ServerTest, LongRequest) {
  6773. std::string request;
  6774. for (size_t i = 0; i < 545; i++) {
  6775. request += "/TooLongRequest";
  6776. }
  6777. request += "OK";
  6778. auto res = cli_.Get(request.c_str());
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6781. }
  6782. TEST_F(ServerTest, TooLongRequest) {
  6783. std::string request;
  6784. for (size_t i = 0; i < 546; i++) {
  6785. request += "/TooLongRequest";
  6786. }
  6787. request += "_NG";
  6788. auto start = std::chrono::high_resolution_clock::now();
  6789. cli_.set_keep_alive(true);
  6790. auto res = cli_.Get(request.c_str());
  6791. auto end = std::chrono::high_resolution_clock::now();
  6792. auto elapsed =
  6793. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6794. .count();
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6797. EXPECT_LE(elapsed, 1000);
  6798. EXPECT_EQ("close", res->get_header_value("Connection"));
  6799. EXPECT_FALSE(cli_.is_socket_open());
  6800. }
  6801. TEST_F(ServerTest, AlmostTooLongRequest) {
  6802. // test for #2046 - URI length check shouldn't include other content on req
  6803. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6804. // leading /, space, HTTP/1.1)
  6805. std::string request =
  6806. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6807. auto res = cli_.Get(request.c_str());
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6810. }
  6811. TEST_F(ServerTest, LongHeader) {
  6812. Request req;
  6813. req.method = "GET";
  6814. req.path = "/hi";
  6815. std::string host_and_port;
  6816. host_and_port += HOST;
  6817. host_and_port += ":";
  6818. host_and_port += std::to_string(PORT);
  6819. req.headers.emplace("Host", host_and_port.c_str());
  6820. req.headers.emplace("Accept", "*/*");
  6821. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6822. req.headers.emplace(
  6823. "Header-Name",
  6824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6852. "@@@@@@@@@@@@@@@@");
  6853. auto res = std::make_shared<Response>();
  6854. auto error = Error::Success;
  6855. auto ret = cli_.send(req, *res, error);
  6856. ASSERT_TRUE(ret);
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST_F(ServerTest, LongQueryValue) {
  6860. auto start = std::chrono::high_resolution_clock::now();
  6861. cli_.set_keep_alive(true);
  6862. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6863. auto end = std::chrono::high_resolution_clock::now();
  6864. auto elapsed =
  6865. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6866. .count();
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6869. EXPECT_LE(elapsed, 1000);
  6870. EXPECT_EQ("close", res->get_header_value("Connection"));
  6871. EXPECT_FALSE(cli_.is_socket_open());
  6872. }
  6873. TEST_F(ServerTest, TooLongQueryValue) {
  6874. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6875. ASSERT_FALSE(res);
  6876. EXPECT_EQ(Error::Read, res.error());
  6877. }
  6878. TEST_F(ServerTest, TooLongHeader) {
  6879. Request req;
  6880. req.method = "GET";
  6881. req.path = "/hi";
  6882. std::string host_and_port;
  6883. host_and_port += HOST;
  6884. host_and_port += ":";
  6885. host_and_port += std::to_string(PORT);
  6886. req.headers.emplace("Host", host_and_port.c_str());
  6887. req.headers.emplace("Accept", "*/*");
  6888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6889. req.headers.emplace(
  6890. "Header-Name",
  6891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6894. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6895. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6919. "@@@@@@@@@@@@@@@@@");
  6920. auto res = std::make_shared<Response>();
  6921. auto error = Error::Success;
  6922. auto ret = cli_.send(req, *res, error);
  6923. ASSERT_TRUE(ret);
  6924. EXPECT_EQ(StatusCode::OK_200, res->status);
  6925. }
  6926. TEST_F(ServerTest, HeaderCountAtLimit) {
  6927. // Test with headers just under the 100 limit
  6928. httplib::Headers headers;
  6929. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6930. // This should keep us just under the 100 header limit
  6931. for (int i = 0; i < 95; i++) {
  6932. std::string name = "X-Test-Header-" + std::to_string(i);
  6933. std::string value = "value" + std::to_string(i);
  6934. headers.emplace(name, value);
  6935. }
  6936. // This should work fine as we're under the limit
  6937. auto res = cli_.Get("/hi", headers);
  6938. EXPECT_TRUE(res);
  6939. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6940. }
  6941. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6942. // Test with many headers to exceed the 100 limit
  6943. httplib::Headers headers;
  6944. // Add 150 headers to definitely exceed the 100 limit
  6945. for (int i = 0; i < 150; i++) {
  6946. std::string name = "X-Test-Header-" + std::to_string(i);
  6947. std::string value = "value" + std::to_string(i);
  6948. headers.emplace(name, value);
  6949. }
  6950. // This should fail due to exceeding header count limit
  6951. cli_.set_keep_alive(true);
  6952. auto res = cli_.Get("/hi", headers);
  6953. // The server should respond with 400 Bad Request
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6956. EXPECT_EQ("close", res->get_header_value("Connection"));
  6957. EXPECT_FALSE(cli_.is_socket_open());
  6958. }
  6959. TEST_F(ServerTest, PercentEncoding) {
  6960. auto res = cli_.Get("/e%6edwith%");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. }
  6964. TEST_F(ServerTest, PercentEncodingUnicode) {
  6965. auto res = cli_.Get("/e%u006edwith%");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. }
  6969. TEST_F(ServerTest, InvalidPercentEncoding) {
  6970. auto res = cli_.Get("/%endwith%");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6973. }
  6974. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6975. auto res = cli_.Get("/%uendwith%");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6978. }
  6979. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6980. auto res = cli_.Get("/hello?aaa=bbb%");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6983. }
  6984. TEST_F(ServerTest, PlusSignEncoding) {
  6985. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::OK_200, res->status);
  6988. EXPECT_EQ("a +b", res->body);
  6989. }
  6990. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6991. // This test simulates a potential DoS attack using many headers
  6992. // to verify our security fix prevents memory exhaustion
  6993. httplib::Headers attack_headers;
  6994. // Attempt to add many headers like an attacker would (200 headers to far
  6995. // exceed limit)
  6996. for (int i = 0; i < 200; i++) {
  6997. std::string name = "X-Attack-Header-" + std::to_string(i);
  6998. std::string value = "attack_payload_" + std::to_string(i);
  6999. attack_headers.emplace(name, value);
  7000. }
  7001. // Try to POST with excessive headers
  7002. cli_.set_keep_alive(true);
  7003. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7004. // Should either fail or return 400 Bad Request due to security limit
  7005. if (res) {
  7006. // If we get a response, it should be 400 Bad Request
  7007. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7008. EXPECT_EQ("close", res->get_header_value("Connection"));
  7009. }
  7010. EXPECT_FALSE(cli_.is_socket_open());
  7011. }
  7012. TEST_F(ServerTest, MultipartFormData) {
  7013. UploadFormDataItems items = {
  7014. {"text1", "text default", "", ""},
  7015. {"text2", "aωb", "", ""},
  7016. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7017. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7018. {"file3", "", "", "application/octet-stream"},
  7019. {"file4", "", "", " application/json tmp-string "}};
  7020. auto res = cli_.Post("/multipart", items);
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::OK_200, res->status);
  7023. }
  7024. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7025. UploadFormDataItems items = {
  7026. {"text", "default text", "", ""},
  7027. {"multi_text1", "aaaaa", "", ""},
  7028. {"multi_text1", "bbbbb", "", ""},
  7029. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7030. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7031. "application/json"},
  7032. };
  7033. auto res = cli_.Post("/multipart/multi_file_values", items);
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7038. auto res = cli_.Get("/hi");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7042. EXPECT_EQ("Hello World!", res->body);
  7043. }
  7044. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7045. Request req;
  7046. req.method = "POST";
  7047. req.path = "/chunked";
  7048. std::string host_and_port;
  7049. host_and_port += HOST;
  7050. host_and_port += ":";
  7051. host_and_port += std::to_string(PORT);
  7052. req.headers.emplace("Host", host_and_port.c_str());
  7053. req.headers.emplace("Accept", "*/*");
  7054. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7055. req.headers.emplace("Content-Type", "text/plain");
  7056. req.headers.emplace("Content-Length", "0");
  7057. req.headers.emplace(
  7058. "Transfer-Encoding",
  7059. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7060. // Client does not chunk, so make a chunked body manually.
  7061. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7062. auto res = std::make_shared<Response>();
  7063. auto error = Error::Success;
  7064. auto ret = cli_.send(req, *res, error);
  7065. ASSERT_TRUE(ret);
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. }
  7068. template <typename ClientT>
  7069. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7070. int expected_status) {
  7071. Request req;
  7072. req.method = "POST";
  7073. req.path = "/chunked";
  7074. std::string host_and_port;
  7075. host_and_port += HOST;
  7076. host_and_port += ":";
  7077. host_and_port += std::to_string(PORT);
  7078. req.headers.emplace("Host", host_and_port.c_str());
  7079. req.headers.emplace("Content-Length", "0");
  7080. req.headers.emplace("Transfer-Encoding", "chunked");
  7081. req.body = body;
  7082. auto res = std::make_shared<Response>();
  7083. auto error = Error::Success;
  7084. ASSERT_TRUE(cli.send(req, *res, error));
  7085. EXPECT_EQ(expected_status, res->status);
  7086. }
  7087. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7088. // rather than treat them as valid lengths.
  7089. template <typename ClientT>
  7090. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7091. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7092. }
  7093. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7094. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7095. }
  7096. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7097. expect_chunked_body_rejected(
  7098. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7099. }
  7100. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7101. // chunk-size line carries no CR, LF or other control character ahead of its
  7102. // terminator. Such a line must be refused rather than read as extension text.
  7103. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7104. expect_chunked_body_rejected(
  7105. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7106. }
  7107. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7108. expect_chunked_body_rejected(
  7109. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7110. }
  7111. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7112. expect_chunked_body_rejected(
  7113. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7114. }
  7115. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7116. // The literal stays split: a hex escape consumes every hex digit that
  7117. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7118. expect_chunked_body_rejected(
  7119. cli_, "4;a\x01"
  7120. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7121. }
  7122. // The bytes around chunk data are no payload, so they cannot ride on the
  7123. // payload limit
  7124. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7125. // Small enough that the whole request is sent before the server turns it
  7126. // down, yet past the limit by the last chunks
  7127. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7128. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7129. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7130. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7131. SCOPED_TRACE(size_line.substr(0, 2));
  7132. std::string body;
  7133. for (auto c : std::string("dechunked post body")) {
  7134. body += size_line + "\r\n" + c + "\r\n";
  7135. }
  7136. body += "0\r\n\r\n";
  7137. expect_chunked_body_rejected(cli_, body.c_str());
  7138. }
  7139. }
  7140. TEST_F(ServerTest, AcceptsChunkExtension) {
  7141. expect_chunked_body_status(cli_,
  7142. "4;name=value\r\ndech\r\n"
  7143. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7144. "0;last\r\n\r\n",
  7145. StatusCode::OK_200);
  7146. }
  7147. TEST_F(ServerTest, GetStreamed2) {
  7148. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("ab"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetStreamed) {
  7157. auto res = cli_.Get("/streamed");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7161. EXPECT_EQ(std::string("aaabbb"), res->body);
  7162. }
  7163. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7164. auto res = cli_.Get("/streamed-without-length",
  7165. Headers{make_range_header({{0, -1}})});
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::OK_200, res->status);
  7168. EXPECT_EQ(false, res->has_header("Content-Length"));
  7169. EXPECT_EQ(false, res->has_header("Content-Range"));
  7170. EXPECT_EQ(std::string("abcdefg"), res->body);
  7171. }
  7172. TEST_F(ServerTest, GetStreamedWithRange1) {
  7173. auto res =
  7174. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7177. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7178. EXPECT_EQ(true, res->has_header("Content-Range"));
  7179. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7180. EXPECT_EQ(std::string("def"), res->body);
  7181. }
  7182. TEST_F(ServerTest, GetStreamedWithRange2) {
  7183. auto res =
  7184. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("bcdefg"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7193. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7196. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7197. EXPECT_EQ(true, res->has_header("Content-Range"));
  7198. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7199. EXPECT_EQ(std::string("efg"), res->body);
  7200. }
  7201. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7202. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7203. // the entire representation.
  7204. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7205. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7208. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7209. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7210. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7211. }
  7212. }
  7213. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7214. auto res =
  7215. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7218. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(0U, res->body.size());
  7221. }
  7222. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7223. // Only a 206 is served as a partial representation. Under any other status
  7224. // `apply_ranges()` reported the full content length, so the body must match
  7225. // that header, and the content provider must never be asked for an offset
  7226. // outside the representation.
  7227. auto check = [&](int status, const char *range) {
  7228. auto path =
  7229. std::string("/streamed-with-range?status=") + std::to_string(status);
  7230. auto ctx = path + " Range: " + range;
  7231. auto res = cli_.Get(path, Headers{{"Range", range}});
  7232. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7233. EXPECT_EQ(status, res->status) << ctx;
  7234. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7236. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7237. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7238. };
  7239. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7240. check(403, "bytes=3-5");
  7241. // The offset is far past the representation.
  7242. check(403, "bytes=100000-100200");
  7243. // `first_pos` is still -1 here, and the bounds asserts in
  7244. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7245. check(403, "bytes=-3");
  7246. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7247. // multipart branch would have written one that is empty.
  7248. check(403, "bytes=1-2, 4-5");
  7249. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7250. // covers the whole representation.
  7251. check(200, "bytes=3-5");
  7252. check(200, "bytes=1-2, 4-5");
  7253. }
  7254. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7255. auto res =
  7256. cli_.Get("/streamed-with-range",
  7257. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7258. "92233720368547758079223372036854775807"}});
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7262. EXPECT_EQ(false, res->has_header("Content-Range"));
  7263. EXPECT_EQ(0U, res->body.size());
  7264. }
  7265. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7266. auto res = cli_.Get(
  7267. "/with-range",
  7268. Headers{{"Range",
  7269. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7270. {"Accept-Encoding", ""}});
  7271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7274. EXPECT_EQ(true, res->has_header("Content-Range"));
  7275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7276. EXPECT_EQ(std::string("abcdefg"), res->body);
  7277. }
  7278. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7279. auto res = cli_.Get("/with-range", Headers{
  7280. {"Range", "bytes=0-"},
  7281. {"Accept-Encoding", ""},
  7282. });
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7285. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7286. EXPECT_EQ(true, res->has_header("Content-Range"));
  7287. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7288. EXPECT_EQ(std::string("abcdefg"), res->body);
  7289. }
  7290. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7291. auto res = cli_.Get("/streamed-with-range",
  7292. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7295. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7296. EXPECT_EQ(false, res->has_header("Content-Range"));
  7297. EXPECT_EQ(267U, res->body.size());
  7298. // Check that both range contents are present
  7299. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7300. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7301. // Check that Content-Range headers are present for both ranges
  7302. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7303. std::string::npos);
  7304. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7305. std::string::npos);
  7306. }
  7307. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7308. Ranges ranges;
  7309. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7310. ranges.emplace_back(0, -1);
  7311. }
  7312. auto res = cli_.Get("/streamed-with-range?error",
  7313. Headers{{make_range_header(ranges)}});
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7316. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7317. EXPECT_EQ(false, res->has_header("Content-Range"));
  7318. EXPECT_EQ(0U, res->body.size());
  7319. }
  7320. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7321. auto res = cli_.Get("/streamed-with-range",
  7322. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7325. EXPECT_EQ(5U, res->body.size());
  7326. // Check that overlapping ranges are coalesced into a single range
  7327. EXPECT_EQ("bcdef", res->body);
  7328. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7329. // Should be single range, not multipart
  7330. EXPECT_TRUE(res->has_header("Content-Range"));
  7331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7332. }
  7333. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7334. auto res = cli_.Get("/streamed-with-range",
  7335. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7338. EXPECT_EQ(268U, res->body.size());
  7339. // Check that both range contents are present
  7340. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7341. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7342. // Check that Content-Range headers are present for both ranges
  7343. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7344. std::string::npos);
  7345. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7346. std::string::npos);
  7347. }
  7348. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7349. auto res = cli_.Get("/streamed-with-range",
  7350. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7353. EXPECT_EQ(269U, res->body.size());
  7354. // Check that both duplicate range contents are present
  7355. size_t first_abc = res->body.find("abc\r\n");
  7356. EXPECT_TRUE(first_abc != std::string::npos);
  7357. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7358. EXPECT_TRUE(second_abc != std::string::npos);
  7359. // Check that Content-Range headers are present for both ranges
  7360. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7361. EXPECT_TRUE(first_range != std::string::npos);
  7362. size_t second_range =
  7363. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7364. EXPECT_TRUE(second_range != std::string::npos);
  7365. }
  7366. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7367. auto res =
  7368. cli_.Get("/streamed-with-range?error",
  7369. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7372. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7373. EXPECT_EQ(false, res->has_header("Content-Range"));
  7374. EXPECT_EQ(0U, res->body.size());
  7375. }
  7376. TEST_F(ServerTest, GetStreamedEndless) {
  7377. uint64_t offset = 0;
  7378. auto res = cli_.Get("/streamed-cancel",
  7379. [&](const char * /*data*/, uint64_t data_length) {
  7380. if (offset < 100) {
  7381. offset += data_length;
  7382. return true;
  7383. }
  7384. return false;
  7385. });
  7386. ASSERT_TRUE(!res);
  7387. EXPECT_EQ(Error::Canceled, res.error());
  7388. }
  7389. TEST_F(ServerTest, ClientStop) {
  7390. std::atomic_size_t count{4};
  7391. std::vector<std::thread> threads;
  7392. for (auto i = count.load(); i != 0; --i) {
  7393. threads.emplace_back([&]() {
  7394. auto res = cli_.Get("/streamed-cancel",
  7395. [&](const char *, uint64_t) { return true; });
  7396. --count;
  7397. ASSERT_TRUE(!res);
  7398. EXPECT_TRUE(res.error() == Error::Canceled ||
  7399. res.error() == Error::Read || res.error() == Error::Write);
  7400. });
  7401. }
  7402. std::this_thread::sleep_for(std::chrono::seconds(2));
  7403. while (count != 0) {
  7404. cli_.stop();
  7405. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7406. }
  7407. for (auto &t : threads) {
  7408. t.join();
  7409. }
  7410. }
  7411. TEST_F(ServerTest, GetWithRange1) {
  7412. auto res = cli_.Get("/with-range", Headers{
  7413. make_range_header({{3, 5}}),
  7414. {"Accept-Encoding", ""},
  7415. });
  7416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7418. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7419. EXPECT_EQ(true, res->has_header("Content-Range"));
  7420. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7421. EXPECT_EQ(std::string("def"), res->body);
  7422. }
  7423. TEST_F(ServerTest, GetWithRange2) {
  7424. auto res = cli_.Get("/with-range", Headers{
  7425. make_range_header({{1, -1}}),
  7426. {"Accept-Encoding", ""},
  7427. });
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7430. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7431. EXPECT_EQ(true, res->has_header("Content-Range"));
  7432. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7433. EXPECT_EQ(std::string("bcdefg"), res->body);
  7434. }
  7435. TEST_F(ServerTest, GetWithRange3) {
  7436. auto res = cli_.Get("/with-range", Headers{
  7437. make_range_header({{0, 0}}),
  7438. {"Accept-Encoding", ""},
  7439. });
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7442. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7443. EXPECT_EQ(true, res->has_header("Content-Range"));
  7444. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7445. EXPECT_EQ(std::string("a"), res->body);
  7446. }
  7447. TEST_F(ServerTest, GetWithRange4) {
  7448. auto res = cli_.Get("/with-range", Headers{
  7449. make_range_header({{-1, 2}}),
  7450. {"Accept-Encoding", ""},
  7451. });
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7454. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7455. EXPECT_EQ(true, res->has_header("Content-Range"));
  7456. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7457. EXPECT_EQ(std::string("fg"), res->body);
  7458. }
  7459. TEST_F(ServerTest, GetWithRange5) {
  7460. auto res = cli_.Get("/with-range", Headers{
  7461. make_range_header({{0, 5}}),
  7462. {"Accept-Encoding", ""},
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7466. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7467. EXPECT_EQ(true, res->has_header("Content-Range"));
  7468. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7469. EXPECT_EQ(std::string("abcdef"), res->body);
  7470. }
  7471. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7472. auto res =
  7473. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7476. }
  7477. TEST_F(ServerTest, GetWithRangeMultipart) {
  7478. auto res =
  7479. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7482. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7483. EXPECT_EQ(false, res->has_header("Content-Range"));
  7484. EXPECT_EQ(267U, res->body.size());
  7485. }
  7486. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7487. auto res = cli_.Get("/with-range",
  7488. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7491. }
  7492. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7493. auto res = cli_.Get("/with-range-customized-response",
  7494. Headers{{make_range_header({{1, 2}})}});
  7495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7496. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7497. EXPECT_EQ(true, res->has_header("Content-Length"));
  7498. EXPECT_EQ(false, res->has_header("Content-Range"));
  7499. EXPECT_EQ(JSON_DATA, res->body);
  7500. }
  7501. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7502. auto res = cli_.Get("/with-range-customized-response",
  7503. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7505. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7506. EXPECT_EQ(true, res->has_header("Content-Length"));
  7507. EXPECT_EQ(false, res->has_header("Content-Range"));
  7508. EXPECT_EQ(JSON_DATA, res->body);
  7509. }
  7510. TEST_F(ServerTest, Issue1772) {
  7511. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7514. }
  7515. TEST_F(ServerTest, Issue609) {
  7516. auto res = cli_.Delete("/issue609");
  7517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7518. EXPECT_EQ(StatusCode::OK_200, res->status);
  7519. EXPECT_EQ(std::string("ok"), res->body);
  7520. }
  7521. TEST_F(ServerTest, GetStreamedChunked) {
  7522. auto res = cli_.Get("/streamed-chunked");
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. EXPECT_EQ(std::string("123456789"), res->body);
  7526. }
  7527. TEST_F(ServerTest, GetStreamedChunked2) {
  7528. auto res = cli_.Get("/streamed-chunked2");
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. EXPECT_EQ(std::string("123456789"), res->body);
  7532. }
  7533. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7534. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. EXPECT_EQ(std::string("123456789"), res->body);
  7538. EXPECT_TRUE(res->has_header("Trailer"));
  7539. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7540. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7541. // Trailers are now stored separately from headers (security fix)
  7542. EXPECT_EQ(2U, res->trailers.size());
  7543. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7544. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7545. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7546. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7547. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7548. // Verify trailers are NOT in headers (security verification)
  7549. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7550. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7551. }
  7552. TEST_F(ServerTest, LargeChunkedPost) {
  7553. Request req;
  7554. req.method = "POST";
  7555. req.path = "/large-chunked";
  7556. std::string host_and_port;
  7557. host_and_port += HOST;
  7558. host_and_port += ":";
  7559. host_and_port += std::to_string(PORT);
  7560. req.headers.emplace("Host", host_and_port.c_str());
  7561. req.headers.emplace("Accept", "*/*");
  7562. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7563. req.headers.emplace("Content-Type", "text/plain");
  7564. req.headers.emplace("Content-Length", "0");
  7565. req.headers.emplace("Transfer-Encoding", "chunked");
  7566. std::string long_string(30 * 1024u, 'a');
  7567. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7568. // Attempt to make a large enough post to exceed OS buffers, to test that
  7569. // the server handles short reads if the full chunk data isn't available.
  7570. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7571. auto res = std::make_shared<Response>();
  7572. auto error = Error::Success;
  7573. auto ret = cli_.send(req, *res, error);
  7574. ASSERT_TRUE(ret);
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7578. auto res = cli_.Get("/remote_addr");
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_EQ(StatusCode::OK_200, res->status);
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7583. }
  7584. TEST_F(ServerTest, GetMethodLocalAddr) {
  7585. auto res = cli_.Get("/local_addr");
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7589. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7590. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7591. }
  7592. TEST_F(ServerTest, HTTPResponseSplitting) {
  7593. auto res = cli_.Get("/http_response_splitting");
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. }
  7597. TEST_F(ServerTest, SlowRequest) {
  7598. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7599. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7600. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7601. }
  7602. #if 0
  7603. TEST_F(ServerTest, SlowPost) {
  7604. char buffer[64 * 1024];
  7605. memset(buffer, 0x42, sizeof(buffer));
  7606. auto res = cli_.Post(
  7607. "/slowpost", 64 * 1024 * 1024,
  7608. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7609. auto ret = sink.write(buffer, sizeof(buffer));
  7610. EXPECT_TRUE(ret);
  7611. return true;
  7612. },
  7613. "text/plain");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST_F(ServerTest, SlowPostFail) {
  7618. char buffer[64 * 1024];
  7619. memset(buffer, 0x42, sizeof(buffer));
  7620. cli_.set_write_timeout(std::chrono::seconds(0));
  7621. auto res = cli_.Post(
  7622. "/slowpost", 64 * 1024 * 1024,
  7623. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7624. sink.write(buffer, sizeof(buffer));
  7625. return true;
  7626. },
  7627. "text/plain");
  7628. ASSERT_TRUE(!res);
  7629. EXPECT_EQ(Error::Write, res.error());
  7630. }
  7631. #endif
  7632. TEST_F(ServerTest, Put) {
  7633. auto res = cli_.Put("/put", "PUT", "text/plain");
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("PUT", res->body);
  7637. }
  7638. TEST_F(ServerTest, PutWithContentProvider) {
  7639. auto res = cli_.Put(
  7640. "/put", 3,
  7641. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7642. sink.os << "PUT";
  7643. return true;
  7644. },
  7645. "text/plain");
  7646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7647. EXPECT_EQ(StatusCode::OK_200, res->status);
  7648. EXPECT_EQ("PUT", res->body);
  7649. }
  7650. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7651. auto res = cli_.Post(
  7652. "/post", 42,
  7653. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7654. return false;
  7655. },
  7656. "text/plain");
  7657. ASSERT_TRUE(!res);
  7658. EXPECT_EQ(Error::Canceled, res.error());
  7659. }
  7660. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7661. auto res = cli_.Put(
  7662. "/put",
  7663. [](size_t /*offset*/, DataSink &sink) {
  7664. sink.os << "PUT";
  7665. sink.done();
  7666. return true;
  7667. },
  7668. "text/plain");
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. EXPECT_EQ("PUT", res->body);
  7672. }
  7673. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7674. auto res = cli_.Post(
  7675. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7676. "text/plain");
  7677. ASSERT_TRUE(!res);
  7678. EXPECT_EQ(Error::Canceled, res.error());
  7679. }
  7680. TEST_F(ServerTest, PostLoopBack) {
  7681. std::string body;
  7682. auto res = cli_.Post(
  7683. "/post-loopback", 9,
  7684. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7685. EXPECT_EQ(9u, length);
  7686. sink.write("123", 3);
  7687. sink.write("456", 3);
  7688. sink.write("789", 3);
  7689. return true;
  7690. },
  7691. "text/plain",
  7692. [&body](const char *data, size_t data_length) {
  7693. body.append(data, data_length);
  7694. return true;
  7695. });
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("123456789", body);
  7699. }
  7700. TEST_F(ServerTest, PutLoopBack) {
  7701. std::string body;
  7702. auto res = cli_.Put(
  7703. "/put-loopback", 9,
  7704. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7705. EXPECT_EQ(9u, length);
  7706. sink.write("123", 3);
  7707. sink.write("456", 3);
  7708. sink.write("789", 3);
  7709. return true;
  7710. },
  7711. "text/plain",
  7712. [&body](const char *data, size_t data_length) {
  7713. body.append(data, data_length);
  7714. return true;
  7715. });
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::OK_200, res->status);
  7718. EXPECT_EQ("123456789", body);
  7719. }
  7720. TEST_F(ServerTest, PatchLoopBack) {
  7721. std::string body;
  7722. auto res = cli_.Patch(
  7723. "/patch-loopback", 9,
  7724. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7725. EXPECT_EQ(9u, length);
  7726. sink.write("123", 3);
  7727. sink.write("456", 3);
  7728. sink.write("789", 3);
  7729. return true;
  7730. },
  7731. "text/plain",
  7732. [&body](const char *data, size_t data_length) {
  7733. body.append(data, data_length);
  7734. return true;
  7735. });
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("123456789", body);
  7739. }
  7740. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7741. std::string body;
  7742. auto res = cli_.Post(
  7743. "/post-loopback",
  7744. [](size_t /*offset*/, DataSink &sink) {
  7745. sink.write("123", 3);
  7746. sink.write("456", 3);
  7747. sink.write("789", 3);
  7748. sink.done();
  7749. return true;
  7750. },
  7751. "text/plain",
  7752. [&body](const char *data, size_t data_length) {
  7753. body.append(data, data_length);
  7754. return true;
  7755. });
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("123456789", body);
  7759. }
  7760. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7761. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7762. cli_.set_compress(true);
  7763. auto res = cli_.Put(
  7764. "/put", 3,
  7765. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7766. sink.os << "PUT";
  7767. return true;
  7768. },
  7769. "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ("PUT", res->body);
  7773. }
  7774. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7775. cli_.set_compress(true);
  7776. auto res = cli_.Post(
  7777. "/post", 42,
  7778. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7779. return false;
  7780. },
  7781. "text/plain");
  7782. ASSERT_TRUE(!res);
  7783. EXPECT_EQ(Error::Canceled, res.error());
  7784. }
  7785. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7786. cli_.set_compress(true);
  7787. auto res = cli_.Put(
  7788. "/put",
  7789. [](size_t /*offset*/, DataSink &sink) {
  7790. sink.os << "PUT";
  7791. sink.done();
  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, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7800. cli_.set_compress(true);
  7801. auto res = cli_.Post(
  7802. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7803. "text/plain");
  7804. ASSERT_TRUE(!res);
  7805. EXPECT_EQ(Error::Canceled, res.error());
  7806. }
  7807. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7808. cli_.set_compress(true);
  7809. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. EXPECT_EQ(LARGE_DATA, res->body);
  7813. }
  7814. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7815. #ifdef CPPHTTPLIB_SSL_ENABLED
  7816. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7817. Client cli(s.c_str());
  7818. cli.enable_server_certificate_verification(false);
  7819. #else
  7820. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7821. Client cli(s.c_str());
  7822. #endif
  7823. cli.set_compress(true);
  7824. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::OK_200, res->status);
  7827. EXPECT_EQ(LARGE_DATA, res->body);
  7828. // The compressed size should be less than a 10th of the original. May vary
  7829. // depending on the zlib library.
  7830. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7831. static_cast<uint64_t>(10 * 1024 * 1024));
  7832. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7833. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7834. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7835. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7836. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7837. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7838. #endif
  7839. }
  7840. TEST_F(ServerTest, PutContentWithDeflate) {
  7841. cli_.set_compress(false);
  7842. Headers headers;
  7843. headers.emplace("Content-Encoding", "deflate");
  7844. // PUT in deflate format:
  7845. auto res = cli_.Put("/put", headers,
  7846. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ("PUT", res->body);
  7850. }
  7851. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7852. Headers headers;
  7853. headers.emplace("Accept-Encoding", "gzip, deflate");
  7854. auto res = cli_.Get("/streamed-chunked", headers);
  7855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7856. EXPECT_EQ(StatusCode::OK_200, res->status);
  7857. EXPECT_EQ(std::string("123456789"), res->body);
  7858. }
  7859. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7860. Headers headers;
  7861. headers.emplace("Accept-Encoding", "gzip, deflate");
  7862. auto res = cli_.Get("/streamed-chunked2", headers);
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ(std::string("123456789"), res->body);
  7866. }
  7867. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7868. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::OK_200, res->status);
  7871. }
  7872. TEST(GzipDecompressor, ChunkedDecompression) {
  7873. std::string data;
  7874. for (size_t i = 0; i < 32 * 1024; ++i) {
  7875. data.push_back(static_cast<char>('a' + i % 26));
  7876. }
  7877. std::string compressed_data;
  7878. {
  7879. httplib::detail::gzip_compressor compressor;
  7880. bool result = compressor.compress(
  7881. data.data(), data.size(),
  7882. /*last=*/true,
  7883. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7884. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7885. compressed_data_size);
  7886. return true;
  7887. });
  7888. ASSERT_TRUE(result);
  7889. }
  7890. std::string decompressed_data;
  7891. {
  7892. httplib::detail::gzip_decompressor decompressor;
  7893. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7894. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7895. size_t chunk_size = 130;
  7896. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7897. chunk_begin += chunk_size) {
  7898. size_t current_chunk_size =
  7899. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7900. bool result = decompressor.decompress(
  7901. compressed_data.data() + chunk_begin, current_chunk_size,
  7902. [&](const char *decompressed_data_chunk,
  7903. size_t decompressed_data_chunk_size) {
  7904. decompressed_data.insert(decompressed_data.size(),
  7905. decompressed_data_chunk,
  7906. decompressed_data_chunk_size);
  7907. return true;
  7908. });
  7909. ASSERT_TRUE(result);
  7910. }
  7911. }
  7912. ASSERT_EQ(data, decompressed_data);
  7913. }
  7914. TEST(GzipDecompressor, DeflateDecompression) {
  7915. std::string original_text = "Raw deflate without gzip";
  7916. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7917. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7918. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7919. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7920. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7921. std::string decompressed_data;
  7922. {
  7923. httplib::detail::gzip_decompressor decompressor;
  7924. bool result = decompressor.decompress(
  7925. compressed_data.data(), compressed_data.size(),
  7926. [&](const char *decompressed_data_chunk,
  7927. size_t decompressed_data_chunk_size) {
  7928. decompressed_data.insert(decompressed_data.size(),
  7929. decompressed_data_chunk,
  7930. decompressed_data_chunk_size);
  7931. return true;
  7932. });
  7933. ASSERT_TRUE(result);
  7934. }
  7935. ASSERT_EQ(original_text, decompressed_data);
  7936. }
  7937. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7938. std::string original_text = "Raw deflate without gzip";
  7939. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7940. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7941. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7942. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7943. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7944. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7945. std::string decompressed_data;
  7946. {
  7947. httplib::detail::gzip_decompressor decompressor;
  7948. bool result = decompressor.decompress(
  7949. compressed_data.data(), compressed_data.size(),
  7950. [&](const char *decompressed_data_chunk,
  7951. size_t decompressed_data_chunk_size) {
  7952. decompressed_data.insert(decompressed_data.size(),
  7953. decompressed_data_chunk,
  7954. decompressed_data_chunk_size);
  7955. return true;
  7956. });
  7957. ASSERT_TRUE(result);
  7958. }
  7959. ASSERT_EQ(original_text, decompressed_data);
  7960. }
  7961. #endif
  7962. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7963. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "br");
  7966. auto res = cli_.Get("/streamed-chunked", headers);
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::OK_200, res->status);
  7969. EXPECT_EQ(std::string("123456789"), res->body);
  7970. }
  7971. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7972. Headers headers;
  7973. headers.emplace("Accept-Encoding", "br");
  7974. auto res = cli_.Get("/streamed-chunked2", headers);
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(StatusCode::OK_200, res->status);
  7977. EXPECT_EQ(std::string("123456789"), res->body);
  7978. }
  7979. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7980. cli_.set_compress(true);
  7981. auto res = cli_.Put(
  7982. "/put", 3,
  7983. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7984. sink.os << "PUT";
  7985. return true;
  7986. },
  7987. "text/plain");
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. EXPECT_EQ("PUT", res->body);
  7991. }
  7992. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7993. cli_.set_compress(true);
  7994. auto res = cli_.Put(
  7995. "/put",
  7996. [](size_t /*offset*/, DataSink &sink) {
  7997. sink.os << "PUT";
  7998. sink.done();
  7999. return true;
  8000. },
  8001. "text/plain");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. EXPECT_EQ("PUT", res->body);
  8005. }
  8006. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8007. cli_.set_compress(true);
  8008. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::OK_200, res->status);
  8011. EXPECT_EQ(LARGE_DATA, res->body);
  8012. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8013. }
  8014. #endif
  8015. TEST_F(ServerTest, Patch) {
  8016. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. EXPECT_EQ("PATCH", res->body);
  8020. }
  8021. TEST_F(ServerTest, Delete) {
  8022. auto res = cli_.Delete("/delete");
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. EXPECT_EQ("DELETE", res->body);
  8026. }
  8027. TEST_F(ServerTest, DeleteContentReceiver) {
  8028. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. EXPECT_EQ("content", res->body);
  8032. }
  8033. TEST_F(ServerTest, Options) {
  8034. auto res = cli_.Options("*");
  8035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8038. EXPECT_TRUE(res->body.empty());
  8039. }
  8040. TEST_F(ServerTest, URL) {
  8041. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. }
  8045. TEST_F(ServerTest, ArrayParam) {
  8046. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. }
  8050. TEST_F(ServerTest, ArrayParamValues) {
  8051. auto res =
  8052. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8054. EXPECT_EQ(StatusCode::OK_200, res->status);
  8055. }
  8056. TEST_F(ServerTest, NoMultipleHeaders) {
  8057. Headers headers = {{"Content-Length", "5"}};
  8058. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8059. "text/plain");
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. }
  8063. TEST_F(ServerTest, PostContentReceiver) {
  8064. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. ASSERT_EQ(StatusCode::OK_200, res->status);
  8067. ASSERT_EQ("content", res->body);
  8068. }
  8069. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8070. UploadFormDataItems items = {
  8071. {"text1", "text default", "", ""},
  8072. {"text2", "aωb", "", ""},
  8073. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8074. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8075. {"file3", "", "", "application/octet-stream"},
  8076. };
  8077. auto res = cli_.Post("/content_receiver", items);
  8078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8079. EXPECT_EQ(StatusCode::OK_200, res->status);
  8080. }
  8081. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8082. UploadFormDataItems items = {
  8083. {"text1", "text default", "", ""},
  8084. {"text2", "aωb", "", ""},
  8085. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8086. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8087. {"file3", "", "", "application/octet-stream"},
  8088. };
  8089. auto boundary = std::string("+++++");
  8090. std::string body;
  8091. for (const auto &item : items) {
  8092. body += "--" + boundary + "\r\n";
  8093. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8094. if (!item.filename.empty()) {
  8095. body += "; filename=\"" + item.filename + "\"";
  8096. }
  8097. body += "\r\n";
  8098. if (!item.content_type.empty()) {
  8099. body += "Content-Type: " + item.content_type + "\r\n";
  8100. }
  8101. body += "\r\n";
  8102. body += item.content + "\r\n";
  8103. }
  8104. body += "--" + boundary + "--\r\n";
  8105. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8106. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST(MultipartFormDataTest, FieldEscaping) {
  8111. Server svr;
  8112. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8113. const ContentReader &content_reader) {
  8114. ASSERT_TRUE(req.is_multipart_form_data());
  8115. std::vector<FormData> received;
  8116. content_reader(
  8117. [&](const FormData &file) {
  8118. received.push_back(file);
  8119. return true;
  8120. },
  8121. [&](const char *data, size_t data_length) {
  8122. received.back().content.append(data, data_length);
  8123. return true;
  8124. });
  8125. // '"', CR and LF in names and filenames are escaped following the
  8126. // WHATWG HTML standard, so each part still parses as a single part
  8127. // with no injected headers. Content types get CR/LF escaped too,
  8128. // while '"' (legal there, e.g. quoted charset) is preserved.
  8129. ASSERT_EQ(4U, received.size());
  8130. EXPECT_EQ("na%22me", received[0].name);
  8131. EXPECT_EQ("quoted name", received[0].content);
  8132. EXPECT_EQ("file", received[1].name);
  8133. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8134. received[1].filename);
  8135. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8136. EXPECT_EQ("injected", received[1].content);
  8137. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8138. EXPECT_EQ("my%22file.txt", received[2].filename);
  8139. EXPECT_EQ("cr lf name", received[2].content);
  8140. EXPECT_EQ("typed", received[3].name);
  8141. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8142. received[3].content_type);
  8143. EXPECT_EQ("typed content", received[3].content);
  8144. });
  8145. auto port = svr.bind_to_any_port("localhost");
  8146. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8147. auto se = detail::scope_exit([&] {
  8148. svr.stop();
  8149. t.join();
  8150. ASSERT_FALSE(svr.is_running());
  8151. });
  8152. svr.wait_until_ready();
  8153. Client cli("localhost", port);
  8154. UploadFormDataItems items = {
  8155. {"na\"me", "quoted name", "", ""},
  8156. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8157. "application/octet-stream"},
  8158. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8159. {"typed", "typed content", "",
  8160. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8161. };
  8162. auto res = cli.Post("/post", items);
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::OK_200, res->status);
  8165. }
  8166. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8167. const UploadFormDataItems items = {
  8168. {"name1", "Content 1", "", ""},
  8169. {"name2", "Content 2", "file2.txt", "text/plain"},
  8170. };
  8171. Server svr;
  8172. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8173. const ContentReader &content_reader) {
  8174. ASSERT_TRUE(req.is_multipart_form_data());
  8175. std::vector<FormData> received;
  8176. content_reader(
  8177. [&](const FormData &file) {
  8178. received.push_back(file);
  8179. return true;
  8180. },
  8181. [&](const char *data, size_t data_length) {
  8182. received.back().content.append(data, data_length);
  8183. return true;
  8184. });
  8185. ASSERT_EQ(2U, received.size());
  8186. EXPECT_EQ("name1", received[0].name);
  8187. EXPECT_EQ("Content 1", received[0].content);
  8188. EXPECT_EQ("name2", received[1].name);
  8189. EXPECT_EQ("Content 2", received[1].content);
  8190. EXPECT_EQ("file2.txt", received[1].filename);
  8191. EXPECT_EQ("text/plain", received[1].content_type);
  8192. });
  8193. auto port = svr.bind_to_any_port("localhost");
  8194. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8195. auto se = detail::scope_exit([&] {
  8196. svr.stop();
  8197. t.join();
  8198. ASSERT_FALSE(svr.is_running());
  8199. });
  8200. svr.wait_until_ready();
  8201. Client cli("localhost", port);
  8202. // Whole-body serialization with a generated boundary
  8203. {
  8204. MultipartFormDataWriter writer;
  8205. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8206. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8207. writer.content_type());
  8208. auto body = writer.serialize(items);
  8209. EXPECT_EQ(body.size(), writer.content_length(items));
  8210. auto res = cli.Post("/post", body, writer.content_type());
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. // Per-part framing with a custom boundary via a content provider
  8215. {
  8216. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8217. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8218. MultipartFormDataWriter writer("custom-boundary_123");
  8219. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8220. std::string body;
  8221. for (const auto &item : items) {
  8222. body += writer.item_begin(item);
  8223. body += item.content;
  8224. body += MultipartFormDataWriter::item_end();
  8225. }
  8226. body += writer.finish();
  8227. EXPECT_EQ(body.size(), writer.content_length(items));
  8228. auto res = cli.Post(
  8229. "/post", body.size(),
  8230. [&](size_t offset, size_t length, DataSink &sink) {
  8231. sink.write(body.data() + offset, length);
  8232. return true;
  8233. },
  8234. writer.content_type());
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. }
  8238. }
  8239. TEST_F(ServerTest, PostContentReceiverGzip) {
  8240. cli_.set_compress(true);
  8241. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. ASSERT_EQ(StatusCode::OK_200, res->status);
  8244. ASSERT_EQ("content", res->body);
  8245. }
  8246. TEST_F(ServerTest, PutContentReceiver) {
  8247. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. ASSERT_EQ(StatusCode::OK_200, res->status);
  8250. ASSERT_EQ("content", res->body);
  8251. }
  8252. TEST_F(ServerTest, PatchContentReceiver) {
  8253. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. ASSERT_EQ(StatusCode::OK_200, res->status);
  8256. ASSERT_EQ("content", res->body);
  8257. }
  8258. template <typename ClientType>
  8259. void TestWithHeadersAndContentReceiver(
  8260. ClientType &cli,
  8261. std::function<Result(ClientType &, const std::string &, const Headers &,
  8262. const std::string &, const std::string &,
  8263. ContentReceiver, DownloadProgress)>
  8264. request_func) {
  8265. Headers headers;
  8266. headers.emplace("X-Custom-Header", "test-value");
  8267. std::string received_body;
  8268. auto res = request_func(
  8269. cli, "/content_receiver", headers, "content", "application/json",
  8270. [&](const char *data, size_t data_length) {
  8271. received_body.append(data, data_length);
  8272. return true;
  8273. },
  8274. nullptr);
  8275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8276. EXPECT_EQ(StatusCode::OK_200, res->status);
  8277. EXPECT_EQ("content", received_body);
  8278. }
  8279. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8280. #ifdef CPPHTTPLIB_SSL_ENABLED
  8281. using ClientT = SSLClient;
  8282. #else
  8283. using ClientT = Client;
  8284. #endif
  8285. TestWithHeadersAndContentReceiver<ClientT>(
  8286. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8287. const std::string &body, const std::string &content_type,
  8288. ContentReceiver receiver, DownloadProgress progress) {
  8289. return cli.Post(path, headers, body, content_type, receiver, progress);
  8290. });
  8291. }
  8292. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8293. #ifdef CPPHTTPLIB_SSL_ENABLED
  8294. using ClientT = SSLClient;
  8295. #else
  8296. using ClientT = Client;
  8297. #endif
  8298. TestWithHeadersAndContentReceiver<ClientT>(
  8299. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8300. const std::string &body, const std::string &content_type,
  8301. ContentReceiver receiver, DownloadProgress progress) {
  8302. return cli.Put(path, headers, body, content_type, receiver, progress);
  8303. });
  8304. }
  8305. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8306. #ifdef CPPHTTPLIB_SSL_ENABLED
  8307. using ClientT = SSLClient;
  8308. #else
  8309. using ClientT = Client;
  8310. #endif
  8311. TestWithHeadersAndContentReceiver<ClientT>(
  8312. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8313. const std::string &body, const std::string &content_type,
  8314. ContentReceiver receiver, DownloadProgress progress) {
  8315. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8316. });
  8317. }
  8318. template <typename ClientType>
  8319. void TestWithHeadersAndContentReceiverWithProgress(
  8320. ClientType &cli,
  8321. std::function<Result(ClientType &, const std::string &, const Headers &,
  8322. const std::string &, const std::string &,
  8323. ContentReceiver, DownloadProgress)>
  8324. request_func) {
  8325. Headers headers;
  8326. headers.emplace("X-Test-Header", "progress-test");
  8327. std::string received_body;
  8328. auto progress_called = false;
  8329. auto res = request_func(
  8330. cli, "/content_receiver", headers, "content", "text/plain",
  8331. [&](const char *data, size_t data_length) {
  8332. received_body.append(data, data_length);
  8333. return true;
  8334. },
  8335. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8336. progress_called = true;
  8337. return true;
  8338. });
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("content", received_body);
  8342. EXPECT_TRUE(progress_called);
  8343. }
  8344. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8345. #ifdef CPPHTTPLIB_SSL_ENABLED
  8346. using ClientT = SSLClient;
  8347. #else
  8348. using ClientT = Client;
  8349. #endif
  8350. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8351. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8352. const std::string &body, const std::string &content_type,
  8353. ContentReceiver receiver, DownloadProgress progress) {
  8354. return cli.Post(path, headers, body, content_type, receiver, progress);
  8355. });
  8356. }
  8357. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8358. #ifdef CPPHTTPLIB_SSL_ENABLED
  8359. using ClientT = SSLClient;
  8360. #else
  8361. using ClientT = Client;
  8362. #endif
  8363. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8364. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8365. const std::string &body, const std::string &content_type,
  8366. ContentReceiver receiver, DownloadProgress progress) {
  8367. return cli.Put(path, headers, body, content_type, receiver, progress);
  8368. });
  8369. }
  8370. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8371. #ifdef CPPHTTPLIB_SSL_ENABLED
  8372. using ClientT = SSLClient;
  8373. #else
  8374. using ClientT = Client;
  8375. #endif
  8376. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8377. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8378. const std::string &body, const std::string &content_type,
  8379. ContentReceiver receiver, DownloadProgress progress) {
  8380. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8381. });
  8382. }
  8383. template <typename ClientType>
  8384. void TestWithHeadersAndContentReceiverError(
  8385. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8386. const Headers &, const std::string &,
  8387. const std::string &, ContentReceiver)>
  8388. request_func) {
  8389. Headers headers;
  8390. headers.emplace("X-Error-Test", "true");
  8391. std::string received_body;
  8392. auto receiver_failed = false;
  8393. auto res =
  8394. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8395. [&](const char *data, size_t data_length) {
  8396. received_body.append(data, data_length);
  8397. receiver_failed = true;
  8398. return false;
  8399. });
  8400. ASSERT_FALSE(res);
  8401. EXPECT_TRUE(receiver_failed);
  8402. }
  8403. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8404. #ifdef CPPHTTPLIB_SSL_ENABLED
  8405. using ClientT = SSLClient;
  8406. #else
  8407. using ClientT = Client;
  8408. #endif
  8409. TestWithHeadersAndContentReceiverError<ClientT>(
  8410. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8411. const std::string &body, const std::string &content_type,
  8412. ContentReceiver receiver) {
  8413. return cli.Post(path, headers, body, content_type, receiver);
  8414. });
  8415. }
  8416. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8417. #ifdef CPPHTTPLIB_SSL_ENABLED
  8418. using ClientT = SSLClient;
  8419. #else
  8420. using ClientT = Client;
  8421. #endif
  8422. TestWithHeadersAndContentReceiverError<ClientT>(
  8423. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8424. const std::string &body, const std::string &content_type,
  8425. ContentReceiver receiver) {
  8426. return cli.Put(path, headers, body, content_type, receiver);
  8427. });
  8428. }
  8429. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8430. #ifdef CPPHTTPLIB_SSL_ENABLED
  8431. using ClientT = SSLClient;
  8432. #else
  8433. using ClientT = Client;
  8434. #endif
  8435. TestWithHeadersAndContentReceiverError<ClientT>(
  8436. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8437. const std::string &body, const std::string &content_type,
  8438. ContentReceiver receiver) {
  8439. return cli.Patch(path, headers, body, content_type, receiver);
  8440. });
  8441. }
  8442. TEST_F(ServerTest, PostQueryStringAndBody) {
  8443. auto res =
  8444. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8446. ASSERT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, HTTP2Magic) {
  8449. Request req;
  8450. req.method = "PRI";
  8451. req.path = "*";
  8452. req.body = "SM";
  8453. auto res = std::make_shared<Response>();
  8454. auto error = Error::Success;
  8455. auto ret = cli_.send(req, *res, error);
  8456. ASSERT_TRUE(ret);
  8457. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8458. }
  8459. TEST_F(ServerTest, KeepAlive) {
  8460. auto res = cli_.Get("/hi");
  8461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8462. EXPECT_EQ(StatusCode::OK_200, res->status);
  8463. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8464. EXPECT_EQ("Hello World!", res->body);
  8465. res = cli_.Get("/hi");
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_EQ(StatusCode::OK_200, res->status);
  8468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8469. EXPECT_EQ("Hello World!", res->body);
  8470. res = cli_.Get("/hi");
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8474. EXPECT_EQ("Hello World!", res->body);
  8475. res = cli_.Get("/not-exist");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8478. res = cli_.Post("/empty", "", "text/plain");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8482. EXPECT_EQ("empty", res->body);
  8483. EXPECT_EQ("close", res->get_header_value("Connection"));
  8484. res = cli_.Post(
  8485. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8486. "text/plain");
  8487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8490. EXPECT_EQ("empty", res->body);
  8491. cli_.set_keep_alive(false);
  8492. res = cli_.Get("/last-request");
  8493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8494. EXPECT_EQ(StatusCode::OK_200, res->status);
  8495. EXPECT_EQ("close", res->get_header_value("Connection"));
  8496. }
  8497. TEST_F(ServerTest, TooManyRedirect) {
  8498. cli_.set_follow_location(true);
  8499. auto res = cli_.Get("/redirect/0");
  8500. ASSERT_TRUE(!res);
  8501. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8502. }
  8503. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8504. Request req;
  8505. req.method = "FOOBAR";
  8506. req.path = "/hi";
  8507. cli_.set_keep_alive(true);
  8508. auto res = cli_.send(req);
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8511. EXPECT_EQ("close", res->get_header_value("Connection"));
  8512. EXPECT_FALSE(cli_.is_socket_open());
  8513. }
  8514. TEST_F(ServerTest, CustomRouteReadsBody) {
  8515. const std::string xml =
  8516. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8517. Request req;
  8518. req.method = "PROPFIND";
  8519. req.path = "/dav/dir";
  8520. req.set_header("Depth", "1");
  8521. req.body = xml;
  8522. auto res = cli_.send(req);
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8525. EXPECT_EQ(xml, res->body);
  8526. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8527. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8528. }
  8529. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8530. Request req;
  8531. req.method = "PROPFIND";
  8532. req.path = "/dav/42";
  8533. auto res = cli_.send(req);
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8536. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8537. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8538. }
  8539. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8540. Request req;
  8541. req.method = "PROPFIND";
  8542. req.path = "/dav-re/123";
  8543. auto res = cli_.send(req);
  8544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8545. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8546. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8547. }
  8548. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8549. Request req;
  8550. req.method = "MKCOL";
  8551. req.path = "/dav-mkcol";
  8552. auto res = cli_.send(req);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::Created_201, res->status);
  8555. }
  8556. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8557. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8558. Request req;
  8559. req.method = "REPORT";
  8560. req.path = "/dav-report";
  8561. req.body = xml;
  8562. auto res = cli_.send(req);
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8565. EXPECT_EQ(xml, res->body);
  8566. }
  8567. // A content reader route must fire even when the request carries no body,
  8568. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8569. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8570. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8571. Request req;
  8572. req.method = "REPORT";
  8573. req.path = "/dav-report";
  8574. auto res = cli_.send(req);
  8575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8576. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8577. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8578. }
  8579. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8580. Request req;
  8581. req.method = "PROPFIND";
  8582. req.path = "/not-dav";
  8583. auto res = cli_.send(req);
  8584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8585. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8586. }
  8587. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8588. Request req;
  8589. req.method = "UNLOCK";
  8590. req.path = "/dav/dir";
  8591. cli_.set_keep_alive(true);
  8592. auto res = cli_.send(req);
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8595. EXPECT_EQ("close", res->get_header_value("Connection"));
  8596. EXPECT_FALSE(cli_.is_socket_open());
  8597. }
  8598. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8599. // The mount point serves this path, but only for GET and HEAD.
  8600. auto get_res = cli_.Get("/dir/index.html");
  8601. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8602. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8603. Request req;
  8604. req.method = "PROPFIND";
  8605. req.path = "/dir/index.html";
  8606. auto res = cli_.send(req);
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8609. }
  8610. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8611. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8612. cli_.set_keep_alive(true);
  8613. for (auto i = 0; i < 2; i++) {
  8614. Request req;
  8615. req.method = "PROPFIND";
  8616. req.path = "/dav/dir";
  8617. req.body = xml;
  8618. auto res = cli_.send(req);
  8619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8620. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8621. EXPECT_EQ(xml, res->body);
  8622. EXPECT_TRUE(cli_.is_socket_open());
  8623. }
  8624. // A built-in method must still be served on the same connection.
  8625. cli_.set_keep_alive(false);
  8626. auto res = cli_.Get("/hi");
  8627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8628. EXPECT_EQ(StatusCode::OK_200, res->status);
  8629. EXPECT_EQ("close", res->get_header_value("Connection"));
  8630. }
  8631. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8632. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8633. Request req;
  8634. req.method = "PROPFIND";
  8635. req.path = "/dav/dir";
  8636. req.set_header("Expect", "100-continue");
  8637. req.body = xml;
  8638. auto res = cli_.send(req);
  8639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8640. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8641. EXPECT_EQ(xml, res->body);
  8642. }
  8643. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8645. TEST_F(ServerTest, Gzip) {
  8646. Headers headers;
  8647. headers.emplace("Accept-Encoding", "gzip, deflate");
  8648. auto res = cli_.Get("/compress", headers);
  8649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8652. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8654. "7890123456789012345678901234567890",
  8655. res->body);
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. }
  8658. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8659. Headers headers;
  8660. headers.emplace("Accept-Encoding", "gzip, deflate");
  8661. auto res = cli_.Get("/compress-with-charset", headers);
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8664. EXPECT_EQ("application/json; charset=utf-8",
  8665. res->get_header_value("Content-Type"));
  8666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8667. "7890123456789012345678901234567890",
  8668. res->body);
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8672. Headers headers;
  8673. headers.emplace("Accept-Encoding", "");
  8674. auto res = cli_.Get("/compress", headers);
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8678. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8679. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8680. "7890123456789012345678901234567890",
  8681. res->body);
  8682. EXPECT_EQ(StatusCode::OK_200, res->status);
  8683. }
  8684. TEST_F(ServerTest, GzipWithContentReceiver) {
  8685. Headers headers;
  8686. headers.emplace("Accept-Encoding", "gzip, deflate");
  8687. std::string body;
  8688. auto res =
  8689. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8690. EXPECT_EQ(100U, data_length);
  8691. body.append(data, data_length);
  8692. return true;
  8693. });
  8694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8695. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8696. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8697. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8698. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8699. "7890123456789012345678901234567890",
  8700. body);
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8704. Headers headers;
  8705. headers.emplace("Accept-Encoding", "gzip, deflate");
  8706. cli_.set_decompress(false);
  8707. auto res = cli_.Get("/compress", headers);
  8708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8709. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8711. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8712. EXPECT_EQ(33U, res->body.size());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. }
  8715. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8716. Headers headers;
  8717. headers.emplace("Accept-Encoding", "");
  8718. std::string body;
  8719. auto res =
  8720. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8721. EXPECT_EQ(100U, data_length);
  8722. body.append(data, data_length);
  8723. return true;
  8724. });
  8725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8726. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8727. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8728. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8729. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8730. "7890123456789012345678901234567890",
  8731. body);
  8732. EXPECT_EQ(StatusCode::OK_200, res->status);
  8733. }
  8734. TEST_F(ServerTest, NoGzip) {
  8735. Headers headers;
  8736. headers.emplace("Accept-Encoding", "gzip, deflate");
  8737. auto res = cli_.Get("/nocompress", headers);
  8738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8739. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8740. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8741. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8742. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8743. "7890123456789012345678901234567890",
  8744. res->body);
  8745. EXPECT_EQ(StatusCode::OK_200, res->status);
  8746. }
  8747. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8748. Headers headers;
  8749. headers.emplace("Accept-Encoding", "gzip, deflate");
  8750. std::string body;
  8751. auto res = cli_.Get("/nocompress", headers,
  8752. [&](const char *data, size_t data_length) {
  8753. EXPECT_EQ(100U, data_length);
  8754. body.append(data, data_length);
  8755. return true;
  8756. });
  8757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8758. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8759. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8762. "7890123456789012345678901234567890",
  8763. body);
  8764. EXPECT_EQ(StatusCode::OK_200, res->status);
  8765. }
  8766. TEST_F(ServerTest, MultipartFormDataGzip) {
  8767. UploadFormDataItems items = {
  8768. {"key1", "test", "", ""},
  8769. {"key2", "--abcdefg123", "", ""},
  8770. };
  8771. cli_.set_compress(true);
  8772. auto res = cli_.Post("/compress-multipart", items);
  8773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8774. EXPECT_EQ(StatusCode::OK_200, res->status);
  8775. }
  8776. #endif
  8777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8778. // Static file compression is opt-in, so these run their own server rather than
  8779. // flipping it on for the shared ServerTest fixture, which would silently
  8780. // rewrite what every other static file test is asserting.
  8781. class StaticFileCompressionTest : public ::testing::Test {
  8782. protected:
  8783. void TearDown() override {
  8784. if (t_.joinable()) {
  8785. svr_.stop();
  8786. t_.join();
  8787. }
  8788. }
  8789. int start(const std::function<void(Server &)> &configure = nullptr) {
  8790. // Serves the same tree as a directory of build-time compressed assets
  8791. // would be served: the mount point names the coding the files are already
  8792. // stored in. Registered before "/" so it is the one that matches.
  8793. svr_.set_mount_point("/pre-encoded", "./www",
  8794. {{"Content-Encoding", "gzip"}});
  8795. svr_.set_mount_point("/", "./www");
  8796. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8797. res.set_file_content("./www/dir/index.html", "text/html");
  8798. });
  8799. svr_.Get("/pre-encoded-file-content",
  8800. [](const Request & /*req*/, Response &res) {
  8801. res.set_header("Content-Encoding", "gzip");
  8802. res.set_file_content("./www/dir/index.html", "text/html");
  8803. });
  8804. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8805. res.set_content_provider(
  8806. 6, "text/plain",
  8807. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8808. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8809. return true;
  8810. });
  8811. });
  8812. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8813. res.set_content_provider(
  8814. 1000, "text/plain",
  8815. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8816. if (offset < 100) {
  8817. std::string data(100, 'A');
  8818. sink.write(data.data(), data.size());
  8819. return true;
  8820. }
  8821. std::this_thread::sleep_for(std::chrono::seconds(2));
  8822. std::string data(900, 'B');
  8823. sink.write(data.data(), data.size());
  8824. return true;
  8825. });
  8826. });
  8827. if (configure) { configure(svr_); }
  8828. auto port = svr_.bind_to_any_port(HOST);
  8829. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8830. svr_.wait_until_ready();
  8831. return port;
  8832. }
  8833. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8834. // Every file under ./www except 1MB.txt is smaller than the default
  8835. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8836. // it out of the way.
  8837. static void enable_without_floor(Server &svr) {
  8838. svr.set_static_file_compression(true);
  8839. svr.set_static_file_compression_min_length(0);
  8840. }
  8841. Server svr_;
  8842. std::thread t_;
  8843. };
  8844. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8845. auto port = start();
  8846. Client cli(HOST, port);
  8847. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8851. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8852. EXPECT_EQ(1048576U, res->body.size());
  8853. }
  8854. TEST_F(StaticFileCompressionTest, MountPoint) {
  8855. auto port = start(enable);
  8856. Client cli(HOST, port);
  8857. cli.set_decompress(false);
  8858. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8860. EXPECT_EQ(StatusCode::OK_200, res->status);
  8861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8862. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8863. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8864. // The response stays self-delimiting: a length, not a chunked body.
  8865. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8866. EXPECT_EQ(std::to_string(res->body.size()),
  8867. res->get_header_value("Content-Length"));
  8868. EXPECT_LT(res->body.size(), 1048576U);
  8869. EXPECT_FALSE(res->body.empty());
  8870. }
  8871. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8872. auto port = start(enable);
  8873. Client cli(HOST, port);
  8874. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8878. EXPECT_EQ(1048576U, res->body.size());
  8879. }
  8880. TEST_F(StaticFileCompressionTest, FileContent) {
  8881. auto port = start(enable_without_floor);
  8882. Client cli(HOST, port);
  8883. auto res = cli.Get("/file_content", 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/html", res->get_header_value("Content-Type"));
  8887. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8888. EXPECT_EQ(104U, res->body.size());
  8889. }
  8890. // A handler that serves an already-encoded file names the coding itself. The
  8891. // file-backed path decided its coding from Accept-Encoding and the content
  8892. // type alone, so it compressed the stored bytes a second time and appended a
  8893. // second Content-Encoding field line.
  8894. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8895. auto port = start(enable_without_floor);
  8896. Client cli(HOST, port);
  8897. cli.set_decompress(false);
  8898. auto res = cli.Get("/pre-encoded-file-content",
  8899. Headers{{"Accept-Encoding", "gzip"}});
  8900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8903. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8904. // Vary belongs to a coding the server chose, and it chose none here.
  8905. EXPECT_FALSE(res->has_header("Vary"));
  8906. // The file travels exactly as it is stored on disk.
  8907. EXPECT_EQ(104U, res->body.size());
  8908. }
  8909. // The 1MB file clears the default floor, so this one runs the configuration a
  8910. // deployment would actually have.
  8911. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8912. auto port = start(enable);
  8913. Client cli(HOST, port);
  8914. cli.set_decompress(false);
  8915. auto res =
  8916. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8920. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8921. EXPECT_FALSE(res->has_header("Vary"));
  8922. EXPECT_EQ(1048576U, res->body.size());
  8923. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8924. }
  8925. TEST_F(StaticFileCompressionTest, Head) {
  8926. auto port = start(enable);
  8927. Client cli(HOST, port);
  8928. cli.set_decompress(false);
  8929. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8930. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8931. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8935. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8936. // HEAD still reports the size a GET would return.
  8937. EXPECT_EQ(get->get_header_value("Content-Length"),
  8938. res->get_header_value("Content-Length"));
  8939. EXPECT_TRUE(res->body.empty());
  8940. }
  8941. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8942. auto port = start(enable);
  8943. Client cli(HOST, port);
  8944. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8945. {"Accept-Encoding", "gzip"}});
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8948. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8949. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8950. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8951. EXPECT_EQ("cd", res->body);
  8952. }
  8953. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8954. auto port = start(enable);
  8955. Client cli(HOST, port);
  8956. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8960. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8961. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8962. }
  8963. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8964. auto port = start(enable);
  8965. Client cli(HOST, port);
  8966. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8970. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8971. EXPECT_TRUE(res->body.empty());
  8972. }
  8973. TEST_F(StaticFileCompressionTest, MinLength) {
  8974. auto port = start(enable);
  8975. Client cli(HOST, port);
  8976. // 104 bytes, well under the default floor. Compressing it would add the
  8977. // gzip header and trailer to a body that already fits in one packet.
  8978. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8982. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8983. }
  8984. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8985. auto port = start([](Server &svr) {
  8986. svr.set_static_file_compression(true);
  8987. svr.set_static_file_compression_min_length(1);
  8988. });
  8989. Client cli(HOST, port);
  8990. cli.set_decompress(false);
  8991. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8994. // A 9-byte file comes back larger than it went in, because gzip's header and
  8995. // trailer outweigh anything deflate can save. That is the end of the range
  8996. // the floor exists to keep out.
  8997. EXPECT_GT(res->body.size(), 9U);
  8998. }
  8999. TEST_F(StaticFileCompressionTest, MaxLength) {
  9000. auto port = start([](Server &svr) {
  9001. svr.set_static_file_compression(true);
  9002. svr.set_static_file_compression_min_length(0);
  9003. svr.set_static_file_compression_max_length(1024);
  9004. });
  9005. Client cli(HOST, port);
  9006. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9007. // defines `small` as a macro on Windows.
  9008. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9009. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9010. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9011. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9012. // Under it: compressed.
  9013. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9014. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9015. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9016. }
  9017. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9018. auto port = start(enable_without_floor);
  9019. Client cli(HOST, port);
  9020. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9021. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9022. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9023. auto identity_etag = identity->get_header_value("ETag");
  9024. ASSERT_FALSE(identity_etag.empty());
  9025. auto gzipped =
  9026. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9027. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9028. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9029. auto gzip_etag = gzipped->get_header_value("ETag");
  9030. ASSERT_FALSE(gzip_etag.empty());
  9031. // Two representations, two validators.
  9032. EXPECT_NE(identity_etag, gzip_etag);
  9033. // Each one revalidates against the request that would produce it...
  9034. auto fresh =
  9035. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9036. {"If-None-Match", gzip_etag}});
  9037. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9038. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9039. auto fresh_identity =
  9040. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9041. {"If-None-Match", identity_etag}});
  9042. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9043. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9044. // ...and not against the other representation.
  9045. auto crossed =
  9046. cli.Get("/dir/index.html",
  9047. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9048. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9049. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9050. }
  9051. // The opt-in covers responses the server reads off disk itself. A caller's own
  9052. // known-length provider keeps its Content-Length and, more importantly, keeps
  9053. // delivering incrementally: routing it through a compressor would hold every
  9054. // write back until zlib's window filled.
  9055. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9056. auto port = start(enable);
  9057. Client cli(HOST, port);
  9058. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ(StatusCode::OK_200, res->status);
  9061. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9062. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9063. EXPECT_EQ("aaabbb", res->body);
  9064. }
  9065. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9066. auto port = start(enable);
  9067. Client cli(HOST, port);
  9068. cli.set_read_timeout(1, 0);
  9069. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9070. Headers{{"Accept-Encoding", "gzip"}});
  9071. ASSERT_TRUE(handle.is_valid());
  9072. // The provider writes 100 bytes and then stalls for longer than the read
  9073. // timeout. Those first bytes have to arrive anyway: run the response through
  9074. // a compressor and zlib holds them until its window fills, so the read would
  9075. // come back empty instead.
  9076. char buf[256];
  9077. auto n = handle.read(buf, sizeof(buf));
  9078. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9079. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9080. }
  9081. #endif
  9082. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9083. TEST_F(ServerTest, Brotli) {
  9084. Headers headers;
  9085. headers.emplace("Accept-Encoding", "br");
  9086. auto res = cli_.Get("/compress", headers);
  9087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9088. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9089. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9090. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9091. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9092. "7890123456789012345678901234567890",
  9093. res->body);
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. }
  9096. #endif
  9097. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9098. TEST_F(ServerTest, Zstd) {
  9099. Headers headers;
  9100. headers.emplace("Accept-Encoding", "zstd");
  9101. auto res = cli_.Get("/compress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9105. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9107. "7890123456789012345678901234567890",
  9108. res->body);
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. }
  9111. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9112. Headers headers;
  9113. headers.emplace("Accept-Encoding", "");
  9114. auto res = cli_.Get("/compress", headers);
  9115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9120. "7890123456789012345678901234567890",
  9121. res->body);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9125. Headers headers;
  9126. headers.emplace("Accept-Encoding", "zstd");
  9127. std::string body;
  9128. auto res =
  9129. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9130. EXPECT_EQ(100U, data_length);
  9131. body.append(data, data_length);
  9132. return true;
  9133. });
  9134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9135. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9138. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9139. "7890123456789012345678901234567890",
  9140. body);
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. }
  9143. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9144. Headers headers;
  9145. headers.emplace("Accept-Encoding", "zstd");
  9146. cli_.set_decompress(false);
  9147. auto res = cli_.Get("/compress", headers);
  9148. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9149. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9150. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9151. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9153. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9155. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9156. EXPECT_EQ(StatusCode::OK_200, res->status);
  9157. ASSERT_EQ(26U, res->body.size());
  9158. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9159. 0);
  9160. }
  9161. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9162. Headers headers;
  9163. headers.emplace("Accept-Encoding", "");
  9164. std::string body;
  9165. auto res =
  9166. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9167. EXPECT_EQ(100U, data_length);
  9168. body.append(data, data_length);
  9169. return true;
  9170. });
  9171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9172. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9174. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9175. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9176. "7890123456789012345678901234567890",
  9177. body);
  9178. EXPECT_EQ(StatusCode::OK_200, res->status);
  9179. }
  9180. TEST_F(ServerTest, NoZstd) {
  9181. Headers headers;
  9182. headers.emplace("Accept-Encoding", "zstd");
  9183. auto res = cli_.Get("/nocompress", headers);
  9184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9185. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9186. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9187. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9189. "7890123456789012345678901234567890",
  9190. res->body);
  9191. EXPECT_EQ(StatusCode::OK_200, res->status);
  9192. }
  9193. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9194. Headers headers;
  9195. headers.emplace("Accept-Encoding", "zstd");
  9196. std::string body;
  9197. auto res = cli_.Get("/nocompress", headers,
  9198. [&](const char *data, size_t data_length) {
  9199. EXPECT_EQ(100U, data_length);
  9200. body.append(data, data_length);
  9201. return true;
  9202. });
  9203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9204. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9205. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9206. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9207. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9208. "7890123456789012345678901234567890",
  9209. body);
  9210. EXPECT_EQ(StatusCode::OK_200, res->status);
  9211. }
  9212. // TODO: How to enable zstd ??
  9213. TEST_F(ServerTest, MultipartFormDataZstd) {
  9214. UploadFormDataItems items = {
  9215. {"key1", "test", "", ""},
  9216. {"key2", "--abcdefg123", "", ""},
  9217. };
  9218. Headers headers;
  9219. headers.emplace("Accept-Encoding", "zstd");
  9220. cli_.set_compress(true);
  9221. auto res = cli_.Post("/compress-multipart", headers, items);
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. }
  9225. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9226. Headers headers;
  9227. headers.emplace("Accept-Encoding", "zstd");
  9228. cli_.set_compress(true);
  9229. auto res = cli_.Put(
  9230. "/put", headers, 3,
  9231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9232. sink.os << "PUT";
  9233. return true;
  9234. },
  9235. "text/plain");
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ("PUT", res->body);
  9239. }
  9240. // Pre-compression logging tests
  9241. TEST_F(ServerTest, PreCompressionLogging) {
  9242. // Test data for compression (matches the actual /compress endpoint content)
  9243. const std::string test_content =
  9244. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9245. "3456789012345678901234567890";
  9246. // Variables to capture logging data
  9247. std::string pre_compression_body;
  9248. std::string pre_compression_content_type;
  9249. std::string pre_compression_content_encoding;
  9250. std::string post_compression_body;
  9251. std::string post_compression_content_type;
  9252. std::string post_compression_content_encoding;
  9253. // Set up pre-compression logger
  9254. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9255. const Response &res) {
  9256. pre_compression_body = res.body;
  9257. pre_compression_content_type = res.get_header_value("Content-Type");
  9258. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9259. });
  9260. // Set up post-compression logger
  9261. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9262. post_compression_body = res.body;
  9263. post_compression_content_type = res.get_header_value("Content-Type");
  9264. post_compression_content_encoding =
  9265. res.get_header_value("Content-Encoding");
  9266. });
  9267. // Test with gzip compression
  9268. Headers headers;
  9269. headers.emplace("Accept-Encoding", "gzip");
  9270. auto res = cli_.Get("/compress", headers);
  9271. // Verify response was compressed
  9272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9273. EXPECT_EQ(StatusCode::OK_200, res->status);
  9274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9275. // Verify pre-compression logger captured uncompressed content
  9276. EXPECT_EQ(test_content, pre_compression_body);
  9277. EXPECT_EQ("text/plain", pre_compression_content_type);
  9278. EXPECT_TRUE(pre_compression_content_encoding
  9279. .empty()); // No encoding header before compression
  9280. // Verify post-compression logger captured compressed content
  9281. EXPECT_NE(test_content,
  9282. post_compression_body); // Should be different after compression
  9283. EXPECT_EQ("text/plain", post_compression_content_type);
  9284. EXPECT_EQ("gzip", post_compression_content_encoding);
  9285. // Verify compressed content is smaller
  9286. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9287. }
  9288. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9289. const std::string test_content =
  9290. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9291. "3456789012345678901234567890";
  9292. std::string pre_compression_body;
  9293. std::string post_compression_body;
  9294. svr_.set_pre_compression_logger(
  9295. [&](const Request & /*req*/, const Response &res) {
  9296. pre_compression_body = res.body;
  9297. });
  9298. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9299. post_compression_body = res.body;
  9300. });
  9301. Headers headers;
  9302. headers.emplace("Accept-Encoding", "br");
  9303. auto res = cli_.Get("/compress", headers);
  9304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9305. EXPECT_EQ(StatusCode::OK_200, res->status);
  9306. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9307. // Verify pre-compression content is uncompressed
  9308. EXPECT_EQ(test_content, pre_compression_body);
  9309. // Verify post-compression content is compressed
  9310. EXPECT_NE(test_content, post_compression_body);
  9311. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9312. }
  9313. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  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. // Request without compression (use /nocompress endpoint)
  9327. Headers headers;
  9328. auto res = cli_.Get("/nocompress", headers);
  9329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9330. EXPECT_EQ(StatusCode::OK_200, res->status);
  9331. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9332. // Pre-compression logger should not be called when no compression is applied
  9333. EXPECT_TRUE(
  9334. pre_compression_body.empty()); // Pre-compression logger not called
  9335. EXPECT_EQ(
  9336. test_content,
  9337. post_compression_body); // Post-compression logger captures final content
  9338. }
  9339. TEST_F(ServerTest, LoggerSeesContentLength) {
  9340. size_t logged_content_length = 0;
  9341. std::string logged_content_length_header;
  9342. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9343. logged_content_length = res.content_length_;
  9344. logged_content_length_header = res.get_header_value("Content-Length");
  9345. });
  9346. auto res = cli_.Get("/nocompress");
  9347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9348. EXPECT_EQ(StatusCode::OK_200, res->status);
  9349. EXPECT_EQ(res->body.size(), logged_content_length);
  9350. EXPECT_EQ(std::to_string(logged_content_length),
  9351. logged_content_length_header);
  9352. }
  9353. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9354. const std::string test_content =
  9355. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9356. "3456789012345678901234567890";
  9357. std::string pre_compression_body;
  9358. bool pre_logger_called = false;
  9359. // Set only pre-compression logger
  9360. svr_.set_pre_compression_logger(
  9361. [&](const Request & /*req*/, const Response &res) {
  9362. pre_compression_body = res.body;
  9363. pre_logger_called = true;
  9364. });
  9365. Headers headers;
  9366. headers.emplace("Accept-Encoding", "gzip");
  9367. auto res = cli_.Get("/compress", headers);
  9368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9369. EXPECT_EQ(StatusCode::OK_200, res->status);
  9370. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9371. // Verify pre-compression logger was called
  9372. EXPECT_TRUE(pre_logger_called);
  9373. EXPECT_EQ(test_content, pre_compression_body);
  9374. }
  9375. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9376. {
  9377. // Test with Expect: 100-continue header - success case
  9378. // Server returns 100 Continue, client sends body, server returns 200 OK
  9379. Request req;
  9380. req.method = "POST";
  9381. req.path = "/post-large";
  9382. req.set_header("Expect", "100-continue");
  9383. req.body = LARGE_DATA;
  9384. Response res;
  9385. auto error = Error::Success;
  9386. cli_.set_keep_alive(true);
  9387. auto ret = cli_.send(req, res, error);
  9388. EXPECT_TRUE(ret);
  9389. EXPECT_EQ(StatusCode::OK_200, res.status);
  9390. EXPECT_EQ(LARGE_DATA, res.body);
  9391. }
  9392. {
  9393. // Test with Expect: 100-continue header - error case
  9394. // Client should not send the body when server returns an error
  9395. Request req;
  9396. req.method = "POST";
  9397. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9398. req.set_header("Expect", "100-continue");
  9399. req.body = LARGE_DATA;
  9400. Response res;
  9401. auto error = Error::Success;
  9402. auto start = std::chrono::high_resolution_clock::now();
  9403. cli_.set_keep_alive(true);
  9404. auto ret = cli_.send(req, res, error);
  9405. auto end = std::chrono::high_resolution_clock::now();
  9406. auto elapsed =
  9407. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9408. .count();
  9409. // With Expect: 100-continue, request completes successfully but with error
  9410. EXPECT_TRUE(ret);
  9411. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9412. EXPECT_EQ("close", res.get_header_value("Connection"));
  9413. EXPECT_FALSE(cli_.is_socket_open());
  9414. EXPECT_LE(elapsed, 2000);
  9415. }
  9416. {
  9417. // Send an extra GET request to ensure error recovery without hanging
  9418. Request req;
  9419. req.method = "GET";
  9420. req.path = "/hi";
  9421. auto start = std::chrono::high_resolution_clock::now();
  9422. auto res = cli_.send(req);
  9423. auto end = std::chrono::high_resolution_clock::now();
  9424. auto elapsed =
  9425. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9426. .count();
  9427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9428. EXPECT_EQ(StatusCode::OK_200, res->status);
  9429. EXPECT_EQ("Hello World!", res->body);
  9430. EXPECT_LE(elapsed, 500);
  9431. }
  9432. }
  9433. TEST(ZstdDecompressor, ChunkedDecompression) {
  9434. std::string data;
  9435. for (size_t i = 0; i < 32 * 1024; ++i) {
  9436. data.push_back(static_cast<char>('a' + i % 26));
  9437. }
  9438. std::string compressed_data;
  9439. {
  9440. httplib::detail::zstd_compressor compressor;
  9441. bool result = compressor.compress(
  9442. data.data(), data.size(),
  9443. /*last=*/true,
  9444. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9445. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9446. compressed_data_size);
  9447. return true;
  9448. });
  9449. ASSERT_TRUE(result);
  9450. }
  9451. std::string decompressed_data;
  9452. {
  9453. httplib::detail::zstd_decompressor decompressor;
  9454. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9455. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9456. size_t chunk_size = 130;
  9457. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9458. chunk_begin += chunk_size) {
  9459. size_t current_chunk_size =
  9460. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9461. bool result = decompressor.decompress(
  9462. compressed_data.data() + chunk_begin, current_chunk_size,
  9463. [&](const char *decompressed_data_chunk,
  9464. size_t decompressed_data_chunk_size) {
  9465. decompressed_data.insert(decompressed_data.size(),
  9466. decompressed_data_chunk,
  9467. decompressed_data_chunk_size);
  9468. return true;
  9469. });
  9470. ASSERT_TRUE(result);
  9471. }
  9472. }
  9473. ASSERT_EQ(data, decompressed_data);
  9474. }
  9475. TEST(ZstdDecompressor, Decompress) {
  9476. std::string original_text = "Compressed with ZSTD";
  9477. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9478. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9479. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9480. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9481. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9482. std::string decompressed_data;
  9483. {
  9484. httplib::detail::zstd_decompressor decompressor;
  9485. bool result = decompressor.decompress(
  9486. compressed_data.data(), compressed_data.size(),
  9487. [&](const char *decompressed_data_chunk,
  9488. size_t decompressed_data_chunk_size) {
  9489. decompressed_data.insert(decompressed_data.size(),
  9490. decompressed_data_chunk,
  9491. decompressed_data_chunk_size);
  9492. return true;
  9493. });
  9494. ASSERT_TRUE(result);
  9495. }
  9496. ASSERT_EQ(original_text, decompressed_data);
  9497. }
  9498. #endif
  9499. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9500. // separate chunks so that the server sees each part in its own read(). Used to
  9501. // place a read boundary at a specific offset of a request body.
  9502. static bool send_request_in_parts(time_t read_timeout_sec,
  9503. const std::vector<std::string> &parts,
  9504. std::string *resp = nullptr,
  9505. int port = PORT) {
  9506. auto error = Error::Success;
  9507. auto client_sock = detail::create_client_socket(
  9508. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9509. /*connection_timeout_sec=*/5, 0,
  9510. /*read_timeout_sec=*/5, 0,
  9511. /*write_timeout_sec=*/5, 0, std::string(), error);
  9512. if (client_sock == INVALID_SOCKET) { return false; }
  9513. auto ret = detail::process_client_socket(
  9514. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9515. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9516. for (size_t i = 0; i < parts.size(); i++) {
  9517. const auto &part = parts[i];
  9518. if (part.size() !=
  9519. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9520. return false;
  9521. }
  9522. if (i + 1 < parts.size()) {
  9523. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9524. }
  9525. }
  9526. char buf[512];
  9527. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9528. while (line_reader.getline()) {
  9529. if (resp) { *resp += line_reader.ptr(); }
  9530. }
  9531. return true;
  9532. });
  9533. detail::close_socket(client_sock);
  9534. return ret;
  9535. }
  9536. // Sends a raw request to a server listening at HOST:PORT.
  9537. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9538. std::string *resp = nullptr, int port = PORT) {
  9539. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9540. }
  9541. #ifdef CPPHTTPLIB_SSL_ENABLED
  9542. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9544. ASSERT_TRUE(svr.is_valid());
  9545. svr.set_read_timeout(1, 0);
  9546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9547. auto se = detail::scope_exit([&] {
  9548. svr.stop();
  9549. t.join();
  9550. ASSERT_FALSE(svr.is_running());
  9551. });
  9552. svr.wait_until_ready();
  9553. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9554. // keeps each wait well within the read timeout. The server gives up a
  9555. // second in, so the bytes sent after that fail.
  9556. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9557. parts.resize(26, std::string(1, '\0'));
  9558. EXPECT_FALSE(send_request_in_parts(5, parts));
  9559. }
  9560. #endif
  9561. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9562. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9563. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9564. const std::vector<std::string> &parts,
  9565. std::string *resp = nullptr,
  9566. int port = PORT) {
  9567. auto error = Error::Success;
  9568. auto sock = detail::create_client_socket(
  9569. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9570. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9571. /*write_timeout_sec=*/5, 0, std::string(), error);
  9572. if (sock == INVALID_SOCKET) { return false; }
  9573. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9574. auto ctx = SSL_CTX_new(TLS_client_method());
  9575. auto ssl = SSL_new(ctx);
  9576. auto ssl_se = detail::scope_exit([&] {
  9577. SSL_free(ssl);
  9578. SSL_CTX_free(ctx);
  9579. });
  9580. SSL_set_fd(ssl, static_cast<int>(sock));
  9581. if (SSL_connect(ssl) != 1) { return false; }
  9582. for (size_t i = 0; i < parts.size(); i++) {
  9583. const auto &part = parts[i];
  9584. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9585. static_cast<int>(part.size())) {
  9586. return false;
  9587. }
  9588. if (i + 1 < parts.size()) {
  9589. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9590. }
  9591. }
  9592. char buf[512];
  9593. int n;
  9594. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9595. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9596. }
  9597. return true;
  9598. }
  9599. #endif
  9600. // The request line, then a header value a byte at a time.
  9601. static std::vector<std::string> slow_request_head_parts() {
  9602. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9603. parts.resize(26, "a");
  9604. parts.emplace_back("\r\n\r\n");
  9605. return parts;
  9606. }
  9607. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9608. // within the one-second read timeout. The server gives up a second in, before
  9609. // the head is complete.
  9610. static void
  9611. expect_slow_request_head_dropped(Server &svr,
  9612. const std::function<std::string()> &send) {
  9613. std::atomic<bool> handled(false);
  9614. svr.Get("/", [&](const Request &, Response &res) {
  9615. handled = true;
  9616. res.set_content("ok", "text/plain");
  9617. });
  9618. svr.set_read_timeout(1, 0);
  9619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9620. auto se = detail::scope_exit([&] {
  9621. svr.stop();
  9622. t.join();
  9623. ASSERT_FALSE(svr.is_running());
  9624. });
  9625. svr.wait_until_ready();
  9626. auto resp = send();
  9627. EXPECT_FALSE(handled);
  9628. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9629. }
  9630. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9631. Server svr;
  9632. expect_slow_request_head_dropped(svr, [] {
  9633. std::string resp;
  9634. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9635. return resp;
  9636. });
  9637. }
  9638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9639. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9641. ASSERT_TRUE(svr.is_valid());
  9642. expect_slow_request_head_dropped(svr, [] {
  9643. std::string resp;
  9644. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9645. return resp;
  9646. });
  9647. }
  9648. #endif
  9649. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9650. Server svr;
  9651. std::string header_value;
  9652. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9653. header_value = req.get_header_value("foo");
  9654. res.set_content("ok", "text/plain");
  9655. });
  9656. thread t = thread([&] { svr.listen(HOST, PORT); });
  9657. auto se = detail::scope_exit([&] {
  9658. svr.stop();
  9659. t.join();
  9660. ASSERT_FALSE(svr.is_running());
  9661. });
  9662. svr.wait_until_ready();
  9663. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9664. // like characters are not treated the same - use vertical tab and escape.
  9665. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9666. "foo: \t \v bar \x1B\t \r\n"
  9667. "Connection: close\r\n"
  9668. "\r\n";
  9669. std::string res;
  9670. ASSERT_TRUE(send_request(5, req, &res));
  9671. EXPECT_EQ(header_value, "");
  9672. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9673. }
  9674. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9675. Server svr;
  9676. std::string received;
  9677. svr.Get("/order", [&](const Request &req, Response &res) {
  9678. received = entries_to_string(req.headers);
  9679. res.set_content("ok", "text/plain");
  9680. });
  9681. auto port = svr.bind_to_any_port(HOST);
  9682. thread t = thread([&] { svr.listen_after_bind(); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. t.join();
  9686. ASSERT_FALSE(svr.is_running());
  9687. });
  9688. svr.wait_until_ready();
  9689. const std::string req = "GET /order HTTP/1.1\r\n"
  9690. "Host: localhost\r\n"
  9691. "X-First: 1\r\n"
  9692. "X-Dup: a\r\n"
  9693. "X-Second: 2\r\n"
  9694. "X-Dup: b\r\n"
  9695. "Connection: close\r\n"
  9696. "\r\n";
  9697. std::string res;
  9698. ASSERT_TRUE(send_request(5, req, &res, port));
  9699. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9700. EXPECT_EQ(
  9701. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9702. received);
  9703. }
  9704. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9705. Server svr;
  9706. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9707. res.set_header("Set-Cookie", "first=1");
  9708. res.set_header("X-Between", "y");
  9709. res.set_header("Set-Cookie", "second=2");
  9710. res.set_content("ok", "text/plain");
  9711. });
  9712. auto port = svr.bind_to_any_port(HOST);
  9713. thread t = thread([&] { svr.listen_after_bind(); });
  9714. auto se = detail::scope_exit([&] {
  9715. svr.stop();
  9716. t.join();
  9717. ASSERT_FALSE(svr.is_running());
  9718. });
  9719. svr.wait_until_ready();
  9720. Client cli(HOST, port);
  9721. auto res = cli.Get("/cookies");
  9722. ASSERT_TRUE(res);
  9723. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9724. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9725. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9726. }
  9727. // A stream may send a byte at a time with a small extension on each chunk,
  9728. // however long it runs
  9729. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9730. Server svr;
  9731. svr.Post("/count", [](const Request &req, Response &res) {
  9732. res.set_content(std::to_string(req.body.size()), "text/plain");
  9733. });
  9734. auto port = svr.bind_to_any_port(HOST);
  9735. ASSERT_LT(0, port);
  9736. thread t = thread([&] { svr.listen_after_bind(); });
  9737. auto se = detail::scope_exit([&] {
  9738. svr.stop();
  9739. t.join();
  9740. ASSERT_FALSE(svr.is_running());
  9741. });
  9742. svr.wait_until_ready();
  9743. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9744. "\r\nTransfer-Encoding: chunked\r\n"
  9745. "Connection: close\r\n\r\n";
  9746. for (auto i = 0; i < 4096; i++) {
  9747. req += "1;a=b\r\nx\r\n";
  9748. }
  9749. req += "0\r\n\r\n";
  9750. std::string res;
  9751. ASSERT_TRUE(send_request(5, req, &res, port));
  9752. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9753. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9754. }
  9755. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9756. Server svr;
  9757. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9758. auto i = new int(0);
  9759. res.set_header("Trailer", "X-Safe, X-Reflected");
  9760. res.set_chunked_content_provider(
  9761. "text/plain",
  9762. [i](size_t /*offset*/, DataSink &sink) {
  9763. if (*i == 0) {
  9764. sink.os << "body";
  9765. } else {
  9766. Headers trailer;
  9767. // A valid trailer that must survive.
  9768. trailer.emplace("X-Safe", "safe");
  9769. // Attacker-controlled value carrying CR/LF (response splitting).
  9770. trailer.emplace("X-Reflected",
  9771. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9772. // Attacker-controlled name carrying CR/LF.
  9773. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9774. sink.done_with_trailer(trailer);
  9775. }
  9776. (*i)++;
  9777. return true;
  9778. },
  9779. [i](bool /*success*/) { delete i; });
  9780. });
  9781. thread t = thread([&] { svr.listen(HOST, PORT); });
  9782. auto se = detail::scope_exit([&] {
  9783. svr.stop();
  9784. t.join();
  9785. ASSERT_FALSE(svr.is_running());
  9786. });
  9787. svr.wait_until_ready();
  9788. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9789. "Host: " + HOST +
  9790. "\r\n"
  9791. "Connection: close\r\n"
  9792. "\r\n";
  9793. std::string res;
  9794. ASSERT_TRUE(send_request(5, req, &res));
  9795. // The injected fields must not appear anywhere in the raw response.
  9796. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9797. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9798. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9799. // Invalid trailers are dropped entirely, matching set_header().
  9800. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9801. // The valid trailer still passes through.
  9802. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9803. }
  9804. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9805. // A custom header writer gets only the fields the default one writes
  9806. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9807. std::string s;
  9808. for (const auto &h : hdrs) {
  9809. s += h.first + ": " + h.second + "\r\n";
  9810. }
  9811. s += "\r\n";
  9812. return strm.write(s.data(), s.size());
  9813. };
  9814. for (auto custom_writer : {false, true}) {
  9815. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9816. Server svr;
  9817. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9818. svr.set_post_routing_handler([](const Request &, Response &res) {
  9819. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9820. });
  9821. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9822. // res.headers is a public field an application can populate directly,
  9823. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9824. // A valid header that must survive.
  9825. res.headers.emplace("X-Safe", "safe");
  9826. // Attacker-controlled value carrying CR/LF (response splitting).
  9827. res.headers.emplace("X-Reflected",
  9828. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9829. // Attacker-controlled name carrying CR/LF.
  9830. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9831. res.set_content("body", "text/plain");
  9832. });
  9833. thread t = thread([&] { svr.listen(HOST, PORT); });
  9834. auto se = detail::scope_exit([&] {
  9835. svr.stop();
  9836. t.join();
  9837. ASSERT_FALSE(svr.is_running());
  9838. });
  9839. svr.wait_until_ready();
  9840. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9841. "Host: " + HOST +
  9842. "\r\n"
  9843. "Connection: close\r\n"
  9844. "\r\n";
  9845. std::string res;
  9846. ASSERT_TRUE(send_request(5, req, &res));
  9847. // The injected fields must not appear anywhere in the raw response.
  9848. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9849. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9850. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9851. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9852. // Invalid headers are dropped entirely, matching set_header().
  9853. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9854. // The valid header still passes through.
  9855. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9856. }
  9857. }
  9858. // Forward declaration: in split builds split.py strips `inline` and moves the
  9859. // definition into httplib.cc, so detail::write_request_line is not visible from
  9860. // the public httplib.h. Re-declaring it here lets the tests link against the
  9861. // symbol in both header-only and split builds.
  9862. namespace httplib {
  9863. namespace detail {
  9864. ssize_t write_request_line(Stream &strm, const std::string &method,
  9865. const std::string &path);
  9866. } // namespace detail
  9867. } // namespace httplib
  9868. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9869. // A well-formed target is written verbatim.
  9870. {
  9871. detail::BufferStream strm;
  9872. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9873. EXPECT_GT(n, 0);
  9874. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9875. }
  9876. // A target carrying CR/LF, SP or other control octets must be rejected
  9877. // before anything reaches the wire, otherwise it splits the request line and
  9878. // injects a header or a whole request.
  9879. const std::string evil_targets[] = {
  9880. "/a\r\nInjected: pwned",
  9881. "/a\rInjected",
  9882. "/a\nInjected",
  9883. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9884. "/a b",
  9885. "/a\tb",
  9886. "/a\x7f",
  9887. };
  9888. for (const auto &evil : evil_targets) {
  9889. detail::BufferStream strm;
  9890. auto n = detail::write_request_line(strm, "GET", evil);
  9891. EXPECT_LT(n, 0);
  9892. EXPECT_TRUE(strm.get_buffer().empty());
  9893. }
  9894. }
  9895. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9896. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9897. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9898. // target reaches write_request. The client must fail cleanly with
  9899. // Error::Write instead of putting a request-line-less, header-injecting
  9900. // request on the wire.
  9901. Server svr;
  9902. svr.Get("/a", [](const Request &, Response &res) {
  9903. res.set_content("ok", "text/plain");
  9904. });
  9905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. thread.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. });
  9911. svr.wait_until_ready();
  9912. {
  9913. Client cli(HOST, PORT);
  9914. cli.set_path_encode(false);
  9915. // The request is rejected before anything is written, so the connection
  9916. // stays silent and the subsequent response read would otherwise block for
  9917. // the full default read timeout. Shorten it -- the assertion is on the
  9918. // error, not the timeout.
  9919. cli.set_read_timeout(1, 0);
  9920. auto res = cli.Get("/a\r\nInjected: pwned");
  9921. EXPECT_FALSE(res);
  9922. EXPECT_EQ(Error::Write, res.error());
  9923. }
  9924. }
  9925. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9926. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9927. // including extension methods.
  9928. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9929. for (const auto &method : good_methods) {
  9930. detail::BufferStream strm;
  9931. auto n = detail::write_request_line(strm, method, "/");
  9932. EXPECT_GT(n, 0);
  9933. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9934. }
  9935. // A method carrying CR/LF would split the request line and smuggle a whole
  9936. // request ahead of the real one. A space or an empty method corrupts the
  9937. // request line. All must be rejected before anything reaches the wire.
  9938. const std::string evil_methods[] = {
  9939. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9940. "GET\r\nInjected: pwned",
  9941. "GET\r",
  9942. "GET\n",
  9943. "GE T",
  9944. "",
  9945. };
  9946. for (const auto &evil : evil_methods) {
  9947. detail::BufferStream strm;
  9948. auto n = detail::write_request_line(strm, evil, "/");
  9949. EXPECT_LT(n, 0);
  9950. EXPECT_TRUE(strm.get_buffer().empty());
  9951. }
  9952. }
  9953. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9954. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9955. // through Client::send must fail with Error::Write and no request, neither
  9956. // the smuggled one nor the real one, may reach the server.
  9957. Server svr;
  9958. std::atomic<int> request_count(0);
  9959. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9960. request_count++;
  9961. res.status = StatusCode::OK_200;
  9962. return Server::HandlerResponse::Handled;
  9963. });
  9964. auto port = svr.bind_to_any_port(HOST);
  9965. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9966. auto se = detail::scope_exit([&] {
  9967. svr.stop();
  9968. thread.join();
  9969. ASSERT_FALSE(svr.is_running());
  9970. });
  9971. svr.wait_until_ready();
  9972. {
  9973. Client cli(HOST, port);
  9974. const std::string evil_methods[] = {
  9975. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9976. "GE T",
  9977. "",
  9978. };
  9979. for (const auto &evil : evil_methods) {
  9980. Request req;
  9981. req.method = evil;
  9982. req.path = "/";
  9983. auto res = cli.send(req);
  9984. EXPECT_FALSE(res);
  9985. EXPECT_EQ(Error::Write, res.error());
  9986. }
  9987. auto handle =
  9988. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9989. EXPECT_FALSE(handle.is_valid());
  9990. EXPECT_EQ(Error::Write, handle.error);
  9991. // A valid request on the same client still goes through.
  9992. auto res = cli.Get("/");
  9993. ASSERT_TRUE(res);
  9994. EXPECT_EQ(StatusCode::OK_200, res->status);
  9995. }
  9996. EXPECT_EQ(1, request_count.load());
  9997. }
  9998. // Sends a raw request and verifies that there isn't a crash or exception.
  9999. static void test_raw_request(const std::string &req,
  10000. std::string *out = nullptr) {
  10001. Server svr;
  10002. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10003. res.set_content("ok", "text/plain");
  10004. });
  10005. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10006. res.set_content("ok", "text/plain");
  10007. });
  10008. svr.Get("/header_field_value_check",
  10009. [&](const Request & /*req*/, Response &res) {
  10010. res.set_content("ok", "text/plain");
  10011. });
  10012. svr.CustomRoute("PROPFIND", "/dav",
  10013. [&](const Request & /*req*/, Response &res) {
  10014. res.status = StatusCode::MultiStatus_207;
  10015. });
  10016. // Server read timeout must be longer than the client read timeout for the
  10017. // bug to reproduce, probably to force the server to process a request
  10018. // without a trailing blank line.
  10019. const time_t client_read_timeout_sec = 1;
  10020. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10021. bool listen_thread_ok = false;
  10022. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. EXPECT_TRUE(listen_thread_ok);
  10028. });
  10029. svr.wait_until_ready();
  10030. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10031. }
  10032. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10033. // A certain header line causes an exception if the header property is parsed
  10034. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10035. test_raw_request(
  10036. "GET /hi HTTP/1.1\r\n"
  10037. " : "
  10038. " "
  10039. " ");
  10040. }
  10041. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10042. // A certain header line causes an exception if the header property *name* is
  10043. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10044. // greedy matcher and requires backtracking when there are a lot of ":"
  10045. // characters.
  10046. // This occurs with libc++ but not libstdc++.
  10047. test_raw_request(
  10048. "GET /hi HTTP/1.1\r\n"
  10049. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10050. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10051. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10052. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10053. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10054. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10055. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10056. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10057. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10058. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10059. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10060. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10061. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10062. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10063. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10064. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10065. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10066. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10067. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10068. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10069. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10070. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10071. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10072. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10073. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10074. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10075. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10076. "&&&%%%");
  10077. }
  10078. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10079. // Make sure this doesn't crash the server.
  10080. // In a previous version of the header line regex, the "\r" rendered the line
  10081. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10082. // a new position where the leading white space ended and the field value
  10083. // began.
  10084. // The crash occurs with libc++ but not libstdc++.
  10085. test_raw_request("GET /hi HTTP/1.1\r\n"
  10086. "a:" +
  10087. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10088. "\r\n"
  10089. "\r\n");
  10090. }
  10091. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10092. const char *rejected[] = {
  10093. // RFC 9112 §3: one SP between the parts, and nothing else
  10094. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10095. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10096. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10097. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10098. // A request-target has no fragment
  10099. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10100. // An HTTP/1.1 request needs a Host
  10101. "GET /hi HTTP/1.1\r\n\r\n",
  10102. };
  10103. for (auto request : rejected) {
  10104. std::string out;
  10105. test_raw_request(request, &out);
  10106. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10107. }
  10108. std::string out;
  10109. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10110. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10111. }
  10112. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10113. // RFC 9112 §6.1
  10114. const char *requests[] = {
  10115. "PUT /put_hi HTTP/1.1\r\n"
  10116. "Host: localhost\r\n"
  10117. "Content-Length: 0\r\n"
  10118. "Transfer-Encoding: chunked\r\n"
  10119. "\r\n"
  10120. "0\r\n\r\n",
  10121. "PUT /put_hi HTTP/1.0\r\n"
  10122. "Connection: keep-alive\r\n"
  10123. "Transfer-Encoding: chunked\r\n"
  10124. "\r\n"
  10125. "0\r\n\r\n",
  10126. };
  10127. for (auto request : requests) {
  10128. std::string out;
  10129. test_raw_request(request, &out);
  10130. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10131. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10132. }
  10133. }
  10134. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10135. std::string out;
  10136. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10137. "Content-Type: text/plain\r\n"
  10138. "Transfer-Encoding: chunked\r\n"
  10139. "\r\n"
  10140. "nothex\r\n",
  10141. &out);
  10142. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10143. }
  10144. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10145. std::string out;
  10146. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10147. "Content-Type: text/plain\r\n"
  10148. "Transfer-Encoding: chunked\r\n"
  10149. "\r\n"
  10150. "3\r\n"
  10151. "xyz\r\n"
  10152. "NaN\r\n",
  10153. &out);
  10154. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10155. }
  10156. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10157. std::string out;
  10158. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10159. "Content-Type: text/plain\r\n"
  10160. "Transfer-Encoding: chunked\r\n"
  10161. "\r\n"
  10162. // Length is too large for 64 bits.
  10163. "1ffffffffffffffff\r\n"
  10164. "xyz\r\n",
  10165. &out);
  10166. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10167. }
  10168. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10169. test_raw_request("GET /hi HTTP/1.1\r\n"
  10170. "Content-Type: text/plain\r\n\r");
  10171. }
  10172. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10173. std::string out;
  10174. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10175. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10176. }
  10177. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10178. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10179. std::string out;
  10180. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10181. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10182. }
  10183. }
  10184. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10185. std::string out;
  10186. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10187. "Host: localhost\r\n"
  10188. "Connection: close\r\n\r\n",
  10189. &out);
  10190. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10191. }
  10192. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10193. Server svr;
  10194. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10195. EXPECT_TRUE(!req.remote_addr.empty());
  10196. });
  10197. thread t = thread([&] { svr.listen(HOST, PORT); });
  10198. auto se = detail::scope_exit([&] {
  10199. svr.stop();
  10200. t.join();
  10201. ASSERT_FALSE(svr.is_running());
  10202. });
  10203. svr.wait_until_ready();
  10204. // Send an invalid request line to trigger Bad Request
  10205. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10206. std::string out;
  10207. ASSERT_TRUE(send_request(5, bad_req, &out));
  10208. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10209. }
  10210. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10211. // answered right away rather than blocking on a read that waits for EOF.
  10212. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10213. std::string out;
  10214. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10215. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10216. }
  10217. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10218. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10219. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10220. for (const auto *method : methods) {
  10221. Server svr;
  10222. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10223. EXPECT_FALSE(svr.is_valid()) << method;
  10224. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10225. }
  10226. }
  10227. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10228. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10229. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10230. for (const auto *method : methods) {
  10231. Server svr;
  10232. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10233. EXPECT_FALSE(svr.is_valid()) << method;
  10234. }
  10235. }
  10236. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10237. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10238. "COPY", "MOVE", "LOCK",
  10239. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10240. Server svr;
  10241. for (const auto *method : methods) {
  10242. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10243. }
  10244. EXPECT_TRUE(svr.is_valid());
  10245. }
  10246. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10247. Server svr;
  10248. svr.CustomRoute("POST", "/x",
  10249. [](const Request &, Response &, const ContentReader &) {});
  10250. EXPECT_FALSE(svr.is_valid());
  10251. }
  10252. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10253. Server svr;
  10254. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10255. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10256. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10257. EXPECT_FALSE(svr.is_valid());
  10258. }
  10259. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10260. Server svr;
  10261. auto captured = Error::Success;
  10262. svr.set_error_logger(
  10263. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10264. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10265. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10266. }
  10267. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10268. std::string out;
  10269. std::string request(
  10270. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10271. test_raw_request(request, &out);
  10272. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10273. }
  10274. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10275. std::string out;
  10276. std::string request(
  10277. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10278. test_raw_request(request, &out);
  10279. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10280. }
  10281. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10282. std::string out;
  10283. std::string request(
  10284. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10285. test_raw_request(request, &out);
  10286. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10287. }
  10288. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10289. std::string out;
  10290. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10291. "Host: localhost\r\n"
  10292. "Test: \r\n\r\n",
  10293. &out);
  10294. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10295. }
  10296. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10297. Server svr;
  10298. std::string x_custom;
  10299. std::string cookie;
  10300. std::string xff;
  10301. std::string x_unicode;
  10302. std::string x_iis;
  10303. svr.Get("/check", [&](const Request &req, Response &res) {
  10304. x_custom = req.get_header_value("X-Custom");
  10305. cookie = req.get_header_value("Cookie");
  10306. xff = req.get_header_value("X-Forwarded-For");
  10307. x_unicode = req.get_header_value("X-Unicode");
  10308. x_iis = req.get_header_value("X-IIS");
  10309. res.set_content("ok", "text/plain");
  10310. });
  10311. thread t = thread([&] { svr.listen(HOST, PORT); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. t.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. const std::string req = "GET /check HTTP/1.1\r\n"
  10319. "Host: localhost\r\n"
  10320. "X-Custom: a%0D%0AInjected: b\r\n"
  10321. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10322. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10323. "X-Unicode: %E3%81%82\r\n"
  10324. "X-IIS: %u00E9\r\n"
  10325. "Connection: close\r\n"
  10326. "\r\n";
  10327. std::string res;
  10328. ASSERT_TRUE(send_request(5, req, &res));
  10329. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10330. // Every value must be returned verbatim (wire form), with no decoding.
  10331. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10332. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10333. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10334. EXPECT_EQ("%E3%81%82", x_unicode);
  10335. EXPECT_EQ("%u00E9", x_iis);
  10336. }
  10337. // Applications that previously relied on automatic percent-decoding can
  10338. // reproduce the old behavior by explicitly calling decode_path_component()
  10339. // or, for RFC 3986 conformance, decode_uri_component().
  10340. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10341. Server svr;
  10342. std::string decoded;
  10343. svr.Get("/check", [&](const Request &req, Response &res) {
  10344. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10345. res.set_content("ok", "text/plain");
  10346. });
  10347. thread t = thread([&] { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. ASSERT_FALSE(svr.is_running());
  10352. });
  10353. svr.wait_until_ready();
  10354. const std::string req = "GET /check HTTP/1.1\r\n"
  10355. "Host: localhost\r\n"
  10356. "X-Custom: hello%20world\r\n"
  10357. "Connection: close\r\n"
  10358. "\r\n";
  10359. std::string res;
  10360. ASSERT_TRUE(send_request(5, req, &res));
  10361. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10362. EXPECT_EQ("hello world", decoded);
  10363. }
  10364. // Regression test for #2033. Browsers send Referer values that include
  10365. // percent-encoded characters such as %0A inside the URL. Decoding the
  10366. // header value would either trip the post-decode CR/LF/NUL guard (the
  10367. // original bug, returning 400) or, after that guard was relaxed, silently
  10368. // store a literal LF — both unacceptable. The wire form must round-trip.
  10369. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10370. Server svr;
  10371. std::string referer;
  10372. svr.Get("/check", [&](const Request &req, Response &res) {
  10373. referer = req.get_header_value("Referer");
  10374. res.set_content("ok", "text/plain");
  10375. });
  10376. thread t = thread([&] { svr.listen(HOST, PORT); });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. t.join();
  10380. ASSERT_FALSE(svr.is_running());
  10381. });
  10382. svr.wait_until_ready();
  10383. const std::string req = "GET /check HTTP/1.1\r\n"
  10384. "Host: localhost\r\n"
  10385. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10386. "Connection: close\r\n"
  10387. "\r\n";
  10388. std::string res;
  10389. ASSERT_TRUE(send_request(5, req, &res));
  10390. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10391. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10392. }
  10393. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10394. Server svr;
  10395. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10396. res.set_header("Cache-Control", "no-cache");
  10397. res.set_chunked_content_provider(
  10398. "text/event-stream", [](size_t offset, DataSink &sink) {
  10399. std::string s = "data:";
  10400. s += std::to_string(offset);
  10401. s += "\n\n";
  10402. auto ret = sink.write(s.data(), s.size());
  10403. EXPECT_TRUE(ret);
  10404. std::this_thread::sleep_for(std::chrono::seconds(1));
  10405. return true;
  10406. });
  10407. });
  10408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10409. svr.wait_until_ready();
  10410. Client client(HOST, PORT);
  10411. const Headers headers = {{"Accept", "text/event-stream"}};
  10412. auto get_thread = std::thread([&client, &headers]() {
  10413. auto res = client.Get(
  10414. "/events", headers,
  10415. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10416. });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. get_thread.join();
  10420. listen_thread.join();
  10421. ASSERT_FALSE(svr.is_running());
  10422. });
  10423. // Give GET time to get a few messages.
  10424. std::this_thread::sleep_for(std::chrono::seconds(2));
  10425. }
  10426. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10427. httplib::Server svr;
  10428. svr.Post("/hi",
  10429. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10430. res.status = StatusCode::OK_200;
  10431. });
  10432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10433. svr.wait_until_ready();
  10434. Client cli(HOST, PORT);
  10435. auto res = cli.Post("/hi", "data", "text/plain");
  10436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10437. EXPECT_EQ(StatusCode::OK_200, res->status);
  10438. svr.stop();
  10439. thread.join();
  10440. ASSERT_FALSE(svr.is_running());
  10441. res = cli.Post("/hi", "data", "text/plain");
  10442. ASSERT_FALSE(res);
  10443. }
  10444. TEST(ServerStopTest, ListenFailure) {
  10445. Server svr;
  10446. auto t = thread([&]() {
  10447. auto ret = svr.listen("????", PORT);
  10448. EXPECT_FALSE(ret);
  10449. });
  10450. svr.wait_until_ready();
  10451. svr.stop();
  10452. t.join();
  10453. }
  10454. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10455. TEST(ServerStopTest, Decommision) {
  10456. Server svr;
  10457. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10458. for (int i = 0; i < 4; i++) {
  10459. auto is_even = !(i % 2);
  10460. std::thread t{[&] {
  10461. try {
  10462. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10463. if (is_even) {
  10464. throw std::runtime_error("Some thing that happens to go wrong.");
  10465. }
  10466. svr.listen(HOST, PORT);
  10467. } catch (...) { svr.decommission(); }
  10468. }};
  10469. svr.wait_until_ready();
  10470. // Server is up
  10471. {
  10472. Client cli(HOST, PORT);
  10473. auto res = cli.Get("/hi");
  10474. if (is_even) {
  10475. EXPECT_FALSE(res);
  10476. } else {
  10477. EXPECT_TRUE(res);
  10478. EXPECT_EQ("hi...", res->body);
  10479. }
  10480. }
  10481. svr.stop();
  10482. t.join();
  10483. // Server is down...
  10484. {
  10485. Client cli(HOST, PORT);
  10486. auto res = cli.Get("/hi");
  10487. EXPECT_FALSE(res);
  10488. }
  10489. }
  10490. }
  10491. #endif
  10492. // Helper function for string body upload progress tests
  10493. template <typename SetupHandler, typename ClientCall>
  10494. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10495. ClientCall &&client_call,
  10496. const string &body) {
  10497. Server svr;
  10498. setup_handler(svr);
  10499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10500. auto se = detail::scope_exit([&] {
  10501. svr.stop();
  10502. t.join();
  10503. });
  10504. svr.wait_until_ready();
  10505. Client cli(HOST, PORT);
  10506. vector<uint64_t> progress_values;
  10507. bool progress_called = false;
  10508. auto res =
  10509. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10510. progress_values.push_back(current);
  10511. progress_called = true;
  10512. return true;
  10513. });
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(200, res->status);
  10516. EXPECT_TRUE(progress_called);
  10517. }
  10518. TEST(UploadProgressTest, PostStringBodyBasic) {
  10519. TestStringBodyUploadProgress(
  10520. [](Server &svr) {
  10521. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10522. res.set_content("received", "text/plain");
  10523. });
  10524. },
  10525. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10526. return cli.Post("/test", body, "text/plain", progress_callback);
  10527. },
  10528. "test data for upload progress");
  10529. }
  10530. TEST(UploadProgressTest, PutStringBodyBasic) {
  10531. TestStringBodyUploadProgress(
  10532. [](Server &svr) {
  10533. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10534. res.set_content("put received", "text/plain");
  10535. });
  10536. },
  10537. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10538. return cli.Put("/test", body, "text/plain", progress_callback);
  10539. },
  10540. "put test data for upload progress");
  10541. }
  10542. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10543. TestStringBodyUploadProgress(
  10544. [](Server &svr) {
  10545. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10546. res.set_content("patch received", "text/plain");
  10547. });
  10548. },
  10549. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10550. return cli.Patch("/test", body, "text/plain", progress_callback);
  10551. },
  10552. "patch test data for upload progress");
  10553. }
  10554. // Helper function for content provider upload progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call) {
  10558. Server svr;
  10559. setup_handler(svr);
  10560. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10561. auto se = detail::scope_exit([&] {
  10562. svr.stop();
  10563. t.join();
  10564. });
  10565. svr.wait_until_ready();
  10566. Client cli(HOST, PORT);
  10567. vector<uint64_t> progress_values;
  10568. auto res =
  10569. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10570. progress_values.push_back(current);
  10571. return true;
  10572. });
  10573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10574. EXPECT_EQ(200, res->status);
  10575. EXPECT_FALSE(progress_values.empty());
  10576. }
  10577. TEST(UploadProgressTest, PostContentProviderProgress) {
  10578. TestContentProviderUploadProgress(
  10579. [](Server &svr) {
  10580. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10581. res.set_content("provider received", "text/plain");
  10582. });
  10583. },
  10584. [](Client &cli, UploadProgress progress_callback) {
  10585. return cli.Post(
  10586. "/test", 9,
  10587. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10588. sink.os << "test data";
  10589. return true;
  10590. },
  10591. "text/plain", progress_callback);
  10592. });
  10593. }
  10594. // Helper function for multipart upload progress tests
  10595. template <typename SetupHandler, typename ClientCall>
  10596. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10597. ClientCall &&client_call,
  10598. const string &endpoint) {
  10599. Server svr;
  10600. setup_handler(svr);
  10601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10602. auto se = detail::scope_exit([&] {
  10603. svr.stop();
  10604. t.join();
  10605. });
  10606. svr.wait_until_ready();
  10607. Client cli(HOST, PORT);
  10608. vector<uint64_t> progress_values;
  10609. UploadFormDataItems items = {
  10610. {"field1", "value1", "", ""},
  10611. {"field2", "longer value for progress tracking test", "", ""},
  10612. {"file1", "file content data for upload progress", "test.txt",
  10613. "text/plain"}};
  10614. auto res = client_call(cli, endpoint, items,
  10615. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10616. progress_values.push_back(current);
  10617. return true;
  10618. });
  10619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10620. EXPECT_EQ(200, res->status);
  10621. EXPECT_FALSE(progress_values.empty());
  10622. }
  10623. TEST(UploadProgressTest, PostMultipartProgress) {
  10624. TestMultipartUploadProgress(
  10625. [](Server &svr) {
  10626. svr.Post("/multipart", [](const Request &req, Response &res) {
  10627. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10628. res.set_content("multipart received", "text/plain");
  10629. });
  10630. },
  10631. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10632. UploadProgress progress_callback) {
  10633. return cli.Post(endpoint, items, progress_callback);
  10634. },
  10635. "/multipart");
  10636. }
  10637. // Helper function for basic download progress tests
  10638. template <typename SetupHandler, typename ClientCall>
  10639. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10640. ClientCall &&client_call, const string &endpoint,
  10641. size_t expected_content_size) {
  10642. Server svr;
  10643. setup_handler(svr);
  10644. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. t.join();
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. vector<uint64_t> progress_values;
  10652. auto res = client_call(cli, endpoint,
  10653. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10654. progress_values.push_back(current);
  10655. return true;
  10656. });
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(200, res->status);
  10659. EXPECT_FALSE(progress_values.empty());
  10660. EXPECT_EQ(expected_content_size, res->body.size());
  10661. }
  10662. TEST(DownloadProgressTest, GetBasic) {
  10663. TestBasicDownloadProgress(
  10664. [](Server &svr) {
  10665. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10666. string content(1000, 'D');
  10667. res.set_content(content, "text/plain");
  10668. });
  10669. },
  10670. [](Client &cli, const string &endpoint,
  10671. DownloadProgress progress_callback) {
  10672. return cli.Get(endpoint, progress_callback);
  10673. },
  10674. "/download", 1000u);
  10675. }
  10676. // Helper function for content receiver download progress tests
  10677. template <typename SetupHandler, typename ClientCall>
  10678. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10679. ClientCall &&client_call,
  10680. const string &endpoint,
  10681. size_t expected_content_size) {
  10682. Server svr;
  10683. setup_handler(svr);
  10684. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10685. auto se = detail::scope_exit([&] {
  10686. svr.stop();
  10687. t.join();
  10688. });
  10689. svr.wait_until_ready();
  10690. Client cli(HOST, PORT);
  10691. vector<uint64_t> progress_values;
  10692. string received_body;
  10693. auto res = client_call(
  10694. cli, endpoint,
  10695. [&](const char *data, size_t data_length) -> bool {
  10696. received_body.append(data, data_length);
  10697. return true;
  10698. },
  10699. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10700. progress_values.push_back(current);
  10701. return true;
  10702. });
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ(200, res->status);
  10705. EXPECT_FALSE(progress_values.empty());
  10706. EXPECT_EQ(expected_content_size, received_body.size());
  10707. EXPECT_TRUE(res->body.empty());
  10708. }
  10709. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10710. TestContentReceiverDownloadProgress(
  10711. [](Server &svr) {
  10712. svr.Get("/download-receiver",
  10713. [](const Request & /*req*/, Response &res) {
  10714. string content(2000, 'R');
  10715. res.set_content(content, "text/plain");
  10716. });
  10717. },
  10718. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10719. DownloadProgress progress_callback) {
  10720. return cli.Get(endpoint, content_receiver, progress_callback);
  10721. },
  10722. "/download-receiver", 2000u);
  10723. }
  10724. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10725. // A provider reaching a pass with nothing to hand over - an empty buffer
  10726. // popped off a queue, say - must not be taken to mean the body is finished.
  10727. // It used to end the loop with the terminating chunk unwritten while the
  10728. // server still considered the response complete, so the peer waited for an
  10729. // end that never arrived.
  10730. Server svr;
  10731. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10732. auto step = std::make_shared<int>(0);
  10733. res.set_chunked_content_provider("text/plain",
  10734. [step](size_t /*offset*/, DataSink &sink) {
  10735. switch ((*step)++) {
  10736. case 0: sink.write("", 0); break;
  10737. case 1: sink.write("hello", 5); break;
  10738. default: sink.done(); break;
  10739. }
  10740. return true;
  10741. });
  10742. });
  10743. auto port = svr.bind_to_any_port(HOST);
  10744. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10745. auto listen_se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli(HOST, port);
  10752. // Without the fix the body is never terminated, so bound the wait rather
  10753. // than letting the test hang on the default read timeout.
  10754. cli.set_read_timeout(5, 0);
  10755. auto res = cli.Get("/stream");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(StatusCode::OK_200, res->status);
  10758. EXPECT_EQ("hello", res->body);
  10759. }
  10760. TEST(StreamingTest, NoContentLengthStreaming) {
  10761. Server svr;
  10762. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10763. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10764. if (offset < 6) {
  10765. sink.os << (offset < 3 ? "a" : "b");
  10766. } else {
  10767. sink.done();
  10768. }
  10769. return true;
  10770. });
  10771. });
  10772. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10773. auto listen_se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. listen_thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. Client client(HOST, PORT);
  10780. auto get_thread = std::thread([&client]() {
  10781. std::string s;
  10782. auto res =
  10783. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10784. s += std::string(data, len);
  10785. return true;
  10786. });
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. EXPECT_EQ(StatusCode::OK_200, res->status);
  10789. EXPECT_EQ("aaabbb", s);
  10790. });
  10791. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10792. // Give GET time to get a few messages.
  10793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10794. }
  10795. TEST(MountTest, Unmount) {
  10796. Server svr;
  10797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10798. auto 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 cli("localhost", PORT);
  10805. svr.set_mount_point("/mount2", "./www2");
  10806. auto res = cli.Get("/");
  10807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10808. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10809. res = cli.Get("/mount2/dir/test.html");
  10810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10811. EXPECT_EQ(StatusCode::OK_200, res->status);
  10812. svr.set_mount_point("/", "./www");
  10813. res = cli.Get("/dir/");
  10814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10815. EXPECT_EQ(StatusCode::OK_200, res->status);
  10816. svr.remove_mount_point("/");
  10817. res = cli.Get("/dir/");
  10818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10820. svr.remove_mount_point("/mount2");
  10821. res = cli.Get("/mount2/dir/test.html");
  10822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10823. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10824. }
  10825. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10826. Server svr;
  10827. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10828. svr.Get("/api/hello", [](const Request &, Response &res) {
  10829. res.set_content("api", "text/plain");
  10830. });
  10831. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10832. auto se = detail::scope_exit([&] {
  10833. svr.stop();
  10834. listen_thread.join();
  10835. ASSERT_FALSE(svr.is_running());
  10836. });
  10837. svr.wait_until_ready();
  10838. Client cli(HOST, PORT);
  10839. auto res = cli.Get("/dir/test.html");
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. res = cli.Get("/api/hello");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ(StatusCode::OK_200, res->status);
  10845. EXPECT_EQ("api", res->body);
  10846. }
  10847. TEST(MountTest, PathSegmentBoundary) {
  10848. Server svr;
  10849. svr.set_mount_point("/mount2", "./www2");
  10850. svr.set_mount_point("/", "./www");
  10851. auto port = svr.bind_to_any_port(HOST);
  10852. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. listen_thread.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. Client cli(HOST, port);
  10860. auto res = cli.Get("/mount2/dir/test.html");
  10861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10862. EXPECT_EQ(StatusCode::OK_200, res->status);
  10863. // "/mount2" must not match part-way through a path segment.
  10864. res = cli.Get("/mount2dir/test.html");
  10865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10866. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10867. // A mount point ending in '/' keeps matching every path below it.
  10868. res = cli.Get("/dir/test.html");
  10869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10870. EXPECT_EQ(StatusCode::OK_200, res->status);
  10871. }
  10872. TEST(MountTest, Redicect) {
  10873. Server svr;
  10874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. listen_thread.join();
  10878. ASSERT_FALSE(svr.is_running());
  10879. });
  10880. svr.set_mount_point("/", "./www");
  10881. svr.wait_until_ready();
  10882. Client cli("localhost", PORT);
  10883. auto res = cli.Get("/dir/");
  10884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10885. EXPECT_EQ(StatusCode::OK_200, res->status);
  10886. res = cli.Get("/dir");
  10887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10889. res = cli.Get("/file");
  10890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10891. EXPECT_EQ(StatusCode::OK_200, res->status);
  10892. res = cli.Get("/file/");
  10893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10895. cli.set_follow_location(true);
  10896. res = cli.Get("/dir");
  10897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10898. EXPECT_EQ(StatusCode::OK_200, res->status);
  10899. }
  10900. TEST(MountTest, MultibytesPathName) {
  10901. Server svr;
  10902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10903. auto se = detail::scope_exit([&] {
  10904. svr.stop();
  10905. listen_thread.join();
  10906. ASSERT_FALSE(svr.is_running());
  10907. });
  10908. svr.set_mount_point("/", "./www");
  10909. svr.wait_until_ready();
  10910. Client cli("localhost", PORT);
  10911. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10915. }
  10916. // A mount point serves no path with an empty segment or one ending in '.' or
  10917. // a space, so a guard in the pre-routing handler sees the path of every file
  10918. // that is served
  10919. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10920. Server svr;
  10921. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10922. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10923. if (req.path == "/dir/test.html") {
  10924. res.status = StatusCode::Unauthorized_401;
  10925. return Server::HandlerResponse::Handled;
  10926. }
  10927. return Server::HandlerResponse::Unhandled;
  10928. });
  10929. auto port = svr.bind_to_any_port(HOST);
  10930. ASSERT_LT(0, port);
  10931. thread t = thread([&] { svr.listen_after_bind(); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. });
  10937. svr.wait_until_ready();
  10938. Client cli(HOST, port);
  10939. for (auto path :
  10940. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10941. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10942. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10943. "/dir/test.html%3A%3A$DATA"}) {
  10944. SCOPED_TRACE(path);
  10945. auto res = cli.Get(path);
  10946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10948. }
  10949. }
  10950. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10951. Server svr;
  10952. svr.set_mount_point("/", "./www");
  10953. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10954. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10955. auto port = svr.bind_to_any_port(HOST);
  10956. ASSERT_GT(port, 0);
  10957. thread t = thread([&] { svr.listen_after_bind(); });
  10958. auto se = detail::scope_exit([&] {
  10959. svr.stop();
  10960. t.join();
  10961. ASSERT_FALSE(svr.is_running());
  10962. });
  10963. svr.wait_until_ready();
  10964. Client cli(HOST, port);
  10965. auto res = cli.Get("/dir/test.abcde");
  10966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10967. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10968. res = cli.Get("/dir/test.html");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10971. }
  10972. #ifdef _WIN32
  10973. // Issue #2435: mmap::open() must succeed even when another handle holds
  10974. // the file open for writing (e.g. an active log file).
  10975. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10976. const char *path = "mmap_concurrent_writer_test.txt";
  10977. const char *content = "hello";
  10978. {
  10979. std::ofstream f(path, std::ios::binary);
  10980. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10981. }
  10982. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10983. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10984. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10985. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10986. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10987. detail::mmap m(path);
  10988. ASSERT_TRUE(m.is_open());
  10989. EXPECT_EQ(strlen(content), m.size());
  10990. char buf[8];
  10991. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10992. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10993. }
  10994. #endif
  10995. #ifndef _WIN32
  10996. // A directory or a device has no size to serve.
  10997. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10998. const char *path = "./mmap_not_regular_test_dir";
  10999. ASSERT_EQ(0, ::mkdir(path, 0755));
  11000. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11001. for (auto p : {path, "/dev/null"}) {
  11002. detail::mmap m(p);
  11003. EXPECT_FALSE(m.is_open()) << p;
  11004. EXPECT_EQ(0U, m.size()) << p;
  11005. }
  11006. Server svr;
  11007. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11008. res.set_file_content("/dev/null");
  11009. });
  11010. auto port = svr.bind_to_any_port(HOST);
  11011. thread t = thread([&] { svr.listen_after_bind(); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. t.join();
  11015. });
  11016. svr.wait_until_ready();
  11017. auto res = Client(HOST, port).Get("/null");
  11018. ASSERT_TRUE(res);
  11019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11020. }
  11021. #endif
  11022. #ifdef __linux__
  11023. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11024. TEST(MmapTest, FileIsNotMapped) {
  11025. const char *path = "mmap_not_mapped_test.txt";
  11026. {
  11027. std::ofstream f(path, std::ios::binary);
  11028. f << "hello";
  11029. }
  11030. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11031. detail::mmap m(path);
  11032. ASSERT_TRUE(m.is_open());
  11033. std::ifstream maps("/proc/self/maps");
  11034. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11035. std::istreambuf_iterator<char>());
  11036. EXPECT_EQ(std::string::npos, mappings.find(path));
  11037. }
  11038. #endif
  11039. TEST(KeepAliveTest, ReadTimeout) {
  11040. Server svr;
  11041. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11042. std::this_thread::sleep_for(std::chrono::seconds(2));
  11043. res.set_content("a", "text/plain");
  11044. });
  11045. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11046. res.set_content("b", "text/plain");
  11047. });
  11048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. listen_thread.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli("localhost", PORT);
  11056. cli.set_keep_alive(true);
  11057. cli.set_read_timeout(std::chrono::seconds(1));
  11058. auto resa = cli.Get("/a");
  11059. ASSERT_FALSE(resa);
  11060. EXPECT_EQ(Error::Read, resa.error());
  11061. auto resb = cli.Get("/b");
  11062. ASSERT_TRUE(resb);
  11063. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11064. EXPECT_EQ("b", resb->body);
  11065. }
  11066. TEST(KeepAliveTest, MaxCount) {
  11067. size_t keep_alive_max_count = 3;
  11068. Server svr;
  11069. svr.set_keep_alive_max_count(keep_alive_max_count);
  11070. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11071. res.set_content("Hello World!", "text/plain");
  11072. });
  11073. auto listen_thread = std::thread([&svr] { svr.listen(HOST, 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(HOST, PORT);
  11081. cli.set_keep_alive(true);
  11082. for (size_t i = 0; i < 5; i++) {
  11083. auto result = cli.Get("/hi");
  11084. ASSERT_TRUE(result);
  11085. EXPECT_EQ(StatusCode::OK_200, result->status);
  11086. if (i == keep_alive_max_count - 1) {
  11087. EXPECT_EQ("close", result->get_header_value("Connection"));
  11088. } else {
  11089. EXPECT_FALSE(result->has_header("Connection"));
  11090. }
  11091. }
  11092. }
  11093. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11094. // can pull the next one into the server's buffer. The server must serve it
  11095. // without waiting for the socket to become readable again. The keep-alive
  11096. // timeout outlasts the client's read timeout, so a request left waiting for it
  11097. // shows up as a missing response.
  11098. static void serve_pipelining_routes(Server &svr,
  11099. const std::function<void(int)> &client) {
  11100. svr.set_keep_alive_timeout(5);
  11101. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11102. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11103. });
  11104. svr.Post("/echo", [](const Request &req, Response &res) {
  11105. res.set_content("echo " + req.body, "text/plain");
  11106. });
  11107. auto port = svr.bind_to_any_port(HOST);
  11108. thread t = thread([&] { svr.listen_after_bind(); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. });
  11113. svr.wait_until_ready();
  11114. client(port);
  11115. }
  11116. static std::string
  11117. send_pipelined_requests(const std::vector<std::string> &parts) {
  11118. Server svr;
  11119. std::string res;
  11120. serve_pipelining_routes(svr, [&](int port) {
  11121. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11122. });
  11123. return res;
  11124. }
  11125. static void expect_in_order(const std::string &res,
  11126. const std::vector<std::string> &bodies) {
  11127. size_t pos = 0;
  11128. for (const auto &body : bodies) {
  11129. pos = res.find(body, pos);
  11130. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11131. pos += body.size();
  11132. }
  11133. }
  11134. TEST(KeepAliveTest, PipelinedRequests) {
  11135. auto res = send_pipelined_requests(
  11136. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11137. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11138. "Content-Length: 4\r\n\r\nbody"
  11139. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11140. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11141. }
  11142. // The second request starts in the server's buffer and ends on the socket.
  11143. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11144. auto res =
  11145. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11146. "GET /hi/2 HTTP/1.1\r\nHo",
  11147. "st: localhost\r\nConnection: close\r\n\r\n"});
  11148. expect_in_order(res, {"hi 1", "hi 2"});
  11149. }
  11150. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11151. // CRLF after a body does not turn into a 400 for the next request.
  11152. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11153. auto res = send_pipelined_requests(
  11154. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11155. "Content-Length: 4\r\n\r\nbody\r\n"
  11156. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11157. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11158. expect_in_order(res, {"echo body", "hi 2"});
  11159. }
  11160. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11161. // must not be served as the next request.
  11162. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11163. auto res = send_pipelined_requests(
  11164. {"INVALID REQUEST LINE\r\n\r\n"
  11165. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11166. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11167. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11168. }
  11169. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11170. // Over TLS, the next request is held by the TLS library as already decrypted
  11171. // data rather than on the socket.
  11172. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11174. std::string res;
  11175. serve_pipelining_routes(svr, [&](int port) {
  11176. // One part, so all three requests arrive in one TLS record
  11177. EXPECT_TRUE(send_ssl_request_in_parts(
  11178. 2,
  11179. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11180. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11181. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11182. &res, port));
  11183. });
  11184. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11185. }
  11186. #endif
  11187. TEST(KeepAliveTest, Issue1041) {
  11188. Server svr;
  11189. svr.set_keep_alive_timeout(3);
  11190. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11191. res.set_content("Hello World!", "text/plain");
  11192. });
  11193. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11194. auto se = detail::scope_exit([&] {
  11195. svr.stop();
  11196. listen_thread.join();
  11197. ASSERT_FALSE(svr.is_running());
  11198. });
  11199. svr.wait_until_ready();
  11200. Client cli(HOST, PORT);
  11201. cli.set_keep_alive(true);
  11202. auto result = cli.Get("/hi");
  11203. ASSERT_TRUE(result);
  11204. EXPECT_EQ(StatusCode::OK_200, result->status);
  11205. std::this_thread::sleep_for(std::chrono::seconds(5));
  11206. result = cli.Get("/hi");
  11207. ASSERT_TRUE(result);
  11208. EXPECT_EQ(StatusCode::OK_200, result->status);
  11209. }
  11210. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11211. Server svr;
  11212. svr.set_keep_alive_max_count(0);
  11213. std::set<int> remote_ports;
  11214. svr.Get("/hi", [&](const Request &req, Response &res) {
  11215. remote_ports.insert(req.remote_port);
  11216. res.set_content("hi", "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. for (int i = 0; i < 3; i++) {
  11228. auto res = cli.Get("/hi");
  11229. ASSERT_TRUE(res);
  11230. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11231. }
  11232. // All three over one connection
  11233. EXPECT_EQ(1u, remote_ports.size());
  11234. }
  11235. TEST(KeepAliveTest, Issue1959) {
  11236. Server svr;
  11237. svr.set_keep_alive_timeout(5);
  11238. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11239. res.set_content("a", "text/plain");
  11240. });
  11241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. if (!svr.is_running()) return;
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. Client cli("localhost", PORT);
  11250. cli.set_keep_alive(true);
  11251. using namespace std::chrono;
  11252. auto start = steady_clock::now();
  11253. cli.Get("/a");
  11254. svr.stop();
  11255. listen_thread.join();
  11256. auto end = steady_clock::now();
  11257. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11258. EXPECT_LT(elapsed, 5000);
  11259. }
  11260. #ifdef CPPHTTPLIB_SSL_ENABLED
  11261. TEST(KeepAliveTest, SSLClientReconnection) {
  11262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11263. ASSERT_TRUE(svr.is_valid());
  11264. svr.set_keep_alive_timeout(1);
  11265. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11266. res.set_content("Hello World!", "text/plain");
  11267. });
  11268. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11269. auto se = detail::scope_exit([&] {
  11270. svr.stop();
  11271. listen_thread.join();
  11272. ASSERT_FALSE(svr.is_running());
  11273. });
  11274. svr.wait_until_ready();
  11275. SSLClient cli(HOST, PORT);
  11276. cli.enable_server_certificate_verification(false);
  11277. cli.set_keep_alive(true);
  11278. auto result = cli.Get("/hi");
  11279. ASSERT_TRUE(result);
  11280. EXPECT_EQ(StatusCode::OK_200, result->status);
  11281. result = cli.Get("/hi");
  11282. ASSERT_TRUE(result);
  11283. EXPECT_EQ(StatusCode::OK_200, result->status);
  11284. std::this_thread::sleep_for(std::chrono::seconds(2));
  11285. // Recoonect
  11286. result = cli.Get("/hi");
  11287. ASSERT_TRUE(result);
  11288. EXPECT_EQ(StatusCode::OK_200, result->status);
  11289. result = cli.Get("/hi");
  11290. ASSERT_TRUE(result);
  11291. EXPECT_EQ(StatusCode::OK_200, result->status);
  11292. }
  11293. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11295. ASSERT_TRUE(svr.is_valid());
  11296. svr.set_keep_alive_timeout(1);
  11297. std::string content = "reconnect";
  11298. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11299. res.set_content("Hello World!", "text/plain");
  11300. });
  11301. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11302. auto se = detail::scope_exit([&] {
  11303. svr.stop();
  11304. listen_thread.join();
  11305. ASSERT_FALSE(svr.is_running());
  11306. });
  11307. svr.wait_until_ready();
  11308. SSLClient cli(HOST, PORT);
  11309. cli.enable_server_certificate_verification(false);
  11310. cli.set_keep_alive(true);
  11311. auto result = cli.Post(
  11312. "/hi", content.size(),
  11313. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11314. sink.write(content.c_str(), content.size());
  11315. return true;
  11316. },
  11317. "text/plain");
  11318. ASSERT_TRUE(result);
  11319. EXPECT_EQ(200, result->status);
  11320. std::this_thread::sleep_for(std::chrono::seconds(2));
  11321. // Recoonect
  11322. result = cli.Post(
  11323. "/hi", content.size(),
  11324. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11325. sink.write(content.c_str(), content.size());
  11326. return true;
  11327. },
  11328. "text/plain");
  11329. ASSERT_TRUE(result);
  11330. EXPECT_EQ(200, result->status);
  11331. result = cli.Post(
  11332. "/hi", content.size(),
  11333. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11334. sink.write(content.c_str(), content.size());
  11335. return true;
  11336. },
  11337. "text/plain");
  11338. ASSERT_TRUE(result);
  11339. EXPECT_EQ(200, result->status);
  11340. }
  11341. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11342. using namespace httplib::tls;
  11343. {
  11344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11345. ASSERT_TRUE(svr.is_valid());
  11346. svr.Get("/sni", [&](const Request &req, Response &res) {
  11347. std::string expected = req.sni();
  11348. EXPECT_EQ(expected, req.get_param_value("expected"));
  11349. res.set_content("ok", "text/plain");
  11350. });
  11351. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. {
  11359. SSLClient cli("localhost", PORT);
  11360. cli.enable_server_certificate_verification(false);
  11361. auto res = cli.Get("/sni?expected=localhost");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. }
  11364. {
  11365. SSLClient cli("::1", PORT);
  11366. cli.enable_server_certificate_verification(false);
  11367. auto res = cli.Get("/sni?expected=");
  11368. // NOTE: This may fail if the server is listening on IPv4 only
  11369. // (e.g., when localhost resolves to 127.0.0.1 only)
  11370. if (res) {
  11371. EXPECT_EQ(StatusCode::OK_200, res->status);
  11372. } else {
  11373. EXPECT_EQ(Error::Connection, res.error());
  11374. }
  11375. }
  11376. }
  11377. }
  11378. // The SNI of a failed handshake does not reach the next connection that the
  11379. // same worker thread serves
  11380. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11381. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11382. ASSERT_TRUE(svr.is_valid());
  11383. svr.new_task_queue = [] { return new ThreadPool(1); };
  11384. svr.Get("/sni", [](const Request &req, Response &res) {
  11385. res.set_content(req.sni(), "text/plain");
  11386. });
  11387. auto port = svr.bind_to_any_port("127.0.0.1");
  11388. ASSERT_LT(0, port);
  11389. thread t = thread([&] { svr.listen_after_bind(); });
  11390. auto se = detail::scope_exit([&] {
  11391. svr.stop();
  11392. t.join();
  11393. ASSERT_FALSE(svr.is_running());
  11394. });
  11395. svr.wait_until_ready();
  11396. {
  11397. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11398. SSLClient cli("localhost", port);
  11399. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11400. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11401. auto res = cli.Get("/sni");
  11402. ASSERT_FALSE(res);
  11403. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11404. }
  11405. // An IP host sends no SNI (RFC 6066)
  11406. SSLClient cli("127.0.0.1", port);
  11407. cli.enable_server_certificate_verification(false);
  11408. auto res = cli.Get("/sni");
  11409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11410. EXPECT_EQ("", res->body);
  11411. }
  11412. #endif
  11413. TEST(ClientProblemDetectionTest, ContentProvider) {
  11414. Server svr;
  11415. size_t content_length = 1024 * 1024;
  11416. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11417. res.set_content_provider(
  11418. content_length, "text/plain",
  11419. [&](size_t offset, size_t length, DataSink &sink) {
  11420. auto out_len = std::min(length, static_cast<size_t>(1024));
  11421. std::string out(out_len, '@');
  11422. sink.write(out.data(), out_len);
  11423. return offset < 4096;
  11424. },
  11425. [](bool success) { ASSERT_FALSE(success); });
  11426. });
  11427. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11428. res.set_content_provider(
  11429. 0, "text/plain",
  11430. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11431. EXPECT_TRUE(false);
  11432. return true;
  11433. },
  11434. [](bool success) { ASSERT_FALSE(success); });
  11435. });
  11436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11437. auto se = detail::scope_exit([&] {
  11438. svr.stop();
  11439. listen_thread.join();
  11440. ASSERT_FALSE(svr.is_running());
  11441. });
  11442. svr.wait_until_ready();
  11443. Client cli("localhost", PORT);
  11444. {
  11445. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11446. size_t /*data_length*/) { return false; });
  11447. ASSERT_FALSE(res);
  11448. }
  11449. {
  11450. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11451. size_t /*data_length*/) { return false; });
  11452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11453. }
  11454. }
  11455. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11456. // A provider that reports success without writing anything and without
  11457. // calling done() used to be handed the same offset and length again on every
  11458. // pass, so it spun for as long as the peer stayed connected.
  11459. Server svr;
  11460. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11461. res.set_content("ok", "text/plain");
  11462. });
  11463. auto port = svr.bind_to_any_port(HOST);
  11464. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. listen_thread.join();
  11468. ASSERT_FALSE(svr.is_running());
  11469. });
  11470. svr.wait_until_ready();
  11471. std::atomic<int> call_count{0};
  11472. Client cli(HOST, port);
  11473. auto res = cli.Post(
  11474. "/", 1024,
  11475. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11476. // Give up after enough passes to show the spin, so that losing the
  11477. // check below fails this test instead of hanging it.
  11478. return ++call_count < 100;
  11479. },
  11480. "text/plain");
  11481. ASSERT_FALSE(res);
  11482. EXPECT_EQ(Error::Write, res.error());
  11483. EXPECT_EQ(1, call_count.load());
  11484. }
  11485. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11486. // A writer only has to assign `write`. The other three used to be left as
  11487. // empty std::functions, so a provider calling one threw
  11488. // std::bad_function_call out of the thread running it and took the whole
  11489. // process down.
  11490. DataSink sink;
  11491. std::string written;
  11492. sink.write = [&](const char *data, size_t data_len) {
  11493. written.append(data, data_len);
  11494. return true;
  11495. };
  11496. EXPECT_TRUE(sink.is_writable());
  11497. sink.done();
  11498. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11499. EXPECT_TRUE(written.empty());
  11500. }
  11501. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11502. // A sink that cannot carry trailers still has to finish.
  11503. DataSink sink;
  11504. auto done_count = 0;
  11505. sink.done = [&]() { done_count++; };
  11506. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11507. EXPECT_EQ(1, done_count);
  11508. }
  11509. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11510. Server svr;
  11511. const std::string body(4096, 'x');
  11512. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11513. res.set_content_provider(body.size(), "text/plain",
  11514. [&](size_t offset, size_t length, DataSink &sink) {
  11515. sink.write(body.data() + offset, length);
  11516. sink.done();
  11517. return true;
  11518. });
  11519. });
  11520. auto port = svr.bind_to_any_port(HOST);
  11521. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11522. auto se = detail::scope_exit([&] {
  11523. svr.stop();
  11524. listen_thread.join();
  11525. ASSERT_FALSE(svr.is_running());
  11526. });
  11527. svr.wait_until_ready();
  11528. Client cli(HOST, port);
  11529. auto res = cli.Get("/");
  11530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11531. EXPECT_EQ(StatusCode::OK_200, res->status);
  11532. EXPECT_EQ(body, res->body);
  11533. }
  11534. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11535. Server svr;
  11536. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11537. res.set_content_provider(
  11538. 1024, "text/plain",
  11539. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11540. sink.write("hello", 5);
  11541. sink.done(); // short of the 1024 bytes the response promised
  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. cli.set_read_timeout(5, 0);
  11555. // The response is short of its Content-Length, so the client cannot read a
  11556. // complete body. What matters is that this returns at all: a no-op done()
  11557. // would leave the writer looping over a provider that never makes progress.
  11558. auto res = cli.Get("/");
  11559. EXPECT_FALSE(res);
  11560. }
  11561. // Read as the next response by a peer that sees it after a framed body.
  11562. static const std::string smuggled_response =
  11563. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11564. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11565. Server svr;
  11566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11567. res.set_content_provider(
  11568. 5, "text/plain",
  11569. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11570. auto data = "AAAAA" + smuggled_response;
  11571. sink.write(data.data(), data.size());
  11572. return true;
  11573. });
  11574. });
  11575. thread t = thread([&] { svr.listen(HOST, PORT); });
  11576. auto se = detail::scope_exit([&] {
  11577. svr.stop();
  11578. t.join();
  11579. ASSERT_FALSE(svr.is_running());
  11580. });
  11581. svr.wait_until_ready();
  11582. std::string resp;
  11583. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11584. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11585. resp.clear();
  11586. ASSERT_TRUE(send_request(
  11587. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11588. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11589. }
  11590. TEST(NoContentTest, BodyIsNotSent) {
  11591. Server svr;
  11592. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11593. res.status = StatusCode::NoContent_204;
  11594. res.set_content(smuggled_response, "text/plain");
  11595. });
  11596. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11597. res.status = StatusCode::NotModified_304;
  11598. res.set_chunked_content_provider(
  11599. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11600. sink.write(smuggled_response.data(), smuggled_response.size());
  11601. sink.done();
  11602. return true;
  11603. });
  11604. });
  11605. thread t = thread([&] { svr.listen(HOST, PORT); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. t.join();
  11609. ASSERT_FALSE(svr.is_running());
  11610. });
  11611. svr.wait_until_ready();
  11612. for (auto path : {"/204", "/304"}) {
  11613. std::string resp;
  11614. ASSERT_TRUE(send_request(
  11615. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11616. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11617. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11618. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11619. }
  11620. }
  11621. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11622. Server svr;
  11623. std::atomic<bool> smuggled(false);
  11624. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11625. res.set_content("ok", "text/plain");
  11626. });
  11627. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11628. smuggled = true;
  11629. });
  11630. auto port = svr.bind_to_any_port(HOST);
  11631. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11632. auto se = detail::scope_exit([&] {
  11633. svr.stop();
  11634. listen_thread.join();
  11635. ASSERT_FALSE(svr.is_running());
  11636. });
  11637. svr.wait_until_ready();
  11638. // What follows the body would be read as the next request.
  11639. Client cli(HOST, port);
  11640. auto res = cli.Post(
  11641. "/", 5,
  11642. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11643. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11644. sink.write(data.data(), data.size());
  11645. return true;
  11646. },
  11647. "text/plain");
  11648. ASSERT_FALSE(res);
  11649. EXPECT_EQ(Error::Write, res.error());
  11650. EXPECT_FALSE(smuggled);
  11651. }
  11652. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11653. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11654. // The compressed path builds the whole body before connecting, so this
  11655. // fails client-side and never reaches a server.
  11656. Client cli(HOST, PORT);
  11657. cli.set_compress(true);
  11658. auto res = cli.Post(
  11659. "/", 1024,
  11660. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11661. sink.write("hello", 5);
  11662. sink.done(); // short of the 1024 bytes the request announced
  11663. return true;
  11664. },
  11665. "text/plain");
  11666. ASSERT_FALSE(res);
  11667. EXPECT_EQ(Error::Write, res.error());
  11668. }
  11669. #endif
  11670. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11671. Server svr;
  11672. svr.set_error_handler([](Request const &, Response &res) -> void {
  11673. res.set_chunked_content_provider(
  11674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11675. sink.os << "hello";
  11676. sink.os << "world";
  11677. sink.done();
  11678. return true;
  11679. });
  11680. });
  11681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. listen_thread.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. Client cli("localhost", PORT);
  11689. auto res = cli.Get("/");
  11690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11692. EXPECT_EQ("helloworld", res->body);
  11693. }
  11694. // A body set after a content provider must replace it, not be sent through it.
  11695. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11696. Server svr;
  11697. svr.set_mount_point("/", "./www");
  11698. svr.set_file_request_handler([](const Request &req, Response &res) {
  11699. if (req.path == "/dir/test.html") {
  11700. res.status = StatusCode::Forbidden_403;
  11701. res.set_content(std::string(5000, 'D'), "text/plain");
  11702. } else if (req.path == "/file") {
  11703. res.status = StatusCode::Forbidden_403;
  11704. res.body = "Denied";
  11705. }
  11706. });
  11707. auto port = svr.bind_to_any_port(HOST);
  11708. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. Client cli(HOST, port);
  11716. {
  11717. auto res = cli.Get("/dir/test.html");
  11718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11719. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11720. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11721. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11722. }
  11723. {
  11724. auto res = cli.Get("/file");
  11725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11726. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11727. EXPECT_EQ("Denied", res->body);
  11728. }
  11729. {
  11730. auto res = cli.Get("/dir/index.html");
  11731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11732. EXPECT_EQ(StatusCode::OK_200, res->status);
  11733. EXPECT_EQ(0U, res->body.find("<html>"));
  11734. }
  11735. }
  11736. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11737. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11738. Server svr;
  11739. std::vector<bool> released;
  11740. std::mutex released_mutex;
  11741. auto releaser = [&](bool success) {
  11742. std::lock_guard<std::mutex> guard(released_mutex);
  11743. released.push_back(success);
  11744. };
  11745. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11746. return sink.write(&"hello"[offset], length);
  11747. };
  11748. svr.Get("/sized", [&](const Request &, Response &res) {
  11749. res.status = StatusCode::NotFound_404;
  11750. res.set_content_provider(5, "text/plain", provider, releaser);
  11751. });
  11752. svr.Get("/chunked", [&](const Request &, Response &res) {
  11753. res.status = StatusCode::ServiceUnavailable_503;
  11754. res.set_chunked_content_provider(
  11755. "text/plain",
  11756. [](size_t, DataSink &sink) {
  11757. sink.os << "chunk";
  11758. sink.done();
  11759. return true;
  11760. },
  11761. releaser);
  11762. });
  11763. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11764. res.set_content_provider(5, "text/plain", provider, releaser);
  11765. throw std::runtime_error("after the provider");
  11766. });
  11767. svr.set_error_handler([](const Request &req, Response &res) {
  11768. // Leave the exception handler's content to it.
  11769. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11770. res.set_content(std::string(1000, 'E'), "text/html");
  11771. return Server::HandlerResponse::Handled;
  11772. });
  11773. svr.set_exception_handler(
  11774. [](const Request &, Response &res, std::exception_ptr) {
  11775. res.status = StatusCode::InternalServerError_500;
  11776. res.set_content(std::string(1000, 'X'), "text/html");
  11777. });
  11778. auto port = svr.bind_to_any_port(HOST);
  11779. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. t.join();
  11783. ASSERT_FALSE(svr.is_running());
  11784. });
  11785. svr.wait_until_ready();
  11786. Client cli(HOST, port);
  11787. {
  11788. auto res = cli.Get("/sized");
  11789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11790. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11791. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11792. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11793. }
  11794. {
  11795. auto res = cli.Get("/chunked");
  11796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11797. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11798. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11799. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11800. }
  11801. {
  11802. auto res = cli.Get("/throw");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11805. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11806. }
  11807. std::lock_guard<std::mutex> guard(released_mutex);
  11808. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11809. }
  11810. #endif
  11811. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11812. Server svr;
  11813. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11814. return sink.write(&"abc"[offset], length);
  11815. };
  11816. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11817. res.set_file_content("./www/dir/test.html");
  11818. res.set_content("body", "text/plain");
  11819. });
  11820. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11821. res.set_content(std::string(100, 'B'), "text/plain");
  11822. res.set_file_content("./www/dir/test.html");
  11823. });
  11824. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11825. res.set_content(std::string(100, 'B'), "text/plain");
  11826. res.set_content_provider(3, "text/x-provider", abc);
  11827. });
  11828. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11829. res.set_content_provider(3, "text/x-provider", abc);
  11830. res.set_content(std::string(100, 'B'), "text/plain");
  11831. });
  11832. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11833. res.set_content_provider(3, "text/x-provider", abc);
  11834. res.set_file_content("./www/dir/test.html", "text/x-file");
  11835. });
  11836. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11837. res.set_file_content("./www/dir/test.html");
  11838. res.set_header("Content-Type", "text/x-handler");
  11839. });
  11840. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11841. res.set_content_provider(3, "text/plain", abc);
  11842. res.body = "direct";
  11843. });
  11844. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11845. res.set_file_content("./www/dir/test.html");
  11846. res.body = "direct";
  11847. });
  11848. auto port = svr.bind_to_any_port(HOST);
  11849. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11850. auto se = detail::scope_exit([&] {
  11851. svr.stop();
  11852. t.join();
  11853. ASSERT_FALSE(svr.is_running());
  11854. });
  11855. svr.wait_until_ready();
  11856. Client cli(HOST, port);
  11857. auto expect_body = [&](const char *path, const std::string &body,
  11858. const std::string &type) {
  11859. // Uncompressed, so Content-Length can be compared with the body.
  11860. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11861. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11862. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11863. EXPECT_EQ(body, res->body) << path;
  11864. EXPECT_EQ(std::to_string(body.size()),
  11865. res->get_header_value("Content-Length"))
  11866. << path;
  11867. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11868. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11869. };
  11870. expect_body("/file-then-body", "body", "text/plain");
  11871. expect_body("/body-then-file", "test.html", "text/html");
  11872. expect_body("/body-then-provider", "abc", "text/x-provider");
  11873. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11874. expect_body("/provider-then-file", "test.html", "text/x-file");
  11875. expect_body("/file-then-header", "test.html", "text/x-handler");
  11876. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11877. expect_body("/file-then-direct-body", "direct", "text/plain");
  11878. // Ranges are checked against the body, not the dropped provider.
  11879. {
  11880. auto res = cli.Get("/provider-then-direct-body",
  11881. Headers{{make_range_header({{1, 2}})}});
  11882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11883. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11884. EXPECT_EQ("ir", res->body);
  11885. }
  11886. {
  11887. auto res = cli.Get("/file-then-direct-body",
  11888. Headers{{make_range_header({{7, 8}})}});
  11889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11890. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11891. }
  11892. }
  11893. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11894. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11895. const char *path = "./truncated_while_served.txt";
  11896. const size_t size = 32 * 1024 * 1024;
  11897. {
  11898. std::ofstream f(path, std::ios::binary);
  11899. f << std::string(size, 'x');
  11900. }
  11901. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11902. // Over TLS, where the bytes are encrypted in this process rather than
  11903. // copied by send().
  11904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11905. svr.Get("/file", [&](const Request &, Response &res) {
  11906. res.set_file_content(path, "text/plain");
  11907. });
  11908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11909. auto se = detail::scope_exit([&] {
  11910. svr.stop();
  11911. thread.join();
  11912. ASSERT_FALSE(svr.is_running());
  11913. });
  11914. svr.wait_until_ready();
  11915. // The file shrinks once the first bytes are in, as a rewrite in place
  11916. // would, and reading the mapping past its new end used to raise SIGBUS.
  11917. SSLClient cli(HOST, PORT);
  11918. cli.enable_server_certificate_verification(false);
  11919. size_t received = 0;
  11920. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11921. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11922. received += len;
  11923. return true;
  11924. });
  11925. EXPECT_FALSE(res);
  11926. EXPECT_LT(received, size);
  11927. }
  11928. #endif
  11929. // Forward declaration (see the base64_encode note).
  11930. namespace httplib {
  11931. namespace detail {
  11932. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11933. const std::string &content_type,
  11934. EncodingType encoding);
  11935. } // namespace detail
  11936. } // namespace httplib
  11937. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11938. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11939. ASSERT_TRUE(mm->is_open());
  11940. Response res;
  11941. detail::set_file_content_provider(res, mm, "text/html",
  11942. detail::EncodingType::None);
  11943. std::string out;
  11944. DataSink sink;
  11945. sink.write = [&](const char *d, size_t l) {
  11946. out.append(d, l);
  11947. return true;
  11948. };
  11949. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11950. EXPECT_EQ("test.html", out);
  11951. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11952. EXPECT_EQ("test.html", out);
  11953. }
  11954. TEST(LongPollingTest, ClientCloseDetection) {
  11955. Server svr;
  11956. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11957. res.set_chunked_content_provider(
  11958. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11959. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11960. sink.os << "hello";
  11961. auto count = 10;
  11962. while (count > 0 && sink.is_writable()) {
  11963. this_thread::sleep_for(chrono::milliseconds(10));
  11964. count--;
  11965. }
  11966. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11967. return true;
  11968. });
  11969. });
  11970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11971. auto se = detail::scope_exit([&] {
  11972. svr.stop();
  11973. listen_thread.join();
  11974. ASSERT_FALSE(svr.is_running());
  11975. });
  11976. svr.wait_until_ready();
  11977. Client cli("localhost", PORT);
  11978. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11979. EXPECT_EQ("hello", string(data, data_length));
  11980. return false; // close the socket immediately.
  11981. });
  11982. ASSERT_FALSE(res);
  11983. }
  11984. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11985. Server svr;
  11986. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11987. res.set_chunked_content_provider(
  11988. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11989. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11990. sink.os << "hello";
  11991. EXPECT_TRUE(sink.os.good());
  11992. // Wait for the client to close the connection
  11993. auto count = 10;
  11994. while (count > 0 && sink.is_writable()) {
  11995. this_thread::sleep_for(chrono::milliseconds(10));
  11996. count--;
  11997. }
  11998. // After client disconnect, write repeatedly until the socket
  11999. // write actually fails (small writes may be absorbed by the
  12000. // kernel buffer)
  12001. std::string chunk(1024, 'x');
  12002. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12003. sink.os << chunk;
  12004. }
  12005. EXPECT_TRUE(sink.os.fail());
  12006. return true;
  12007. });
  12008. });
  12009. auto port = svr.bind_to_any_port("localhost");
  12010. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. listen_thread.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. });
  12016. svr.wait_until_ready();
  12017. Client cli("localhost", port);
  12018. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12019. EXPECT_EQ("hello", string(data, data_length));
  12020. return false; // close the socket immediately.
  12021. });
  12022. ASSERT_FALSE(res);
  12023. }
  12024. TEST(GetWithParametersTest, GetWithParameters) {
  12025. Server svr;
  12026. svr.Get("/", [&](const Request &req, Response &) {
  12027. EXPECT_EQ("world", req.get_param_value("hello"));
  12028. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12029. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12030. });
  12031. svr.Get("/params", [&](const Request &req, Response &) {
  12032. EXPECT_EQ("world", req.get_param_value("hello"));
  12033. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12034. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12035. });
  12036. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12037. EXPECT_EQ("resource-id", req.matches[1]);
  12038. EXPECT_EQ("foo", req.get_param_value("param1"));
  12039. EXPECT_EQ("bar", req.get_param_value("param2"));
  12040. });
  12041. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12042. EXPECT_EQ("user-id", req.path_params.at("id"));
  12043. EXPECT_EQ("foo", req.get_param_value("param1"));
  12044. EXPECT_EQ("bar", req.get_param_value("param2"));
  12045. });
  12046. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12047. auto se = detail::scope_exit([&] {
  12048. svr.stop();
  12049. listen_thread.join();
  12050. ASSERT_FALSE(svr.is_running());
  12051. });
  12052. svr.wait_until_ready();
  12053. {
  12054. Client cli(HOST, PORT);
  12055. Params params;
  12056. params.emplace("hello", "world");
  12057. params.emplace("hello2", "world2");
  12058. params.emplace("hello3", "world3");
  12059. auto res = cli.Get("/", params, Headers{});
  12060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12061. EXPECT_EQ(StatusCode::OK_200, res->status);
  12062. }
  12063. {
  12064. Client cli(HOST, PORT);
  12065. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12067. EXPECT_EQ(StatusCode::OK_200, res->status);
  12068. }
  12069. {
  12070. Client cli(HOST, PORT);
  12071. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. {
  12076. Client cli(HOST, PORT);
  12077. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. EXPECT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. }
  12082. TEST(GetWithParametersTest, GetWithParameters2) {
  12083. Server svr;
  12084. svr.Get("/", [&](const Request &req, Response &res) {
  12085. auto text = req.get_param_value("hello");
  12086. res.set_content(text, "text/plain");
  12087. });
  12088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12089. auto se = detail::scope_exit([&] {
  12090. svr.stop();
  12091. listen_thread.join();
  12092. ASSERT_FALSE(svr.is_running());
  12093. });
  12094. svr.wait_until_ready();
  12095. Client cli("localhost", PORT);
  12096. Params params;
  12097. params.emplace("hello", "world");
  12098. std::string body;
  12099. auto res = cli.Get("/", params, Headers{},
  12100. [&](const char *data, size_t data_length) {
  12101. body.append(data, data_length);
  12102. return true;
  12103. });
  12104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12105. EXPECT_EQ(StatusCode::OK_200, res->status);
  12106. EXPECT_EQ("world", body);
  12107. }
  12108. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12109. Server svr;
  12110. svr.Get("/search", [&](const Request &req, Response &res) {
  12111. auto q = req.get_param_value("q");
  12112. res.set_content(q, "text/plain");
  12113. });
  12114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12115. auto se = detail::scope_exit([&] {
  12116. svr.stop();
  12117. listen_thread.join();
  12118. ASSERT_FALSE(svr.is_running());
  12119. });
  12120. svr.wait_until_ready();
  12121. Client cli("localhost", PORT);
  12122. // Verify that Get(path, params) works without requiring Headers argument
  12123. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12125. EXPECT_EQ(StatusCode::OK_200, res->status);
  12126. EXPECT_EQ("cpp-httplib", res->body);
  12127. }
  12128. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12129. auto host = "httpbingo.org";
  12130. auto path = std::string{"/range/32"};
  12131. #ifdef CPPHTTPLIB_SSL_ENABLED
  12132. SSLClient cli(host);
  12133. #else
  12134. Client cli(host);
  12135. #endif
  12136. cli.set_default_headers({make_range_header({{1, 10}})});
  12137. cli.set_connection_timeout(5);
  12138. {
  12139. auto res = cli.Get(path);
  12140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12141. EXPECT_EQ("bcdefghijk", res->body);
  12142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12143. }
  12144. {
  12145. auto res = cli.Get(path);
  12146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12147. EXPECT_EQ("bcdefghijk", res->body);
  12148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12149. }
  12150. }
  12151. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12152. Server svr;
  12153. svr.set_default_headers({{"Hello", "World"}});
  12154. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12155. res.set_content("ok", "text/plain");
  12156. });
  12157. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12158. auto se = detail::scope_exit([&] {
  12159. svr.stop();
  12160. listen_thread.join();
  12161. ASSERT_FALSE(svr.is_running());
  12162. });
  12163. svr.wait_until_ready();
  12164. Client cli("localhost", PORT);
  12165. auto res = cli.Get("/");
  12166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12167. EXPECT_EQ(StatusCode::OK_200, res->status);
  12168. EXPECT_EQ("ok", res->body);
  12169. EXPECT_EQ("World", res->get_header_value("Hello"));
  12170. }
  12171. #ifdef CPPHTTPLIB_SSL_ENABLED
  12172. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12174. ASSERT_TRUE(svr.is_valid());
  12175. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12176. std::this_thread::sleep_for(std::chrono::seconds(2));
  12177. res.set_content("a", "text/plain");
  12178. });
  12179. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12180. res.set_content("b", "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. SSLClient cli("localhost", PORT);
  12190. cli.enable_server_certificate_verification(false);
  12191. cli.set_keep_alive(true);
  12192. cli.set_read_timeout(std::chrono::seconds(1));
  12193. auto resa = cli.Get("/a");
  12194. ASSERT_TRUE(!resa);
  12195. EXPECT_EQ(Error::Read, resa.error());
  12196. auto resb = cli.Get("/b");
  12197. ASSERT_TRUE(resb);
  12198. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12199. EXPECT_EQ("b", resb->body);
  12200. }
  12201. // Closing an idle keep-alive connection sends close_notify and returns. The
  12202. // server must not wait for the client's close_notify: an idle client never
  12203. // sends one, so the worker would be held until the read timeout expires, and
  12204. // stop() would wait for it.
  12205. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12207. ASSERT_TRUE(svr.is_valid());
  12208. svr.set_keep_alive_timeout(1);
  12209. svr.set_read_timeout(10, 0);
  12210. svr.Get("/", [](const Request &, Response &res) {
  12211. res.set_content("ok", "text/plain");
  12212. });
  12213. auto port = svr.bind_to_any_port(HOST);
  12214. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12215. auto se = detail::scope_exit([&] {
  12216. if (listen_thread.joinable()) {
  12217. svr.stop();
  12218. listen_thread.join();
  12219. }
  12220. });
  12221. svr.wait_until_ready();
  12222. SSLClient cli(HOST, port);
  12223. cli.enable_server_certificate_verification(false);
  12224. cli.set_keep_alive(true);
  12225. auto res = cli.Get("/");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::OK_200, res->status);
  12228. // Stay idle past the keep-alive timeout so the server closes the connection.
  12229. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12230. auto start = std::chrono::steady_clock::now();
  12231. svr.stop();
  12232. listen_thread.join();
  12233. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12234. std::chrono::steady_clock::now() - start)
  12235. .count();
  12236. EXPECT_LT(elapsed, 3000);
  12237. }
  12238. #endif
  12239. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12240. protected:
  12241. ServerTestWithAI_PASSIVE()
  12242. : cli_(HOST, PORT)
  12243. #ifdef CPPHTTPLIB_SSL_ENABLED
  12244. ,
  12245. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12246. #endif
  12247. {
  12248. #ifdef CPPHTTPLIB_SSL_ENABLED
  12249. cli_.enable_server_certificate_verification(false);
  12250. #endif
  12251. }
  12252. virtual void SetUp() {
  12253. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12254. res.set_content("Hello World!", "text/plain");
  12255. });
  12256. t_ = thread(
  12257. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12258. svr_.wait_until_ready();
  12259. }
  12260. virtual void TearDown() {
  12261. svr_.stop();
  12262. t_.join();
  12263. }
  12264. #ifdef CPPHTTPLIB_SSL_ENABLED
  12265. SSLClient cli_;
  12266. SSLServer svr_;
  12267. #else
  12268. Client cli_;
  12269. Server svr_;
  12270. #endif
  12271. thread t_;
  12272. };
  12273. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12274. auto res = cli_.Get("/hi");
  12275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12276. EXPECT_EQ(StatusCode::OK_200, res->status);
  12277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12278. EXPECT_EQ("Hello World!", res->body);
  12279. }
  12280. class ServerUpDownTest : public ::testing::Test {
  12281. protected:
  12282. ServerUpDownTest() : cli_(HOST, PORT) {}
  12283. virtual void SetUp() {
  12284. t_ = thread([&]() {
  12285. svr_.bind_to_any_port(HOST);
  12286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12287. ASSERT_TRUE(svr_.listen_after_bind());
  12288. });
  12289. svr_.wait_until_ready();
  12290. }
  12291. virtual void TearDown() {
  12292. svr_.stop();
  12293. t_.join();
  12294. }
  12295. Client cli_;
  12296. Server svr_;
  12297. thread t_;
  12298. };
  12299. TEST_F(ServerUpDownTest, QuickStartStop) {
  12300. // Should not crash, especially when run with
  12301. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12302. }
  12303. class PayloadMaxLengthTest : public ::testing::Test {
  12304. protected:
  12305. PayloadMaxLengthTest()
  12306. : cli_(HOST, PORT)
  12307. #ifdef CPPHTTPLIB_SSL_ENABLED
  12308. ,
  12309. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12310. #endif
  12311. {
  12312. #ifdef CPPHTTPLIB_SSL_ENABLED
  12313. cli_.enable_server_certificate_verification(false);
  12314. #endif
  12315. }
  12316. virtual void SetUp() {
  12317. svr_.set_payload_max_length(8);
  12318. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12319. res.set_content("test", "text/plain");
  12320. });
  12321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12322. svr_.wait_until_ready();
  12323. }
  12324. virtual void TearDown() {
  12325. svr_.stop();
  12326. t_.join();
  12327. }
  12328. #ifdef CPPHTTPLIB_SSL_ENABLED
  12329. SSLClient cli_;
  12330. SSLServer svr_;
  12331. #else
  12332. Client cli_;
  12333. Server svr_;
  12334. #endif
  12335. thread t_;
  12336. };
  12337. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12338. auto res = cli_.Post("/test", "123456789", "text/plain");
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12341. res = cli_.Post("/test", "12345678", "text/plain");
  12342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12343. EXPECT_EQ(StatusCode::OK_200, res->status);
  12344. }
  12345. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12346. // Test chunked encoding with payload exceeding the 8-byte limit
  12347. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12348. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12351. }
  12352. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12353. // Test chunked encoding with payload within the 8-byte limit
  12354. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12355. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. EXPECT_EQ(StatusCode::OK_200, res->status);
  12358. }
  12359. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12360. // Test using send_request to send chunked data exceeding payload limit
  12361. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12362. "Host: " +
  12363. std::string(HOST) + ":" + std::to_string(PORT) +
  12364. "\r\n"
  12365. "Transfer-Encoding: chunked\r\n"
  12366. "Connection: close\r\n"
  12367. "\r\n"
  12368. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12369. "0123456789\r\n"
  12370. "0\r\n" // End chunk
  12371. "\r\n";
  12372. std::string response;
  12373. bool result = send_request(1, chunked_request, &response);
  12374. if (!result) {
  12375. // If send_request fails, it might be because the server closed the
  12376. // connection due to payload limit enforcement, which is acceptable
  12377. SUCCEED()
  12378. << "Server rejected oversized chunked request (connection closed)";
  12379. } else {
  12380. // If we got a response, check if it's an error response or connection was
  12381. // closed early Short response length indicates connection was closed due to
  12382. // payload limit
  12383. if (response.length() <= 10) {
  12384. SUCCEED() << "Server closed connection for oversized chunked request";
  12385. } else {
  12386. // Check for error status codes
  12387. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12388. response.find("Payload Too Large") != std::string::npos ||
  12389. response.find("400") != std::string::npos);
  12390. }
  12391. }
  12392. }
  12393. class LargePayloadMaxLengthTest : public ::testing::Test {
  12394. protected:
  12395. LargePayloadMaxLengthTest()
  12396. : cli_(HOST, PORT)
  12397. #ifdef CPPHTTPLIB_SSL_ENABLED
  12398. ,
  12399. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12400. #endif
  12401. {
  12402. #ifdef CPPHTTPLIB_SSL_ENABLED
  12403. cli_.enable_server_certificate_verification(false);
  12404. #endif
  12405. }
  12406. virtual void SetUp() {
  12407. // Set 10MB payload limit
  12408. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12409. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12410. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12411. res.set_content("Large payload test", "text/plain");
  12412. });
  12413. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12414. svr_.wait_until_ready();
  12415. }
  12416. virtual void TearDown() {
  12417. svr_.stop();
  12418. t_.join();
  12419. }
  12420. #ifdef CPPHTTPLIB_SSL_ENABLED
  12421. SSLClient cli_;
  12422. SSLServer svr_;
  12423. #else
  12424. Client cli_;
  12425. Server svr_;
  12426. #endif
  12427. thread t_;
  12428. };
  12429. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12430. // Test chunked encoding with payload within 10MB limit
  12431. std::string medium_payload(5 * 1024 * 1024,
  12432. 'A'); // 5MB payload, within 10MB limit
  12433. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12435. EXPECT_EQ(StatusCode::OK_200, res->status);
  12436. }
  12437. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12438. // Test chunked encoding with payload exceeding 10MB limit
  12439. std::string large_payload(12 * 1024 * 1024,
  12440. 'B'); // 12MB payload, exceeds 10MB limit
  12441. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12442. // Server may either return 413 or close the connection
  12443. if (res) {
  12444. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12445. } else {
  12446. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12447. }
  12448. }
  12449. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12450. Server svr;
  12451. svr.Get("/", [](const Request &, Response &res) {
  12452. // Claims the most the client accepts, far more than it sends, then drops
  12453. // the connection.
  12454. res.set_content_provider(std::string().max_size(), "text/plain",
  12455. [](size_t, size_t, DataSink &sink) {
  12456. sink.write("abc", 3);
  12457. return false;
  12458. });
  12459. });
  12460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12461. auto se = detail::scope_exit([&] {
  12462. svr.stop();
  12463. thread.join();
  12464. ASSERT_FALSE(svr.is_running());
  12465. });
  12466. svr.wait_until_ready();
  12467. Client cli(HOST, PORT);
  12468. cli.set_payload_max_length(0);
  12469. EXPECT_FALSE(cli.Get("/"));
  12470. }
  12471. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12472. // Stream API does, not as a plain read failure
  12473. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12474. Server svr;
  12475. svr.Get("/big", [](const Request &, Response &res) {
  12476. res.set_content(std::string(100000, 'b'), "text/plain");
  12477. });
  12478. auto port = svr.bind_to_any_port(HOST);
  12479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12480. auto se = detail::scope_exit([&] {
  12481. svr.stop();
  12482. thread.join();
  12483. });
  12484. svr.wait_until_ready();
  12485. Client cli(HOST, port);
  12486. cli.set_payload_max_length(1000);
  12487. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12488. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12489. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12490. [](const char *, size_t) { return true; });
  12491. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12492. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12493. // Small on the wire, over the limit once decompressed
  12494. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12495. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12496. #endif
  12497. }
  12498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12499. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12500. // path.
  12501. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12502. Server svr;
  12503. const size_t LIMIT = 64 * 1024; // 64KB
  12504. svr.set_payload_max_length(LIMIT);
  12505. size_t total = 0;
  12506. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12507. const ContentReader &content_reader) {
  12508. content_reader([&](const char * /*data*/, size_t len) {
  12509. total += len;
  12510. return true;
  12511. });
  12512. res.status = 200;
  12513. res.set_content("stream_ok", "text/plain");
  12514. });
  12515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12516. auto se = detail::scope_exit([&] {
  12517. svr.stop();
  12518. thread.join();
  12519. ASSERT_FALSE(svr.is_running());
  12520. });
  12521. svr.wait_until_ready();
  12522. // Prepare 256KB raw data and gzip-compress it
  12523. std::string raw(256 * 1024, 'A');
  12524. std::string gz;
  12525. {
  12526. z_stream zs{};
  12527. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12528. Z_DEFAULT_STRATEGY);
  12529. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12530. zs.avail_in = static_cast<uInt>(raw.size());
  12531. char outbuf[4096];
  12532. int ret;
  12533. do {
  12534. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12535. zs.avail_out = sizeof(outbuf);
  12536. ret = deflate(&zs, Z_FINISH);
  12537. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12538. } while (ret != Z_STREAM_END);
  12539. deflateEnd(&zs);
  12540. }
  12541. Client cli(HOST, PORT);
  12542. cli.set_connection_timeout(std::chrono::seconds(5));
  12543. Headers headers = {{"Content-Encoding", "gzip"}};
  12544. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12545. "application/octet-stream");
  12546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12547. // Server must reject oversized decompressed payloads with 413.
  12548. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12549. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12550. EXPECT_LE(total, LIMIT);
  12551. }
  12552. #endif
  12553. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12554. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12555. // the payload must be passed through untouched instead of being rejected.
  12556. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12557. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12558. Server svr;
  12559. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12560. res.set_content(body, "image/jpeg");
  12561. res.set_header("Content-Encoding", "UTF-8");
  12562. });
  12563. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12564. res.set_content(body, "image/jpeg");
  12565. res.set_header("Content-Encoding", "identity");
  12566. });
  12567. svr.Post("/echo", [](const Request &req, Response &res) {
  12568. res.set_content(req.body, "image/jpeg");
  12569. });
  12570. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12571. auto se = detail::scope_exit([&] {
  12572. svr.stop();
  12573. t.join();
  12574. ASSERT_FALSE(svr.is_running());
  12575. });
  12576. svr.wait_until_ready();
  12577. Client cli(HOST, PORT);
  12578. {
  12579. auto res = cli.Get("/image");
  12580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12581. EXPECT_EQ(StatusCode::OK_200, res->status);
  12582. EXPECT_EQ(body, res->body);
  12583. }
  12584. {
  12585. auto res = cli.Get("/identity");
  12586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12587. EXPECT_EQ(StatusCode::OK_200, res->status);
  12588. EXPECT_EQ(body, res->body);
  12589. }
  12590. {
  12591. // The same applies to a request body reaching the server.
  12592. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12593. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12595. EXPECT_EQ(StatusCode::OK_200, res->status);
  12596. EXPECT_EQ(body, res->body);
  12597. }
  12598. }
  12599. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12600. // gzip-encoded response even when the build has no zlib support.
  12601. static const char GZIPPED_HELLO_WORLD[] = {
  12602. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12603. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12604. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12605. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12606. // A content coding is a whole token, not something the field value merely
  12607. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12608. // as "fibre" look like Brotli, and turned a multi-coding value like
  12609. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12610. // it was never meant to see.
  12611. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12612. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12613. Server svr;
  12614. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12615. res.set_content(body, "image/jpeg");
  12616. res.set_header("Content-Encoding", "fibre");
  12617. });
  12618. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12619. res.set_content(body, "image/jpeg");
  12620. res.set_header("Content-Encoding", "gzip, br");
  12621. });
  12622. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12623. res.set_content(body, "image/jpeg");
  12624. res.set_header("Content-Encoding", "x-zstd-ish");
  12625. });
  12626. auto port = svr.bind_to_any_port(HOST);
  12627. thread t = thread([&]() { svr.listen_after_bind(); });
  12628. auto se = detail::scope_exit([&] {
  12629. svr.stop();
  12630. t.join();
  12631. ASSERT_FALSE(svr.is_running());
  12632. });
  12633. svr.wait_until_ready();
  12634. Client cli(HOST, port);
  12635. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12636. auto res = cli.Get(path);
  12637. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12638. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12639. // Not a coding we recognize, so the payload comes back untouched
  12640. EXPECT_EQ(body, res->body) << path;
  12641. }
  12642. }
  12643. // A content coding cpp-httplib recognizes but was not built with must be
  12644. // reported as such. Handing the still-compressed payload back to the caller
  12645. // would silently corrupt it.
  12646. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12647. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12648. Server svr;
  12649. // "image/jpeg" keeps the server from applying a content coding of its own,
  12650. // so the hand-crafted Content-Encoding below survives.
  12651. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12652. res.set_content(gzipped, "image/jpeg");
  12653. res.set_header("Content-Encoding", "gzip");
  12654. });
  12655. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12656. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12657. res.set_content(gzipped, "image/jpeg");
  12658. res.set_header("Content-Encoding", "GZIP");
  12659. });
  12660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12661. auto se = detail::scope_exit([&] {
  12662. svr.stop();
  12663. t.join();
  12664. ASSERT_FALSE(svr.is_running());
  12665. });
  12666. svr.wait_until_ready();
  12667. Client cli(HOST, PORT);
  12668. {
  12669. auto res = cli.Get("/gzipped");
  12670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. EXPECT_EQ("Hello World!", res->body);
  12673. #else
  12674. ASSERT_FALSE(res);
  12675. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12676. #endif
  12677. }
  12678. {
  12679. // open_stream() must behave the same way.
  12680. auto handle = cli.open_stream("GET", "/gzipped");
  12681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12682. ASSERT_TRUE(handle.is_valid());
  12683. std::string received;
  12684. char buf[256];
  12685. ssize_t n;
  12686. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12687. received.append(buf, static_cast<size_t>(n));
  12688. }
  12689. EXPECT_EQ("Hello World!", received);
  12690. #else
  12691. EXPECT_FALSE(handle.is_valid());
  12692. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12693. #endif
  12694. }
  12695. {
  12696. // A differently-cased coding must not be mistaken for an unknown one, or
  12697. // the body would be handed back still compressed.
  12698. auto res = cli.Get("/gzipped-uppercase");
  12699. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12701. EXPECT_EQ("Hello World!", res->body);
  12702. #else
  12703. ASSERT_FALSE(res);
  12704. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12705. #endif
  12706. }
  12707. }
  12708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12709. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12710. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12711. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12712. // body a second time and appending a second Content-Encoding field line, so
  12713. // clients that decode one coding per listed value handed back raw gzip bytes.
  12714. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12715. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12716. Server svr;
  12717. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12718. // keeps the server from applying a coding of its own.
  12719. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12720. res.set_content(gzipped, "text/plain");
  12721. res.set_header("Content-Encoding", "gzip");
  12722. });
  12723. auto port = svr.bind_to_any_port(HOST);
  12724. thread t = thread([&]() { svr.listen_after_bind(); });
  12725. auto se = detail::scope_exit([&] {
  12726. svr.stop();
  12727. t.join();
  12728. ASSERT_FALSE(svr.is_running());
  12729. });
  12730. svr.wait_until_ready();
  12731. Client cli(HOST, port);
  12732. Headers headers = {{"Accept-Encoding", "gzip"}};
  12733. auto res = cli.Get("/pre-gzipped", headers);
  12734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12735. EXPECT_EQ(StatusCode::OK_200, res->status);
  12736. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12737. EXPECT_EQ("Hello World!", res->body);
  12738. }
  12739. // set_compress(false) sends every handler response as it is, buffered or
  12740. // streamed
  12741. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12742. const std::string text(1000, 'a');
  12743. Server svr;
  12744. svr.set_compress(false);
  12745. svr.Get("/buffered", [&](const Request &, Response &res) {
  12746. res.set_content(text, "text/plain");
  12747. });
  12748. svr.Get("/streamed", [&](const Request &, Response &res) {
  12749. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12750. sink.write(text.data(), text.size());
  12751. sink.done();
  12752. return true;
  12753. });
  12754. });
  12755. auto port = svr.bind_to_any_port(HOST);
  12756. ASSERT_LT(0, port);
  12757. thread t = thread([&] { svr.listen_after_bind(); });
  12758. auto se = detail::scope_exit([&] {
  12759. svr.stop();
  12760. t.join();
  12761. ASSERT_FALSE(svr.is_running());
  12762. });
  12763. svr.wait_until_ready();
  12764. Client cli(HOST, port);
  12765. cli.set_decompress(false);
  12766. for (auto path : {"/buffered", "/streamed"}) {
  12767. SCOPED_TRACE(path);
  12768. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12770. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12771. EXPECT_EQ(text, res->body);
  12772. }
  12773. }
  12774. // A chunked provider settles its coding where the headers are written and
  12775. // reuses it at write time. Both ends of that have to hold: a handler's own
  12776. // Content-Encoding suppresses the coding, and a response without one is still
  12777. // compressed as it always was.
  12778. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12779. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12780. const std::string plain = "Hello World! Hello World! Hello World!";
  12781. Server svr;
  12782. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12783. res.set_header("Content-Encoding", "gzip");
  12784. res.set_chunked_content_provider(
  12785. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12786. sink.write(gzipped.data(), gzipped.size());
  12787. sink.done();
  12788. return true;
  12789. });
  12790. });
  12791. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12792. res.set_chunked_content_provider(
  12793. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12794. sink.write(plain.data(), plain.size());
  12795. sink.done();
  12796. return true;
  12797. });
  12798. });
  12799. auto port = svr.bind_to_any_port(HOST);
  12800. thread t = thread([&]() { svr.listen_after_bind(); });
  12801. auto se = detail::scope_exit([&] {
  12802. svr.stop();
  12803. t.join();
  12804. ASSERT_FALSE(svr.is_running());
  12805. });
  12806. svr.wait_until_ready();
  12807. Client cli(HOST, port);
  12808. Headers headers = {{"Accept-Encoding", "gzip"}};
  12809. {
  12810. auto res = cli.Get("/pre-gzipped", headers);
  12811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12812. EXPECT_EQ(StatusCode::OK_200, res->status);
  12813. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12814. EXPECT_EQ("Hello World!", res->body);
  12815. }
  12816. {
  12817. auto res = cli.Get("/negotiated", headers);
  12818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12819. EXPECT_EQ(StatusCode::OK_200, res->status);
  12820. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12821. EXPECT_EQ(plain, res->body);
  12822. }
  12823. }
  12824. #endif
  12825. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12826. // the same message as the comma-joined one, so both have to be read the same
  12827. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12828. // single gzip coding, and a body the sender says was encoded twice was handed
  12829. // back after one pass, still compressed but presented as decoded.
  12830. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12831. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12832. Server svr;
  12833. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12834. res.set_content(body, "image/jpeg");
  12835. res.headers.emplace("Content-Encoding", "gzip");
  12836. res.headers.emplace("Content-Encoding", "gzip");
  12837. });
  12838. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12839. res.set_content(body, "image/jpeg");
  12840. res.set_header("Content-Encoding", "gzip, gzip");
  12841. });
  12842. auto port = svr.bind_to_any_port(HOST);
  12843. thread t = thread([&]() { svr.listen_after_bind(); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. ASSERT_FALSE(svr.is_running());
  12848. });
  12849. svr.wait_until_ready();
  12850. Client cli(HOST, port);
  12851. // Two codings is not something cpp-httplib decodes, so both representations
  12852. // take the pass-through path rather than one of them being gunzipped once.
  12853. for (const char *path : {"/split", "/joined"}) {
  12854. auto res = cli.Get(path);
  12855. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12856. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12857. EXPECT_EQ(body, res->body) << path;
  12858. }
  12859. }
  12860. // Regression test for DoS vulnerability: a malicious server sending a response
  12861. // without Content-Length header must not cause unbounded memory consumption on
  12862. // the client side. The client should stop reading after a reasonable limit,
  12863. // similar to the server-side set_payload_max_length protection.
  12864. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12865. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12866. #ifndef _WIN32
  12867. signal(SIGPIPE, SIG_IGN);
  12868. #endif
  12869. auto server_thread = std::thread([] {
  12870. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12872. default_socket_options(srv);
  12873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12875. sockaddr_in addr{};
  12876. addr.sin_family = AF_INET;
  12877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12879. int opt = 1;
  12880. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12881. #ifdef _WIN32
  12882. reinterpret_cast<const char *>(&opt),
  12883. #else
  12884. &opt,
  12885. #endif
  12886. sizeof(opt));
  12887. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12888. ::listen(srv, 1);
  12889. sockaddr_in cli_addr{};
  12890. socklen_t cli_len = sizeof(cli_addr);
  12891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12892. if (cli != INVALID_SOCKET) {
  12893. char buf[4096];
  12894. ::recv(cli, buf, sizeof(buf), 0);
  12895. // Malicious response: no Content-Length, no chunked encoding
  12896. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12897. "Connection: close\r\n"
  12898. "\r\n";
  12899. ::send(cli,
  12900. #ifdef _WIN32
  12901. static_cast<const char *>(response_header.c_str()),
  12902. static_cast<int>(response_header.size()),
  12903. #else
  12904. response_header.c_str(), response_header.size(),
  12905. #endif
  12906. 0);
  12907. // Send 10MB of data
  12908. std::string chunk(64 * 1024, 'A');
  12909. size_t total_sent = 0;
  12910. while (total_sent < MALICIOUS_DATA_SIZE) {
  12911. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12912. auto sent = ::send(cli,
  12913. #ifdef _WIN32
  12914. static_cast<const char *>(chunk.c_str()),
  12915. static_cast<int>(to_send),
  12916. #else
  12917. chunk.c_str(), to_send,
  12918. #endif
  12919. 0);
  12920. if (sent <= 0) break;
  12921. total_sent += static_cast<size_t>(sent);
  12922. }
  12923. detail::close_socket(cli);
  12924. }
  12925. detail::close_socket(srv);
  12926. });
  12927. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12928. size_t total_read = 0;
  12929. {
  12930. Client cli("127.0.0.1", PORT + 2);
  12931. cli.set_read_timeout(5, 0);
  12932. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12933. auto stream = cli.open_stream("GET", "/malicious");
  12934. ASSERT_TRUE(stream.is_valid());
  12935. char buffer[64 * 1024];
  12936. ssize_t n;
  12937. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12938. total_read += static_cast<size_t>(n);
  12939. }
  12940. } // StreamHandle and Client destroyed here, closing the socket
  12941. server_thread.join();
  12942. // With set_payload_max_length, the client must stop reading before consuming
  12943. // all 10MB. The read loop should be cut off at or near the configured limit.
  12944. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12945. << "Client read " << total_read << " bytes, exceeding the configured "
  12946. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12947. }
  12948. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12949. // the entire response body without truncation.
  12950. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12951. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12952. #ifndef _WIN32
  12953. signal(SIGPIPE, SIG_IGN);
  12954. #endif
  12955. auto server_thread = std::thread([] {
  12956. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12957. default_socket_options(srv);
  12958. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12959. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12960. sockaddr_in addr{};
  12961. addr.sin_family = AF_INET;
  12962. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12963. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12964. int opt = 1;
  12965. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12966. #ifdef _WIN32
  12967. reinterpret_cast<const char *>(&opt),
  12968. #else
  12969. &opt,
  12970. #endif
  12971. sizeof(opt));
  12972. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12973. ::listen(srv, 1);
  12974. sockaddr_in cli_addr{};
  12975. socklen_t cli_len = sizeof(cli_addr);
  12976. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12977. if (cli != INVALID_SOCKET) {
  12978. char buf[4096];
  12979. ::recv(cli, buf, sizeof(buf), 0);
  12980. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12981. "Connection: close\r\n"
  12982. "\r\n";
  12983. ::send(cli,
  12984. #ifdef _WIN32
  12985. static_cast<const char *>(response_header.c_str()),
  12986. static_cast<int>(response_header.size()),
  12987. #else
  12988. response_header.c_str(), response_header.size(),
  12989. #endif
  12990. 0);
  12991. std::string chunk(64 * 1024, 'A');
  12992. size_t total_sent = 0;
  12993. while (total_sent < DATA_SIZE) {
  12994. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12995. auto sent = ::send(cli,
  12996. #ifdef _WIN32
  12997. static_cast<const char *>(chunk.c_str()),
  12998. static_cast<int>(to_send),
  12999. #else
  13000. chunk.c_str(), to_send,
  13001. #endif
  13002. 0);
  13003. if (sent <= 0) break;
  13004. total_sent += static_cast<size_t>(sent);
  13005. }
  13006. #ifdef _WIN32
  13007. ::shutdown(cli, SD_SEND);
  13008. #else
  13009. ::shutdown(cli, SHUT_WR);
  13010. #endif
  13011. // Drain until the client closes its end, ensuring all data is delivered
  13012. char drain[1024];
  13013. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13014. detail::close_socket(cli);
  13015. }
  13016. detail::close_socket(srv);
  13017. });
  13018. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13019. size_t total_read = 0;
  13020. {
  13021. Client cli("127.0.0.1", PORT + 2);
  13022. cli.set_read_timeout(5, 0);
  13023. cli.set_payload_max_length(0); // 0 means no limit
  13024. auto stream = cli.open_stream("GET", "/data");
  13025. ASSERT_TRUE(stream.is_valid());
  13026. char buffer[64 * 1024];
  13027. ssize_t n;
  13028. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13029. total_read += static_cast<size_t>(n);
  13030. }
  13031. }
  13032. server_thread.join();
  13033. EXPECT_EQ(total_read, DATA_SIZE)
  13034. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13035. << " bytes without truncation, but only read " << total_read << " bytes.";
  13036. }
  13037. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13038. // enormous Content-Length must not cause the client to pre-allocate a huge
  13039. // response body buffer. The reservation is capped at payload_max_length_, and
  13040. // the read itself fails when the body exceeds the limit.
  13041. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13042. #ifndef _WIN32
  13043. signal(SIGPIPE, SIG_IGN);
  13044. #endif
  13045. auto server_thread = std::thread([] {
  13046. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13047. default_socket_options(srv);
  13048. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13049. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13050. sockaddr_in addr{};
  13051. addr.sin_family = AF_INET;
  13052. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13053. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13054. int opt = 1;
  13055. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13056. #ifdef _WIN32
  13057. reinterpret_cast<const char *>(&opt),
  13058. #else
  13059. &opt,
  13060. #endif
  13061. sizeof(opt));
  13062. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13063. ::listen(srv, 1);
  13064. sockaddr_in cli_addr{};
  13065. socklen_t cli_len = sizeof(cli_addr);
  13066. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13067. if (cli != INVALID_SOCKET) {
  13068. char buf[4096];
  13069. ::recv(cli, buf, sizeof(buf), 0);
  13070. // Malicious response: claim a 20GB body but send only a tiny payload.
  13071. std::string response = "HTTP/1.1 200 OK\r\n"
  13072. "Content-Length: 20000000000\r\n"
  13073. "\r\n"
  13074. "abc";
  13075. ::send(cli,
  13076. #ifdef _WIN32
  13077. static_cast<const char *>(response.c_str()),
  13078. static_cast<int>(response.size()),
  13079. #else
  13080. response.c_str(), response.size(),
  13081. #endif
  13082. 0);
  13083. detail::close_socket(cli);
  13084. }
  13085. detail::close_socket(srv);
  13086. });
  13087. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13088. {
  13089. Client cli("127.0.0.1", PORT + 2);
  13090. cli.set_read_timeout(5, 0);
  13091. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13092. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13093. // (server claims more bytes than payload_max_length permits), but it must
  13094. // not exhaust memory before getting there.
  13095. auto res = cli.Get("/malicious");
  13096. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13097. }
  13098. server_thread.join();
  13099. }
  13100. // Verify that content_receiver bypasses the default payload_max_length,
  13101. // allowing streaming downloads larger than 100MB without requiring an explicit
  13102. // set_payload_max_length call.
  13103. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13105. #ifndef _WIN32
  13106. signal(SIGPIPE, SIG_IGN);
  13107. #endif
  13108. auto server_thread = std::thread([] {
  13109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13110. default_socket_options(srv);
  13111. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13113. sockaddr_in addr{};
  13114. addr.sin_family = AF_INET;
  13115. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13116. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13117. int opt = 1;
  13118. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13119. #ifdef _WIN32
  13120. reinterpret_cast<const char *>(&opt),
  13121. #else
  13122. &opt,
  13123. #endif
  13124. sizeof(opt));
  13125. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13126. ::listen(srv, 1);
  13127. sockaddr_in cli_addr{};
  13128. socklen_t cli_len = sizeof(cli_addr);
  13129. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13130. if (cli != INVALID_SOCKET) {
  13131. char buf[4096];
  13132. ::recv(cli, buf, sizeof(buf), 0);
  13133. // Response with Content-Length larger than default 100MB limit
  13134. auto content_length = std::to_string(DATA_SIZE);
  13135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13136. "Content-Length: " +
  13137. content_length +
  13138. "\r\n"
  13139. "Connection: close\r\n"
  13140. "\r\n";
  13141. ::send(cli,
  13142. #ifdef _WIN32
  13143. static_cast<const char *>(response_header.c_str()),
  13144. static_cast<int>(response_header.size()),
  13145. #else
  13146. response_header.c_str(), response_header.size(),
  13147. #endif
  13148. 0);
  13149. std::string chunk(64 * 1024, 'A');
  13150. size_t total_sent = 0;
  13151. while (total_sent < DATA_SIZE) {
  13152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13153. auto sent = ::send(cli,
  13154. #ifdef _WIN32
  13155. static_cast<const char *>(chunk.c_str()),
  13156. static_cast<int>(to_send),
  13157. #else
  13158. chunk.c_str(), to_send,
  13159. #endif
  13160. 0);
  13161. if (sent <= 0) break;
  13162. total_sent += static_cast<size_t>(sent);
  13163. }
  13164. detail::close_socket(cli);
  13165. }
  13166. detail::close_socket(srv);
  13167. });
  13168. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13169. size_t total_received = 0;
  13170. {
  13171. Client cli("127.0.0.1", PORT + 2);
  13172. cli.set_read_timeout(10, 0);
  13173. // Do NOT call set_payload_max_length — use the default 100MB limit
  13174. auto res =
  13175. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13176. total_received += data_length;
  13177. return true;
  13178. });
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. EXPECT_EQ(StatusCode::OK_200, res->status);
  13181. }
  13182. server_thread.join();
  13183. EXPECT_EQ(total_received, DATA_SIZE)
  13184. << "With content_receiver, the client should read all " << DATA_SIZE
  13185. << " bytes despite the default 100MB payload_max_length, but only read "
  13186. << total_received << " bytes.";
  13187. }
  13188. // Verify that an explicit set_payload_max_length smaller than the response is
  13189. // enforced even when a content_receiver is used.
  13190. TEST(ClientVulnerabilityTest,
  13191. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13192. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13193. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13194. #ifndef _WIN32
  13195. signal(SIGPIPE, SIG_IGN);
  13196. #endif
  13197. auto server_thread = std::thread([] {
  13198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13199. default_socket_options(srv);
  13200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13202. sockaddr_in addr{};
  13203. addr.sin_family = AF_INET;
  13204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13206. int opt = 1;
  13207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13208. #ifdef _WIN32
  13209. reinterpret_cast<const char *>(&opt),
  13210. #else
  13211. &opt,
  13212. #endif
  13213. sizeof(opt));
  13214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13215. ::listen(srv, 1);
  13216. sockaddr_in cli_addr{};
  13217. socklen_t cli_len = sizeof(cli_addr);
  13218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13219. if (cli != INVALID_SOCKET) {
  13220. char buf[4096];
  13221. ::recv(cli, buf, sizeof(buf), 0);
  13222. auto content_length = std::to_string(DATA_SIZE);
  13223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13224. "Content-Length: " +
  13225. content_length +
  13226. "\r\n"
  13227. "Connection: close\r\n"
  13228. "\r\n";
  13229. ::send(cli,
  13230. #ifdef _WIN32
  13231. static_cast<const char *>(response_header.c_str()),
  13232. static_cast<int>(response_header.size()),
  13233. #else
  13234. response_header.c_str(), response_header.size(),
  13235. #endif
  13236. 0);
  13237. std::string chunk(64 * 1024, 'A');
  13238. size_t total_sent = 0;
  13239. while (total_sent < DATA_SIZE) {
  13240. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13241. auto sent = ::send(cli,
  13242. #ifdef _WIN32
  13243. static_cast<const char *>(chunk.c_str()),
  13244. static_cast<int>(to_send),
  13245. #else
  13246. chunk.c_str(), to_send,
  13247. #endif
  13248. 0);
  13249. if (sent <= 0) break;
  13250. total_sent += static_cast<size_t>(sent);
  13251. }
  13252. detail::close_socket(cli);
  13253. }
  13254. detail::close_socket(srv);
  13255. });
  13256. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13257. size_t total_received = 0;
  13258. {
  13259. Client cli("127.0.0.1", PORT + 2);
  13260. cli.set_read_timeout(10, 0);
  13261. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13262. auto res =
  13263. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13264. total_received += data_length;
  13265. return true;
  13266. });
  13267. // Should fail because 200MB exceeds the explicit 150MB limit
  13268. EXPECT_FALSE(res);
  13269. }
  13270. server_thread.join();
  13271. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13272. << "Client with content_receiver should respect the explicit "
  13273. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13274. << total_received << " bytes.";
  13275. }
  13276. // Verify that an explicit set_payload_max_length larger than the response
  13277. // allows the content_receiver to read all data successfully.
  13278. TEST(ClientVulnerabilityTest,
  13279. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13280. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13281. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13282. #ifndef _WIN32
  13283. signal(SIGPIPE, SIG_IGN);
  13284. #endif
  13285. auto server_thread = std::thread([] {
  13286. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13287. default_socket_options(srv);
  13288. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13289. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13290. sockaddr_in addr{};
  13291. addr.sin_family = AF_INET;
  13292. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13293. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13294. int opt = 1;
  13295. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13296. #ifdef _WIN32
  13297. reinterpret_cast<const char *>(&opt),
  13298. #else
  13299. &opt,
  13300. #endif
  13301. sizeof(opt));
  13302. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13303. ::listen(srv, 1);
  13304. sockaddr_in cli_addr{};
  13305. socklen_t cli_len = sizeof(cli_addr);
  13306. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13307. if (cli != INVALID_SOCKET) {
  13308. char buf[4096];
  13309. ::recv(cli, buf, sizeof(buf), 0);
  13310. auto content_length = std::to_string(DATA_SIZE);
  13311. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13312. "Content-Length: " +
  13313. content_length +
  13314. "\r\n"
  13315. "Connection: close\r\n"
  13316. "\r\n";
  13317. ::send(cli,
  13318. #ifdef _WIN32
  13319. static_cast<const char *>(response_header.c_str()),
  13320. static_cast<int>(response_header.size()),
  13321. #else
  13322. response_header.c_str(), response_header.size(),
  13323. #endif
  13324. 0);
  13325. std::string chunk(64 * 1024, 'A');
  13326. size_t total_sent = 0;
  13327. while (total_sent < DATA_SIZE) {
  13328. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13329. auto sent = ::send(cli,
  13330. #ifdef _WIN32
  13331. static_cast<const char *>(chunk.c_str()),
  13332. static_cast<int>(to_send),
  13333. #else
  13334. chunk.c_str(), to_send,
  13335. #endif
  13336. 0);
  13337. if (sent <= 0) break;
  13338. total_sent += static_cast<size_t>(sent);
  13339. }
  13340. #ifdef _WIN32
  13341. ::shutdown(cli, SD_SEND);
  13342. #else
  13343. ::shutdown(cli, SHUT_WR);
  13344. #endif
  13345. char drain[1024];
  13346. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13347. detail::close_socket(cli);
  13348. }
  13349. detail::close_socket(srv);
  13350. });
  13351. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13352. size_t total_received = 0;
  13353. {
  13354. Client cli("127.0.0.1", PORT + 2);
  13355. cli.set_read_timeout(10, 0);
  13356. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13357. auto res =
  13358. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13359. total_received += data_length;
  13360. return true;
  13361. });
  13362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13363. EXPECT_EQ(StatusCode::OK_200, res->status);
  13364. }
  13365. server_thread.join();
  13366. EXPECT_EQ(total_received, DATA_SIZE)
  13367. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13368. << " bytes (larger than " << DATA_SIZE
  13369. << " bytes response), content_receiver should read all data, but only "
  13370. "read "
  13371. << total_received << " bytes.";
  13372. }
  13373. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13374. // Regression test for "zip bomb" attack on the client side: a malicious server
  13375. // sends a small gzip-compressed response that decompresses to a huge payload.
  13376. // The client must enforce payload_max_length on the decompressed size.
  13377. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13378. constexpr size_t DECOMPRESSED_SIZE =
  13379. 10 * 1024 * 1024; // 10MB after decompression
  13380. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13381. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13382. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13383. std::string compressed;
  13384. {
  13385. httplib::detail::gzip_compressor compressor;
  13386. bool ok =
  13387. compressor.compress(uncompressed.data(), uncompressed.size(),
  13388. /*last=*/true, [&](const char *buf, size_t len) {
  13389. compressed.append(buf, len);
  13390. return true;
  13391. });
  13392. ASSERT_TRUE(ok);
  13393. }
  13394. // Sanity: compressed data should be much smaller than the decompressed size
  13395. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13396. #ifndef _WIN32
  13397. signal(SIGPIPE, SIG_IGN);
  13398. #endif
  13399. // Set up the listening socket in the main thread so the server is guaranteed
  13400. // to be ready before the client connects (eliminates race condition).
  13401. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13402. default_socket_options(srv);
  13403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13404. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13405. sockaddr_in addr{};
  13406. addr.sin_family = AF_INET;
  13407. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13408. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13409. int opt = 1;
  13410. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13411. #ifdef _WIN32
  13412. reinterpret_cast<const char *>(&opt),
  13413. #else
  13414. &opt,
  13415. #endif
  13416. sizeof(opt));
  13417. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13418. ASSERT_EQ(0, ::listen(srv, 1));
  13419. auto server_thread = std::thread([&compressed, srv] {
  13420. sockaddr_in cli_addr{};
  13421. socklen_t cli_len = sizeof(cli_addr);
  13422. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13423. if (cli != INVALID_SOCKET) {
  13424. // Read the full HTTP request (until \r\n\r\n)
  13425. char buf[4096];
  13426. size_t total = 0;
  13427. while (total < sizeof(buf)) {
  13428. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13429. if (n <= 0) break;
  13430. total += static_cast<size_t>(n);
  13431. // Check for end of headers
  13432. if (total >= 4) {
  13433. std::string req(buf, total);
  13434. if (req.find("\r\n\r\n") != std::string::npos) break;
  13435. }
  13436. }
  13437. // Malicious response: gzip-compressed body, no Content-Length
  13438. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13439. "Content-Encoding: gzip\r\n"
  13440. "Connection: close\r\n"
  13441. "\r\n";
  13442. ::send(cli,
  13443. #ifdef _WIN32
  13444. static_cast<const char *>(response_header.c_str()),
  13445. static_cast<int>(response_header.size()),
  13446. #else
  13447. response_header.c_str(), response_header.size(),
  13448. #endif
  13449. 0);
  13450. // Send the compressed payload (small on the wire, huge when decompressed)
  13451. size_t total_sent = 0;
  13452. while (total_sent < compressed.size()) {
  13453. auto to_send = std::min(compressed.size() - total_sent,
  13454. static_cast<size_t>(64 * 1024));
  13455. auto sent =
  13456. ::send(cli,
  13457. #ifdef _WIN32
  13458. static_cast<const char *>(compressed.c_str() + total_sent),
  13459. static_cast<int>(to_send),
  13460. #else
  13461. compressed.c_str() + total_sent, to_send,
  13462. #endif
  13463. 0);
  13464. if (sent <= 0) break;
  13465. total_sent += static_cast<size_t>(sent);
  13466. }
  13467. detail::close_socket(cli);
  13468. }
  13469. });
  13470. auto se = detail::scope_exit([&] {
  13471. detail::close_socket(srv);
  13472. server_thread.join();
  13473. });
  13474. size_t total_decompressed = 0;
  13475. {
  13476. Client cli("127.0.0.1", PORT + 3);
  13477. cli.set_read_timeout(5, 0);
  13478. cli.set_decompress(true);
  13479. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13480. auto stream = cli.open_stream("GET", "/zipbomb");
  13481. ASSERT_TRUE(stream.is_valid());
  13482. char buffer[64 * 1024];
  13483. ssize_t n;
  13484. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13485. total_decompressed += static_cast<size_t>(n);
  13486. }
  13487. }
  13488. // The decompressed size must be capped by payload_max_length. Without
  13489. // protection, the client would decompress the full 10MB from a tiny
  13490. // compressed payload, enabling a zip bomb DoS attack.
  13491. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13492. << "Client decompressed " << total_decompressed
  13493. << " bytes from a gzip response. The decompressed size should be "
  13494. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13495. }
  13496. #endif
  13497. TEST(HostAndPortPropertiesTest, NoSSL) {
  13498. httplib::Client cli("www.google.com", 1234);
  13499. ASSERT_EQ("www.google.com", cli.host());
  13500. ASSERT_EQ(1234, cli.port());
  13501. }
  13502. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13503. httplib::Client cli("www.google.com:1234");
  13504. ASSERT_EQ("www.google.com", cli.host());
  13505. ASSERT_EQ(1234, cli.port());
  13506. }
  13507. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13508. // Port number that overflows int — should not crash, client becomes invalid
  13509. httplib::Client cli("http://www.google.com:99999999999999999999");
  13510. ASSERT_FALSE(cli.is_valid());
  13511. }
  13512. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13513. // Port 99999 exceeds valid range (1-65535) — should not crash
  13514. httplib::Client cli("http://www.google.com:99999");
  13515. ASSERT_FALSE(cli.is_valid());
  13516. auto res = cli.Get("/");
  13517. EXPECT_FALSE(res);
  13518. EXPECT_EQ(Error::Connection, res.error());
  13519. }
  13520. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13521. httplib::Client cli("http://user:pass@localhost:1234");
  13522. ASSERT_FALSE(cli.is_valid());
  13523. EXPECT_FALSE(cli.Get("/"));
  13524. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13525. }
  13526. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13527. httplib::Client cli("http://www.google.com:80abc");
  13528. ASSERT_FALSE(cli.is_valid());
  13529. }
  13530. #ifdef CPPHTTPLIB_SSL_ENABLED
  13531. TEST(HostAndPortPropertiesTest, SSL) {
  13532. httplib::SSLClient cli("www.google.com");
  13533. ASSERT_EQ("www.google.com", cli.host());
  13534. ASSERT_EQ(443, cli.port());
  13535. }
  13536. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13537. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13538. std::string cert;
  13539. read_file(CA_CERT_FILE, cert);
  13540. httplib::SSLClient httplib_client("www.google.com");
  13541. // Load CA store first time
  13542. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13543. // Load CA store second time (update)
  13544. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13545. // Verify client is still valid and can make connections
  13546. httplib_client.enable_server_certificate_verification(true);
  13547. auto res = httplib_client.Get("/");
  13548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13549. // Google may return 200 or 301 depending on various factors
  13550. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13551. res->status == StatusCode::MovedPermanently_301);
  13552. }
  13553. TEST(SSLClientTest, ServerNameIndication_Online) {
  13554. auto host = "httpbingo.org";
  13555. auto path = std::string{"/get"};
  13556. SSLClient cli(host, 443);
  13557. auto res = cli.Get(path);
  13558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13559. ASSERT_EQ(StatusCode::OK_200, res->status);
  13560. }
  13561. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13562. // Use a site that will cause SSL verification failure due to self-signed cert
  13563. SSLClient cli("self-signed.badssl.com", 443);
  13564. cli.enable_server_certificate_verification(true);
  13565. auto res = cli.Get("/");
  13566. ASSERT_TRUE(!res);
  13567. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13568. // Verify backend error is captured for SSLServerVerification
  13569. // This occurs when certificate verification fails
  13570. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13571. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13572. EXPECT_NE(0UL, res.ssl_backend_error());
  13573. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13574. res.ssl_error());
  13575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13576. #if !defined(_WIN32) || \
  13577. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13578. // On non-Windows or when Windows Schannel is disabled, the error comes
  13579. // from OpenSSL's verification
  13580. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13581. res.ssl_backend_error());
  13582. #endif
  13583. #endif
  13584. }
  13585. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13586. // Use a site where hostname doesn't match the certificate
  13587. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13588. SSLClient cli("wrong.host.badssl.com", 443);
  13589. cli.enable_server_certificate_verification(true);
  13590. cli.enable_server_hostname_verification(true);
  13591. auto res = cli.Get("/");
  13592. ASSERT_TRUE(!res);
  13593. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13594. // Verify backend error is captured for hostname verification failure
  13595. EXPECT_NE(0UL, res.ssl_backend_error());
  13596. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13597. res.ssl_error());
  13598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13599. #if !defined(_WIN32) || \
  13600. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13601. // On non-Windows or when Windows Schannel is disabled, the error comes
  13602. // from OpenSSL's hostname verification
  13603. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13604. res.ssl_backend_error());
  13605. #endif
  13606. #endif
  13607. }
  13608. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13609. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13610. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13611. SSLClient cli("www.google.com", 443);
  13612. cli.enable_server_certificate_verification(true);
  13613. auto res = cli.Get("/");
  13614. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13615. }
  13616. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13617. SSLClient cli("www.google.com", 443);
  13618. cli.enable_server_certificate_verification(true);
  13619. cli.enable_windows_certificate_verification(false);
  13620. auto res = cli.Get("/");
  13621. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13622. }
  13623. // The server sends an intermediate cross-signed by a root Windows trusts,
  13624. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13625. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13626. SSLClient cli("accounts.spotify.com", 443);
  13627. auto res = cli.Get("/");
  13628. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13629. << " ssl_backend_error=" << res.ssl_backend_error();
  13630. }
  13631. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13632. // policy status, which no backend reports for a self-signed certificate.
  13633. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13634. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13635. ASSERT_TRUE(svr.is_valid());
  13636. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13637. auto se = detail::scope_exit([&] {
  13638. svr.stop();
  13639. t.join();
  13640. ASSERT_FALSE(svr.is_running());
  13641. });
  13642. svr.wait_until_ready();
  13643. SSLClient cli("127.0.0.1", PORT);
  13644. cli.set_connection_timeout(30);
  13645. auto res = cli.Get("/");
  13646. ASSERT_FALSE(res);
  13647. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13648. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13649. }
  13650. #endif
  13651. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13652. Client cli("https://google.com");
  13653. auto res = cli.Get("/");
  13654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13655. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13656. }
  13657. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13658. SSLClient cli("google.com");
  13659. cli.set_ca_cert_path(CA_CERT_FILE);
  13660. auto res = cli.Get("/");
  13661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13662. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13663. }
  13664. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13665. SSLClient cli("google.com");
  13666. cli.enable_server_certificate_verification(true);
  13667. cli.set_ca_cert_path("hello");
  13668. auto res = cli.Get("/");
  13669. ASSERT_TRUE(!res);
  13670. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13671. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13672. // should be set
  13673. EXPECT_EQ(0, res.ssl_error());
  13674. // Verify backend error is captured for SSLLoadingCerts
  13675. // This error occurs when loading CA certificates fails
  13676. EXPECT_NE(0UL, res.ssl_backend_error());
  13677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13678. // OpenSSL specific error codes:
  13679. // > openssl errstr 0x80000002
  13680. // error:80000002:system library::No such file or directory
  13681. // > openssl errstr 0xA000126
  13682. // error:0A000126:SSL routines::unexpected eof while reading
  13683. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13684. res.ssl_backend_error() == 0xA000126);
  13685. #endif
  13686. }
  13687. TEST(SSLClientTest, ServerCertificateVerification4) {
  13688. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13689. ASSERT_TRUE(svr.is_valid());
  13690. svr.Get("/test", [&](const Request &, Response &res) {
  13691. res.set_content("test", "text/plain");
  13692. svr.stop();
  13693. ASSERT_TRUE(true);
  13694. });
  13695. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13696. auto se = detail::scope_exit([&] {
  13697. t.join();
  13698. ASSERT_FALSE(svr.is_running());
  13699. });
  13700. svr.wait_until_ready();
  13701. SSLClient cli("127.0.0.1", PORT);
  13702. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13703. cli.enable_server_certificate_verification(true);
  13704. cli.set_connection_timeout(30);
  13705. auto res = cli.Get("/test");
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_EQ(StatusCode::OK_200, res->status);
  13708. }
  13709. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13710. std::string cert;
  13711. read_file(CA_CERT_FILE, cert);
  13712. SSLClient cli("google.com");
  13713. cli.load_ca_cert_store(cert.data(), cert.size());
  13714. const auto res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13717. }
  13718. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13719. // clang-format off
  13720. static constexpr char cert[] =
  13721. "GlobalSign Root CA\n"
  13722. "==================\n"
  13723. "-----BEGIN CERTIFICATE-----\n"
  13724. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13725. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13726. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13727. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13728. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13729. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13730. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13731. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13732. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13733. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13734. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13735. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13736. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13737. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13738. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13739. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13740. "-----END CERTIFICATE-----\n";
  13741. // clang-format on
  13742. SSLClient cli("google.com");
  13743. cli.load_ca_cert_store(cert, sizeof(cert));
  13744. const auto res = cli.Get("/");
  13745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13747. }
  13748. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13749. SSLClient cli("www.youtube.com");
  13750. cli.set_ca_cert_path(CA_CERT_FILE);
  13751. cli.enable_server_certificate_verification(true);
  13752. cli.set_follow_location(true);
  13753. auto res = cli.Get("/");
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. ASSERT_EQ(StatusCode::OK_200, res->status);
  13756. }
  13757. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13758. SSLClient cli("wWw.YouTube.Com");
  13759. cli.set_ca_cert_path(CA_CERT_FILE);
  13760. cli.enable_server_certificate_verification(true);
  13761. cli.enable_server_hostname_verification(true);
  13762. cli.set_follow_location(true);
  13763. auto res = cli.Get("/");
  13764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13765. ASSERT_EQ(StatusCode::OK_200, res->status);
  13766. }
  13767. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13768. SSLClient cli("gOoGlE.COm");
  13769. cli.enable_server_certificate_verification(true);
  13770. cli.enable_server_hostname_verification(true);
  13771. cli.set_follow_location(true);
  13772. auto res = cli.Get("/");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. ASSERT_EQ(StatusCode::OK_200, res->status);
  13775. }
  13776. TEST(SSLClientTest, Issue2004_Online) {
  13777. Client client("https://google.com");
  13778. client.set_follow_location(true);
  13779. auto res = client.Get("/");
  13780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13781. ASSERT_EQ(StatusCode::OK_200, res->status);
  13782. auto body = res->body;
  13783. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13784. }
  13785. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13786. // Create SSLClient with invalid cert/key to make is_valid() return false
  13787. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13788. "nonexistent_key.pem");
  13789. // is_valid() should be false due to cert loading failure
  13790. ASSERT_FALSE(cli.is_valid());
  13791. auto res = cli.Get("/");
  13792. ASSERT_FALSE(res);
  13793. EXPECT_EQ(Error::SSLConnection, res.error());
  13794. }
  13795. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13796. // Test for Issue #2251: SSL error not properly reported when client cert
  13797. // and key paths are swapped or mismatched
  13798. // This simulates the scenario where user accidentally swaps the cert and key
  13799. // files
  13800. // Using client cert file as private key and vice versa (completely wrong)
  13801. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13802. // Should fail validation due to cert/key mismatch
  13803. ASSERT_FALSE(cli.is_valid());
  13804. // Attempt to make a request should fail with proper error
  13805. auto res = cli.Get("/");
  13806. ASSERT_FALSE(res);
  13807. EXPECT_EQ(Error::SSLConnection, res.error());
  13808. // SSL error should be recorded in the Result object (this is the key fix for
  13809. // Issue #2251)
  13810. auto backend_error = res.ssl_backend_error();
  13811. EXPECT_NE(0u, backend_error);
  13812. }
  13813. // Tests cert/key mismatch detection at the TLS context level
  13814. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13815. // Test that using mismatched cert/key causes connection failure.
  13816. // We verify this at the SSLClient level rather than through internal
  13817. // TLS API functions.
  13818. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13819. cli.enable_server_certificate_verification(false);
  13820. cli.set_connection_timeout(2);
  13821. // The mismatch should cause a connection or handshake error
  13822. auto res = cli.Get("/test");
  13823. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13824. // Either way, the request should fail
  13825. EXPECT_FALSE(res);
  13826. }
  13827. #endif
  13828. #if 0
  13829. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13830. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13831. ASSERT_TRUE(cli != nullptr);
  13832. cli->set_address_family(AF_INET6);
  13833. cli->set_interface("en0");
  13834. auto res = cli->Get("/get");
  13835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13836. ASSERT_EQ(StatusCode::OK_200, res->status);
  13837. }
  13838. #endif
  13839. // Client certificate tests - work with all TLS backends
  13840. #ifdef CPPHTTPLIB_SSL_ENABLED
  13841. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13842. void ClientCertPresent(
  13843. const std::string &client_cert_file,
  13844. const std::string &client_private_key_file,
  13845. const std::string &client_encrypted_private_key_pass = std::string(),
  13846. const ClientCertServerSetup &setup = nullptr) {
  13847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13848. ASSERT_TRUE(svr.is_valid());
  13849. if (setup) { setup(svr); }
  13850. svr.Get("/test", [&](const Request &req, Response &res) {
  13851. res.set_content("test", "text/plain");
  13852. auto cert = req.peer_cert();
  13853. ASSERT_TRUE(static_cast<bool>(cert));
  13854. std::string common_name = cert.subject_cn();
  13855. EXPECT_EQ("Common Name", common_name);
  13856. });
  13857. auto port = svr.bind_to_any_port(HOST);
  13858. ASSERT_LT(0, port);
  13859. thread t = thread([&]() { svr.listen_after_bind(); });
  13860. auto se = detail::scope_exit([&] {
  13861. svr.stop();
  13862. t.join();
  13863. ASSERT_FALSE(svr.is_running());
  13864. });
  13865. svr.wait_until_ready();
  13866. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13867. client_encrypted_private_key_pass);
  13868. cli.enable_server_certificate_verification(false);
  13869. cli.set_connection_timeout(30);
  13870. auto res = cli.Get("/test");
  13871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13872. ASSERT_EQ(StatusCode::OK_200, res->status);
  13873. }
  13874. TEST(SSLClientServerTest, ClientCertPresent) {
  13875. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13876. }
  13877. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13878. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13879. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13880. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13881. }
  13882. // Expects svr, which must require client certificates, to reject a client
  13883. // that has none
  13884. void RejectsClientWithoutCert(SSLServer &svr) {
  13885. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13886. auto port = svr.bind_to_any_port(HOST);
  13887. ASSERT_LT(0, port);
  13888. thread t = thread([&]() { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. });
  13894. svr.wait_until_ready();
  13895. SSLClient cli(HOST, port);
  13896. cli.set_connection_timeout(30);
  13897. // Skip the server certificate check, so that the request fails because the
  13898. // client certificate is missing rather than because cert.pem is not trusted
  13899. cli.enable_server_certificate_verification(false);
  13900. auto res = cli.Get("/test");
  13901. ASSERT_FALSE(res);
  13902. // The server rejects the client during the handshake, or on TLS 1.3 right
  13903. // after it, which the client notices on its first write or read
  13904. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13905. res.error() == Error::Write || res.error() == Error::Read)
  13906. << to_string(res.error());
  13907. if (res.error() == Error::SSLConnection) {
  13908. EXPECT_NE(0UL, res.ssl_backend_error());
  13909. }
  13910. // A rejection noticed on the write keeps the TLS error the write hit
  13911. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13912. }
  13913. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13915. ASSERT_TRUE(svr.is_valid());
  13916. if (setup) { setup(svr); }
  13917. RejectsClientWithoutCert(svr);
  13918. }
  13919. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13920. // A server that requires client certificates must keep requiring them after
  13921. // setup changes it, and keep accepting a client that has one
  13922. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13923. ClientCertMissing(setup);
  13924. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13925. setup);
  13926. }
  13927. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13928. ClientCertStillRequired([](SSLServer &svr) {
  13929. ASSERT_TRUE(tls::set_verify_callback(
  13930. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13931. });
  13932. }
  13933. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13934. ClientCertStillRequired([](SSLServer &svr) {
  13935. ASSERT_TRUE(tls::set_verify_callback(
  13936. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13937. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13938. });
  13939. }
  13940. // The client verifies the server certificate during the handshake, so a
  13941. // server that fails the check never gets the client certificate, even when a
  13942. // verifier of the client's own accepts it
  13943. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13944. struct Case {
  13945. const char *trusted_ca;
  13946. const char *host;
  13947. Error error;
  13948. };
  13949. // cert2.pem names localhost: the first client does not trust it, and the
  13950. // second trusts it but asks for another name
  13951. for (const auto &c :
  13952. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13953. Case{SERVER_CERT2_FILE, "example.com",
  13954. Error::SSLServerHostnameVerification}}) {
  13955. for (auto with_verifier : {false, true}) {
  13956. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13957. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13958. CLIENT_CA_CERT_FILE);
  13959. ASSERT_TRUE(svr.is_valid());
  13960. std::atomic<bool> got_client_cert{false};
  13961. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13962. [&](const tls::VerifyContext &) {
  13963. got_client_cert = true;
  13964. return true;
  13965. }));
  13966. auto port = svr.bind_to_any_port("127.0.0.1");
  13967. ASSERT_LT(0, port);
  13968. thread t = thread([&] { svr.listen_after_bind(); });
  13969. svr.wait_until_ready();
  13970. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13971. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  13972. cli.set_ca_cert_path(c.trusted_ca);
  13973. if (with_verifier) {
  13974. cli.set_server_certificate_verifier(
  13975. [](const tls::VerifyContext &) { return true; });
  13976. }
  13977. auto res = cli.Get("/");
  13978. EXPECT_FALSE(res);
  13979. EXPECT_EQ(c.error, res.error());
  13980. svr.stop();
  13981. t.join();
  13982. EXPECT_FALSE(got_client_cert);
  13983. }
  13984. }
  13985. }
  13986. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13987. std::string cert_pem, key_pem, ca_pem;
  13988. read_file(SERVER_CERT_FILE, cert_pem);
  13989. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13990. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13991. ASSERT_TRUE(
  13992. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13993. }
  13994. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13996. ASSERT_TRUE(svr.is_valid());
  13997. UpdateCertsPemWithClientCA(svr);
  13998. RejectsClientWithoutCert(svr);
  13999. }
  14000. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14001. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14002. }
  14003. // A TLS error from one request must not show up in a later request's Result
  14004. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14006. ASSERT_TRUE(svr.is_valid());
  14007. svr.Get("/test", [](const Request &, Response &res) {
  14008. res.set_content("test", "text/plain");
  14009. });
  14010. auto port = svr.bind_to_any_port(HOST);
  14011. ASSERT_LT(0, port);
  14012. thread t = thread([&]() { svr.listen_after_bind(); });
  14013. auto se = detail::scope_exit([&] {
  14014. svr.stop();
  14015. t.join();
  14016. ASSERT_FALSE(svr.is_running());
  14017. });
  14018. svr.wait_until_ready();
  14019. SSLClient cli(HOST, port);
  14020. cli.set_connection_timeout(30);
  14021. cli.enable_server_hostname_verification(false);
  14022. // cert.pem is not trusted, so the handshake fails
  14023. ASSERT_FALSE(cli.Get("/test"));
  14024. cli.enable_server_certificate_verification(false);
  14025. auto res = cli.Get("/test");
  14026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14027. EXPECT_EQ(0, res.ssl_error());
  14028. EXPECT_EQ(0UL, res.ssl_backend_error());
  14029. }
  14030. // PEM memory-based constructor tests (works with all TLS backends).
  14031. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14032. // terminator after it.
  14033. void PemMemoryClientCertPresent(
  14034. const std::string &client_cert_file,
  14035. const std::string &client_private_key_file,
  14036. const std::string &client_encrypted_private_key_pass = std::string(),
  14037. bool exact_size = false) {
  14038. // Read PEM files into memory
  14039. std::string server_cert_pem, server_key_pem;
  14040. std::string client_ca_pem;
  14041. std::string client_cert_pem, client_key_pem;
  14042. read_file(SERVER_CERT_FILE, server_cert_pem);
  14043. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14044. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14045. read_file(client_cert_file, client_cert_pem);
  14046. read_file(client_private_key_file, client_key_pem);
  14047. std::list<std::vector<char>> exact_copies;
  14048. auto data = [&](const std::string &pem) -> const char * {
  14049. if (!exact_size) { return pem.c_str(); }
  14050. exact_copies.emplace_back(pem.begin(), pem.end());
  14051. return exact_copies.back().data();
  14052. };
  14053. // Create server with PEM memory
  14054. SSLServer::PemMemory server_pem = {
  14055. data(server_cert_pem),
  14056. server_cert_pem.size(),
  14057. data(server_key_pem),
  14058. server_key_pem.size(),
  14059. data(client_ca_pem),
  14060. client_ca_pem.size(),
  14061. nullptr // no password for server key
  14062. };
  14063. SSLServer svr(server_pem);
  14064. ASSERT_TRUE(svr.is_valid());
  14065. svr.Get("/test", [&](const Request &req, Response &res) {
  14066. res.set_content("test", "text/plain");
  14067. auto cert = req.peer_cert();
  14068. ASSERT_TRUE(static_cast<bool>(cert));
  14069. EXPECT_EQ("Common Name", cert.subject_cn());
  14070. });
  14071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14072. auto se = detail::scope_exit([&] {
  14073. svr.stop();
  14074. t.join();
  14075. ASSERT_FALSE(svr.is_running());
  14076. });
  14077. svr.wait_until_ready();
  14078. // Create client with PEM memory
  14079. const char *password = client_encrypted_private_key_pass.empty()
  14080. ? nullptr
  14081. : client_encrypted_private_key_pass.c_str();
  14082. SSLClient::PemMemory client_pem = {
  14083. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14084. client_key_pem.size(), password};
  14085. SSLClient cli(HOST, PORT, client_pem);
  14086. cli.enable_server_certificate_verification(false);
  14087. cli.set_connection_timeout(30);
  14088. auto res = cli.Get("/test");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14093. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14094. }
  14095. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14096. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14097. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14098. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14099. }
  14100. // A server built from PEM memory with a client CA requires client certificates,
  14101. // also when the CA is a NUL-terminated string passed with a length of 0
  14102. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14103. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14104. read_file(SERVER_CERT_FILE, server_cert_pem);
  14105. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14106. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14107. SSLServer::PemMemory server_pem = {
  14108. server_cert_pem.c_str(),
  14109. server_cert_pem.size(),
  14110. server_key_pem.c_str(),
  14111. server_key_pem.size(),
  14112. client_ca_pem.c_str(),
  14113. client_ca_pem.size(),
  14114. nullptr // no password for server key
  14115. };
  14116. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14117. SCOPED_TRACE(client_ca_pem_len);
  14118. server_pem.client_ca_pem_len = client_ca_pem_len;
  14119. SSLServer svr(server_pem);
  14120. ASSERT_TRUE(svr.is_valid());
  14121. RejectsClientWithoutCert(svr);
  14122. }
  14123. // An empty CA fails to load instead of turning the check off
  14124. server_pem.client_ca_pem = "";
  14125. server_pem.client_ca_pem_len = 0;
  14126. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14127. }
  14128. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14129. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14130. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14131. true);
  14132. }
  14133. // A length shorter than the PEM cuts it short, so it no longer loads
  14134. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14135. std::string cert, key;
  14136. read_file(SERVER_CERT_FILE, cert);
  14137. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14138. for (auto cut_cert : {true, false}) {
  14139. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14140. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14141. SSLServer::PemMemory server_pem = {
  14142. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14143. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14144. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14145. key_len, nullptr};
  14146. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14147. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14148. key.c_str(), key_len, nullptr};
  14149. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14150. }
  14151. }
  14152. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14153. class NoListenSSLServer : public SSLServer {
  14154. public:
  14155. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14156. const char *client_ca_cert_file_path,
  14157. const char *client_ca_cert_dir_path = nullptr)
  14158. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14159. client_ca_cert_dir_path),
  14160. stop_(false) {}
  14161. std::atomic_bool stop_;
  14162. private:
  14163. bool process_and_close_socket(socket_t /*sock*/) override {
  14164. // Don't create SSL context
  14165. while (!stop_.load()) {
  14166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14167. }
  14168. return true;
  14169. }
  14170. };
  14171. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14172. CLIENT_CA_CERT_FILE);
  14173. ASSERT_TRUE(svr.is_valid());
  14174. svr.Get("/test", [&](const Request &, Response &res) {
  14175. res.set_content("test", "text/plain");
  14176. });
  14177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14178. auto se = detail::scope_exit([&] {
  14179. svr.stop_ = true;
  14180. svr.stop();
  14181. t.join();
  14182. ASSERT_FALSE(svr.is_running());
  14183. });
  14184. svr.wait_until_ready();
  14185. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14186. cli.enable_server_certificate_verification(false);
  14187. cli.set_connection_timeout(1);
  14188. auto res = cli.Get("/test");
  14189. ASSERT_TRUE(!res);
  14190. EXPECT_EQ(Error::SSLConnection, res.error());
  14191. // Timeout results in WantRead error code (maps to backend-specific value)
  14192. EXPECT_NE(0, res.ssl_error());
  14193. }
  14194. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14195. // Test SSLServer with client certificate verification using the standard
  14196. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14198. CLIENT_CA_CERT_DIR);
  14199. ASSERT_TRUE(svr.is_valid());
  14200. svr.Get("/test", [&](const Request &req, Response &res) {
  14201. res.set_content("test", "text/plain");
  14202. auto cert = req.peer_cert();
  14203. ASSERT_TRUE(static_cast<bool>(cert));
  14204. auto common_name = cert.subject_cn();
  14205. EXPECT_EQ("Common Name", common_name);
  14206. });
  14207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. ASSERT_FALSE(svr.is_running());
  14212. });
  14213. svr.wait_until_ready();
  14214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14215. cli.enable_server_certificate_verification(false);
  14216. cli.set_connection_timeout(30);
  14217. auto res = cli.Get("/test");
  14218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14219. ASSERT_EQ(StatusCode::OK_200, res->status);
  14220. }
  14221. // Test verify_hostname on every backend: a host is named by a SAN only
  14222. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14223. using namespace httplib::tls;
  14224. // We need a running server to test against
  14225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14226. ASSERT_TRUE(svr.is_valid());
  14227. svr.Get("/test", [](const Request &, Response &res) {
  14228. res.set_content("ok", "text/plain");
  14229. });
  14230. thread t([&]() { svr.listen(HOST, PORT); });
  14231. auto se = detail::scope_exit([&] {
  14232. svr.stop();
  14233. t.join();
  14234. });
  14235. svr.wait_until_ready();
  14236. bool verify_callback_called = false;
  14237. bool verify_result_wrong = false;
  14238. SSLClient cli(HOST, PORT);
  14239. cli.enable_server_certificate_verification(true);
  14240. cli.set_ca_cert_path(CA_CERT_FILE);
  14241. cli.set_connection_timeout(5);
  14242. // Note: Test certificate has CN="Common Name", not "localhost"
  14243. bool verify_result_cn = false;
  14244. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14245. verify_callback_called = true;
  14246. if (!ctx.cert) return false;
  14247. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14248. verify_result_cn = ctx.check_hostname("Common Name");
  14249. // Test 2: wrong hostname should not match
  14250. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14251. return true; // Accept for the purpose of this test
  14252. });
  14253. auto res = cli.Get("/test");
  14254. // The request may succeed or fail depending on cert configuration
  14255. // but the callback should have been called
  14256. ASSERT_TRUE(verify_callback_called)
  14257. << "Verify callback should have been called";
  14258. EXPECT_FALSE(verify_result_cn)
  14259. << "verify_hostname must not match the certificate CN (no SAN)";
  14260. // Wrong hostname should not match
  14261. EXPECT_FALSE(verify_result_wrong)
  14262. << "verify_hostname should not match 'wronghost.example.com'";
  14263. }
  14264. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14265. // backend verifies it.
  14266. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14267. // Certificate CN is "localhost" and it carries no SAN.
  14268. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14269. ASSERT_TRUE(svr.is_valid());
  14270. svr.Get("/test", [](const Request &, Response &res) {
  14271. res.set_content("ok", "text/plain");
  14272. });
  14273. auto port = svr.bind_to_any_port(HOST);
  14274. thread t([&]() { svr.listen_after_bind(); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. });
  14279. svr.wait_until_ready();
  14280. SSLClient cli("localhost", port);
  14281. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14282. cli.enable_server_certificate_verification(true);
  14283. cli.set_connection_timeout(5);
  14284. auto res = cli.Get("/test");
  14285. ASSERT_FALSE(res);
  14286. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14287. // The same certificate is accepted once host name verification is off, so the
  14288. // failure above is the host name and not the chain.
  14289. cli.enable_server_hostname_verification(false);
  14290. res = cli.Get("/test");
  14291. ASSERT_TRUE(res) << to_string(res.error());
  14292. EXPECT_EQ(StatusCode::OK_200, res->status);
  14293. }
  14294. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14295. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14296. // X509_check_ip behavior and must hold for every backend.
  14297. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14298. using namespace httplib::tls;
  14299. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14300. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14301. ASSERT_TRUE(svr.is_valid());
  14302. svr.Get("/test", [](const Request &, Response &res) {
  14303. res.set_content("ok", "text/plain");
  14304. });
  14305. thread t([&]() { svr.listen(HOST, PORT); });
  14306. auto se = detail::scope_exit([&] {
  14307. svr.stop();
  14308. t.join();
  14309. });
  14310. svr.wait_until_ready();
  14311. bool verify_callback_called = false;
  14312. bool ip_matched_via_cn = true;
  14313. SSLClient cli(HOST, PORT);
  14314. cli.enable_server_certificate_verification(true);
  14315. cli.set_ca_cert_path(CA_CERT_FILE);
  14316. cli.set_connection_timeout(5);
  14317. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14318. verify_callback_called = true;
  14319. if (!ctx.cert) return false;
  14320. // The IP appears only in the CN, so it must NOT be accepted.
  14321. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14322. return true; // Accept for the purpose of this test
  14323. });
  14324. cli.Get("/test");
  14325. ASSERT_TRUE(verify_callback_called)
  14326. << "Verify callback should have been called";
  14327. EXPECT_FALSE(ip_matched_via_cn)
  14328. << "An IP host must not be authenticated via the certificate CN";
  14329. }
  14330. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14331. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14332. using namespace httplib::tls;
  14333. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14334. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14335. ASSERT_TRUE(svr.is_valid());
  14336. svr.Get("/test", [](const Request &, Response &res) {
  14337. res.set_content("ok", "text/plain");
  14338. });
  14339. thread t([&]() { svr.listen(HOST, PORT); });
  14340. auto se = detail::scope_exit([&] {
  14341. svr.stop();
  14342. t.join();
  14343. });
  14344. svr.wait_until_ready();
  14345. bool verify_callback_called = false;
  14346. bool san_matched = false;
  14347. bool wrong_ipv6_matched = true;
  14348. bool cn_ipv6_matched = true;
  14349. SSLClient cli(HOST, PORT);
  14350. cli.enable_server_certificate_verification(true);
  14351. cli.set_ca_cert_path(CA_CERT_FILE);
  14352. cli.set_connection_timeout(5);
  14353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14354. verify_callback_called = true;
  14355. if (!ctx.cert) return false;
  14356. // Matches the IPv6 iPAddress SAN.
  14357. san_matched = ctx.check_hostname("2001:db8::1");
  14358. // A different IPv6 address must not match.
  14359. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14360. // "::1" lives only in the CN, so it must not be accepted.
  14361. cn_ipv6_matched = ctx.check_hostname("::1");
  14362. return true; // Accept for the purpose of this test
  14363. });
  14364. cli.Get("/test");
  14365. ASSERT_TRUE(verify_callback_called)
  14366. << "Verify callback should have been called";
  14367. EXPECT_TRUE(san_matched)
  14368. << "verify_hostname should match an IPv6 iPAddress SAN";
  14369. EXPECT_FALSE(wrong_ipv6_matched)
  14370. << "verify_hostname should not match a non-matching IPv6 address";
  14371. EXPECT_FALSE(cn_ipv6_matched)
  14372. << "An IPv6 host must not be authenticated via the certificate CN";
  14373. }
  14374. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14375. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14376. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14377. using namespace httplib::tls;
  14378. // SANs: DNS:a.zz, IP:42.46.122.122
  14379. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14380. ASSERT_TRUE(svr.is_valid());
  14381. svr.Get("/test", [](const Request &, Response &res) {
  14382. res.set_content("ok", "text/plain");
  14383. });
  14384. auto port = svr.bind_to_any_port(HOST);
  14385. thread t([&]() { svr.listen_after_bind(); });
  14386. auto se = detail::scope_exit([&] {
  14387. svr.stop();
  14388. t.join();
  14389. });
  14390. svr.wait_until_ready();
  14391. bool verify_callback_called = false;
  14392. bool dns_san_matched = false;
  14393. bool ip_san_matched = false;
  14394. bool ip_matched_via_dns_san = true;
  14395. bool dns_matched_via_ip_san = true;
  14396. bool cn_matched_next_to_dns_san = true;
  14397. SSLClient cli(HOST, port);
  14398. cli.enable_server_certificate_verification(true);
  14399. cli.set_ca_cert_path(CA_CERT_FILE);
  14400. cli.set_connection_timeout(5);
  14401. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14402. verify_callback_called = true;
  14403. if (!ctx.cert) return false;
  14404. dns_san_matched = ctx.check_hostname("a.zz");
  14405. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14406. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14407. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14408. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14409. return true; // Accept for the purpose of this test
  14410. });
  14411. cli.Get("/test");
  14412. ASSERT_TRUE(verify_callback_called)
  14413. << "Verify callback should have been called";
  14414. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14415. EXPECT_TRUE(ip_san_matched)
  14416. << "verify_hostname should match an iPAddress SAN";
  14417. EXPECT_FALSE(ip_matched_via_dns_san)
  14418. << "An IP host must not be authenticated via a dNSName SAN";
  14419. EXPECT_FALSE(dns_matched_via_ip_san)
  14420. << "A DNS host must not be authenticated via an iPAddress SAN";
  14421. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14422. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14423. }
  14424. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14425. // "www.*.example.test" names one host and not every host under example.test.
  14426. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14427. using namespace httplib::tls;
  14428. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14429. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. svr.Get("/test", [](const Request &, Response &res) {
  14432. res.set_content("ok", "text/plain");
  14433. });
  14434. auto port = svr.bind_to_any_port(HOST);
  14435. thread t([&]() { svr.listen_after_bind(); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. });
  14440. svr.wait_until_ready();
  14441. bool verify_callback_called = false;
  14442. bool leftmost_wildcard_matched = false;
  14443. bool wildcard_spanned_labels = true;
  14444. bool inner_wildcard_matched = true;
  14445. SSLClient cli(HOST, port);
  14446. cli.enable_server_certificate_verification(true);
  14447. cli.set_ca_cert_path(CA_CERT_FILE);
  14448. cli.set_connection_timeout(5);
  14449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14450. verify_callback_called = true;
  14451. if (!ctx.cert) return false;
  14452. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14453. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14454. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14455. return true; // Accept for the purpose of this test
  14456. });
  14457. cli.Get("/test");
  14458. ASSERT_TRUE(verify_callback_called)
  14459. << "Verify callback should have been called";
  14460. EXPECT_TRUE(leftmost_wildcard_matched)
  14461. << "A leftmost wildcard should match a single label";
  14462. EXPECT_FALSE(wildcard_spanned_labels)
  14463. << "A wildcard label must not match more than one label";
  14464. EXPECT_FALSE(inner_wildcard_matched)
  14465. << "A wildcard outside the leftmost label must not be honoured";
  14466. }
  14467. // sans() must report each SAN entry under its own type.
  14468. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14469. using namespace httplib::tls;
  14470. // SANs: DNS:a.zz, IP:42.46.122.122
  14471. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14472. ASSERT_TRUE(svr.is_valid());
  14473. svr.Get("/test", [](const Request &, Response &res) {
  14474. res.set_content("ok", "text/plain");
  14475. });
  14476. auto port = svr.bind_to_any_port(HOST);
  14477. thread t([&]() { svr.listen_after_bind(); });
  14478. auto se = detail::scope_exit([&] {
  14479. svr.stop();
  14480. t.join();
  14481. });
  14482. svr.wait_until_ready();
  14483. bool verify_callback_called = false;
  14484. std::vector<SanEntry> sans;
  14485. SSLClient cli(HOST, port);
  14486. cli.enable_server_certificate_verification(true);
  14487. cli.set_ca_cert_path(CA_CERT_FILE);
  14488. cli.set_connection_timeout(5);
  14489. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14490. verify_callback_called = true;
  14491. if (!ctx.cert) return false;
  14492. sans = ctx.sans();
  14493. return true; // Accept for the purpose of this test
  14494. });
  14495. cli.Get("/test");
  14496. ASSERT_TRUE(verify_callback_called)
  14497. << "Verify callback should have been called";
  14498. auto has_san = [&](SanType type, const std::string &value) {
  14499. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14500. return san.type == type && san.value == value;
  14501. });
  14502. };
  14503. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14504. << "sans() should report the dNSName SAN";
  14505. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14506. << "sans() should report the iPAddress SAN";
  14507. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14508. << "sans() must not report the dNSName SAN as an address";
  14509. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14510. << "sans() must not report the iPAddress SAN as a DNS name";
  14511. }
  14512. #endif
  14513. // mbedTLS-specific callback constructor test
  14514. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14515. #ifdef CPPHTTPLIB_SSL_ENABLED
  14516. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14518. ASSERT_TRUE(svr.is_valid());
  14519. // Set up a handler to verify client certificate is present
  14520. bool client_cert_verified = false;
  14521. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14522. // Verify that client certificate was provided
  14523. client_cert_verified = true;
  14524. res.set_content("success", "text/plain");
  14525. });
  14526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14527. auto se = detail::scope_exit([&] {
  14528. svr.stop();
  14529. t.join();
  14530. ASSERT_FALSE(svr.is_running());
  14531. });
  14532. svr.wait_until_ready();
  14533. // Client with certificate
  14534. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14535. cli.enable_server_certificate_verification(false);
  14536. cli.set_connection_timeout(30);
  14537. auto res = cli.Get("/test");
  14538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14539. ASSERT_EQ(StatusCode::OK_200, res->status);
  14540. ASSERT_TRUE(client_cert_verified);
  14541. EXPECT_EQ("success", res->body);
  14542. }
  14543. #endif
  14544. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14545. // backends
  14546. #ifdef CPPHTTPLIB_SSL_ENABLED
  14547. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14548. using namespace httplib::tls;
  14549. // Test that when client CA cert file is provided,
  14550. // the server properly requests and validates client certificates
  14551. // Create a server with client authentication
  14552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. bool handler_called = false;
  14555. svr.Get("/test", [&](const Request &req, Response &res) {
  14556. handler_called = true;
  14557. // Verify that a client certificate was provided
  14558. auto cert = req.peer_cert();
  14559. ASSERT_TRUE(static_cast<bool>(cert));
  14560. // Get the issuer name
  14561. std::string issuer_str = cert.issuer_name();
  14562. ASSERT_FALSE(issuer_str.empty());
  14563. // The client certificate should be issued by our test CA
  14564. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14565. res.set_content("authenticated", "text/plain");
  14566. });
  14567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14568. auto se = detail::scope_exit([&] {
  14569. svr.stop();
  14570. t.join();
  14571. ASSERT_FALSE(svr.is_running());
  14572. });
  14573. svr.wait_until_ready();
  14574. // Connect with a client certificate issued by the CA
  14575. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14576. cli.enable_server_certificate_verification(false);
  14577. cli.set_connection_timeout(30);
  14578. auto res = cli.Get("/test");
  14579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14580. ASSERT_EQ(StatusCode::OK_200, res->status);
  14581. ASSERT_TRUE(handler_called);
  14582. EXPECT_EQ("authenticated", res->body);
  14583. }
  14584. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14585. using namespace httplib::tls;
  14586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14587. ASSERT_TRUE(svr.is_valid());
  14588. svr.Get("/test", [](const Request &, Response &res) {
  14589. res.set_content("ok", "text/plain");
  14590. });
  14591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14592. auto se = detail::scope_exit([&] {
  14593. svr.stop();
  14594. t.join();
  14595. });
  14596. svr.wait_until_ready();
  14597. SSLClient cli(HOST, PORT);
  14598. cli.enable_server_certificate_verification(false);
  14599. cli.set_connection_timeout(30);
  14600. bool cert_checked = false;
  14601. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14602. if (ctx.cert) {
  14603. auto sans = ctx.sans();
  14604. // Test certificate may or may not have SANs - just verify the API
  14605. // works If SANs exist, verify the types are valid
  14606. for (const auto &san : sans) {
  14607. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14608. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14609. san.type == SanType::OTHER);
  14610. EXPECT_FALSE(san.value.empty());
  14611. }
  14612. cert_checked = true;
  14613. }
  14614. return true;
  14615. });
  14616. auto res = cli.Get("/test");
  14617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14618. EXPECT_TRUE(cert_checked);
  14619. }
  14620. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14621. using namespace httplib::tls;
  14622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14623. ASSERT_TRUE(svr.is_valid());
  14624. svr.Get("/test", [](const Request &, Response &res) {
  14625. res.set_content("ok", "text/plain");
  14626. });
  14627. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14628. auto se = detail::scope_exit([&] {
  14629. svr.stop();
  14630. t.join();
  14631. });
  14632. svr.wait_until_ready();
  14633. SSLClient cli(HOST, PORT);
  14634. cli.enable_server_certificate_verification(false);
  14635. cli.set_connection_timeout(30);
  14636. bool validity_checked = false;
  14637. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14638. if (ctx.cert) {
  14639. time_t not_before = 0, not_after = 0;
  14640. bool result = ctx.validity(not_before, not_after);
  14641. EXPECT_TRUE(result);
  14642. // Verify that not_before < now < not_after for a valid cert
  14643. time_t now = time(nullptr);
  14644. EXPECT_LT(not_before, now);
  14645. EXPECT_GT(not_after, now);
  14646. validity_checked = true;
  14647. }
  14648. return true;
  14649. });
  14650. auto res = cli.Get("/test");
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. EXPECT_TRUE(validity_checked);
  14653. }
  14654. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14655. using namespace httplib::tls;
  14656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14657. ASSERT_TRUE(svr.is_valid());
  14658. svr.Get("/test", [](const Request &, Response &res) {
  14659. res.set_content("ok", "text/plain");
  14660. });
  14661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14662. auto se = detail::scope_exit([&] {
  14663. svr.stop();
  14664. t.join();
  14665. });
  14666. svr.wait_until_ready();
  14667. SSLClient cli(HOST, PORT);
  14668. cli.enable_server_certificate_verification(false);
  14669. cli.set_connection_timeout(30);
  14670. bool serial_checked = false;
  14671. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14672. if (ctx.cert) {
  14673. std::string serial = ctx.serial();
  14674. EXPECT_FALSE(serial.empty());
  14675. // Serial should be a hex string
  14676. for (char c : serial) {
  14677. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14678. (c >= 'a' && c <= 'f'));
  14679. }
  14680. serial_checked = true;
  14681. }
  14682. return true;
  14683. });
  14684. auto res = cli.Get("/test");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_TRUE(serial_checked);
  14687. }
  14688. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14689. // Test 1: Valid CA file - no error should be recorded
  14690. {
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14692. CLIENT_CA_CERT_FILE);
  14693. ASSERT_TRUE(svr.is_valid());
  14694. // With valid setup, last_ssl_error should be 0
  14695. EXPECT_EQ(0, svr.ssl_last_error());
  14696. }
  14697. // Test 2: Invalid CA file content
  14698. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14699. {
  14700. // Create a temporary file with completely invalid content
  14701. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14702. {
  14703. std::ofstream ofs(temp_invalid_ca);
  14704. ofs << "This is not a certificate file at all\n";
  14705. ofs << "Just plain text content\n";
  14706. }
  14707. // Create server with invalid CA file
  14708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14709. // Clean up temporary file
  14710. std::remove(temp_invalid_ca);
  14711. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14712. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14713. // Note: SSL_CTX_load_verify_locations typically fails first,
  14714. // but our error handling code path is still exercised
  14715. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14716. }
  14717. }
  14718. TEST(VerifyCallbackTest, VerifyContextFields) {
  14719. using namespace httplib::tls;
  14720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14721. ASSERT_TRUE(svr.is_valid());
  14722. svr.Get("/test", [](const Request &, Response &res) {
  14723. res.set_content("ok", "text/plain");
  14724. });
  14725. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14726. auto se = detail::scope_exit([&] {
  14727. svr.stop();
  14728. t.join();
  14729. });
  14730. svr.wait_until_ready();
  14731. SSLClient cli(HOST, PORT);
  14732. cli.enable_server_certificate_verification(false);
  14733. cli.set_connection_timeout(30);
  14734. int callback_count = 0;
  14735. bool saw_leaf_cert = false;
  14736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14737. if (ctx.cert) {
  14738. callback_count++;
  14739. // We should see at least one certificate (the leaf)
  14740. std::string cn = ctx.subject_cn();
  14741. if (!cn.empty()) { saw_leaf_cert = true; }
  14742. // Verify context fields are populated
  14743. EXPECT_NE(ctx.session, nullptr);
  14744. EXPECT_GE(ctx.depth, 0);
  14745. }
  14746. return true;
  14747. });
  14748. auto res = cli.Get("/test");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. EXPECT_GT(callback_count, 0);
  14751. EXPECT_TRUE(saw_leaf_cert);
  14752. }
  14753. // A verifier that accepts runs alongside the built-in verification, and is the
  14754. // only check once that is turned off.
  14755. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14756. using namespace httplib::tls;
  14757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14758. ASSERT_TRUE(svr.is_valid());
  14759. svr.Get("/test", [](const Request &, Response &res) {
  14760. res.set_content("ok", "text/plain");
  14761. });
  14762. auto port = svr.bind_to_any_port(HOST);
  14763. thread t([&]() { svr.listen_after_bind(); });
  14764. auto se = detail::scope_exit([&] {
  14765. svr.stop();
  14766. t.join();
  14767. });
  14768. svr.wait_until_ready();
  14769. SSLClient cli(HOST, port);
  14770. cli.enable_server_hostname_verification(false);
  14771. auto calls = 0;
  14772. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14773. calls++;
  14774. return true;
  14775. });
  14776. // cert.pem is not trusted
  14777. auto res = cli.Get("/test");
  14778. ASSERT_FALSE(res);
  14779. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14780. EXPECT_GT(calls, 0);
  14781. cli.enable_server_certificate_verification(false);
  14782. res = cli.Get("/test");
  14783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14784. EXPECT_EQ("ok", res->body);
  14785. }
  14786. // A verifier belongs to the client that set it, not to the thread that set it.
  14787. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14788. using namespace httplib::tls;
  14789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14790. ASSERT_TRUE(svr.is_valid());
  14791. svr.Get("/test", [](const Request &, Response &res) {
  14792. res.set_content("ok", "text/plain");
  14793. });
  14794. auto port = svr.bind_to_any_port(HOST);
  14795. thread t([&]() { svr.listen_after_bind(); });
  14796. auto se = detail::scope_exit([&] {
  14797. svr.stop();
  14798. t.join();
  14799. });
  14800. svr.wait_until_ready();
  14801. auto rejecting_calls = 0;
  14802. SSLClient rejecting(HOST, port);
  14803. rejecting.enable_server_certificate_verification(false);
  14804. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14805. rejecting_calls++;
  14806. return false;
  14807. });
  14808. auto accepting_calls = 0;
  14809. SSLClient accepting(HOST, port);
  14810. accepting.enable_server_certificate_verification(false);
  14811. // Set on another thread than the requests below.
  14812. thread([&]() {
  14813. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14814. accepting_calls++;
  14815. return true;
  14816. });
  14817. }).join();
  14818. // Requested on another thread than the verifier was set on.
  14819. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14820. EXPECT_GT(rejecting_calls, 0);
  14821. auto res = accepting.Get("/test");
  14822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14823. EXPECT_GT(accepting_calls, 0);
  14824. }
  14825. // A verifier replaced while a handshake runs it lives until it returns.
  14826. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14827. using namespace httplib::tls;
  14828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14829. ASSERT_TRUE(svr.is_valid());
  14830. svr.Get("/test", [](const Request &, Response &res) {
  14831. res.set_content("ok", "text/plain");
  14832. });
  14833. auto port = svr.bind_to_any_port(HOST);
  14834. thread t([&]() { svr.listen_after_bind(); });
  14835. auto se = detail::scope_exit([&] {
  14836. svr.stop();
  14837. t.join();
  14838. });
  14839. svr.wait_until_ready();
  14840. SSLClient cli(HOST, port);
  14841. cli.enable_server_certificate_verification(false);
  14842. std::promise<void> entered;
  14843. std::promise<void> replaced;
  14844. auto replaced_future = replaced.get_future();
  14845. auto first_call = true;
  14846. // Long enough to live on the heap
  14847. std::string expected(64, 'v');
  14848. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14849. if (first_call) {
  14850. first_call = false;
  14851. entered.set_value();
  14852. replaced_future.wait();
  14853. }
  14854. return expected == std::string(64, 'v');
  14855. });
  14856. thread request([&]() {
  14857. auto res = cli.Get("/test");
  14858. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14859. });
  14860. entered.get_future().wait();
  14861. cli.set_server_certificate_verifier(
  14862. [](const VerifyContext &) { return true; });
  14863. replaced.set_value();
  14864. request.join();
  14865. }
  14866. // VerifyContext::session is the same handle the other tls:: functions take.
  14867. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14868. using namespace httplib::tls;
  14869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14870. ASSERT_TRUE(svr.is_valid());
  14871. svr.Get("/test", [](const Request &, Response &res) {
  14872. res.set_content("ok", "text/plain");
  14873. });
  14874. auto port = svr.bind_to_any_port(HOST);
  14875. thread t([&]() { svr.listen_after_bind(); });
  14876. auto se = detail::scope_exit([&] {
  14877. svr.stop();
  14878. t.join();
  14879. });
  14880. svr.wait_until_ready();
  14881. SSLClient cli(HOST, port);
  14882. cli.enable_server_certificate_verification(false);
  14883. session_t verifier_session = nullptr;
  14884. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14885. verifier_session = ctx.session;
  14886. return true;
  14887. });
  14888. session_t session_verifier_session = nullptr;
  14889. cli.set_session_verifier([&](session_t session) {
  14890. session_verifier_session = session;
  14891. return SSLVerifierResponse::NoDecisionMade;
  14892. });
  14893. auto res = cli.Get("/test");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. EXPECT_NE(nullptr, verifier_session);
  14896. EXPECT_EQ(session_verifier_session, verifier_session);
  14897. }
  14898. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14899. using httplib::tls::TlsError;
  14900. // Test that verify_error_to_string returns empty for success
  14901. std::string success_str = TlsError::verify_error_to_string(0);
  14902. EXPECT_TRUE(success_str.empty());
  14903. // Test that verify_error_to_string returns non-empty for error codes
  14904. // Using a common error code (certificate expired)
  14905. std::string error_str =
  14906. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14907. EXPECT_FALSE(error_str.empty());
  14908. }
  14909. TEST(SessionVerifierTest, CertificateAccepted) {
  14910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14911. ASSERT_TRUE(svr.is_valid());
  14912. svr.Get("/test", [](const Request &, Response &res) {
  14913. res.set_content("ok", "text/plain");
  14914. });
  14915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14916. auto se = detail::scope_exit([&] {
  14917. svr.stop();
  14918. t.join();
  14919. });
  14920. svr.wait_until_ready();
  14921. SSLClient cli(HOST, PORT);
  14922. cli.enable_server_certificate_verification(false);
  14923. cli.set_connection_timeout(30);
  14924. bool callback_called = false;
  14925. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14926. EXPECT_NE(session, nullptr);
  14927. callback_called = true;
  14928. return SSLVerifierResponse::CertificateAccepted;
  14929. });
  14930. auto res = cli.Get("/test");
  14931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14932. EXPECT_EQ(200, res->status);
  14933. EXPECT_TRUE(callback_called);
  14934. }
  14935. TEST(SessionVerifierTest, CertificateRejected) {
  14936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14937. ASSERT_TRUE(svr.is_valid());
  14938. svr.Get("/test", [](const Request &, Response &res) {
  14939. res.set_content("ok", "text/plain");
  14940. });
  14941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. t.join();
  14945. });
  14946. svr.wait_until_ready();
  14947. SSLClient cli(HOST, PORT);
  14948. cli.enable_server_certificate_verification(false);
  14949. cli.set_connection_timeout(30);
  14950. bool callback_called = false;
  14951. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14952. EXPECT_NE(session, nullptr);
  14953. callback_called = true;
  14954. return SSLVerifierResponse::CertificateRejected;
  14955. });
  14956. auto res = cli.Get("/test");
  14957. EXPECT_FALSE(res);
  14958. EXPECT_TRUE(callback_called);
  14959. }
  14960. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  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. // NoDecisionMade with verification disabled should succeed (no default check)
  14973. SSLClient cli(HOST, PORT);
  14974. cli.enable_server_certificate_verification(false);
  14975. cli.set_connection_timeout(30);
  14976. bool callback_called = false;
  14977. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14978. EXPECT_NE(session, nullptr);
  14979. callback_called = true;
  14980. return SSLVerifierResponse::NoDecisionMade;
  14981. });
  14982. auto res = cli.Get("/test");
  14983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14984. EXPECT_EQ(200, res->status);
  14985. EXPECT_TRUE(callback_called);
  14986. }
  14987. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14988. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14989. ASSERT_TRUE(svr.is_valid());
  14990. svr.Get("/test", [](const Request &, Response &res) {
  14991. res.set_content("ok", "text/plain");
  14992. });
  14993. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14994. auto se = detail::scope_exit([&] {
  14995. svr.stop();
  14996. t.join();
  14997. });
  14998. svr.wait_until_ready();
  14999. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15000. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15001. // so we only check that the request fails, not whether the callback was
  15002. // called.
  15003. SSLClient cli(HOST, PORT);
  15004. cli.enable_server_certificate_verification(true);
  15005. cli.set_connection_timeout(30);
  15006. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15007. EXPECT_NE(session, nullptr);
  15008. return SSLVerifierResponse::NoDecisionMade;
  15009. });
  15010. auto res = cli.Get("/test");
  15011. EXPECT_FALSE(res);
  15012. }
  15013. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15014. // Test SSL server using PemMemory constructor with client CA certificates
  15015. // Read PEM files
  15016. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15017. read_file(SERVER_CERT_FILE, server_cert_pem);
  15018. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15019. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15020. // Create SSLServer with PemMemory constructor including client CA
  15021. SSLServer::PemMemory server_pem = {
  15022. server_cert_pem.c_str(),
  15023. server_cert_pem.size(),
  15024. server_key_pem.c_str(),
  15025. server_key_pem.size(),
  15026. client_ca_pem.c_str(),
  15027. client_ca_pem.size(),
  15028. nullptr // no password for server key
  15029. };
  15030. SSLServer svr(server_pem);
  15031. ASSERT_TRUE(svr.is_valid());
  15032. // No SSL error should be recorded for valid setup
  15033. EXPECT_EQ(0, svr.ssl_last_error());
  15034. // Set up server endpoints
  15035. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15036. res.set_content("ok", "text/plain");
  15037. });
  15038. // Start server in a thread
  15039. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15040. svr.wait_until_ready();
  15041. // Connect with client certificate (using constructor with paths)
  15042. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15043. cli.enable_server_certificate_verification(false);
  15044. auto res = cli.Get("/test-pem-ca");
  15045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15046. EXPECT_EQ(200, res->status);
  15047. EXPECT_EQ("ok", res->body);
  15048. svr.stop();
  15049. server_thread.join();
  15050. }
  15051. #endif
  15052. #ifdef _WIN32
  15053. TEST(CleanupTest, WSACleanup) {
  15054. int ret = WSACleanup();
  15055. ASSERT_EQ(0, ret);
  15056. }
  15057. #endif
  15058. #ifndef CPPHTTPLIB_SSL_ENABLED
  15059. TEST(NoSSLSupport, SimpleInterface) {
  15060. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15061. }
  15062. #endif
  15063. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15064. TEST(InvalidScheme, SimpleInterface) {
  15065. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15066. }
  15067. #endif
  15068. TEST(NoScheme, SimpleInterface) {
  15069. Client cli("yahoo.com:80");
  15070. ASSERT_TRUE(cli.is_valid());
  15071. }
  15072. TEST(SendAPI, SimpleInterface_Online) {
  15073. Client cli("http://yahoo.com");
  15074. Request req;
  15075. req.method = "GET";
  15076. req.path = "/";
  15077. auto res = cli.send(req);
  15078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15079. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15080. }
  15081. TEST(SendAPI, WithParamsInRequest) {
  15082. Server svr;
  15083. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15084. EXPECT_TRUE(req.has_param("test"));
  15085. EXPECT_EQ("test_value", req.get_param_value("test"));
  15086. });
  15087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15088. auto se = detail::scope_exit([&] {
  15089. svr.stop();
  15090. t.join();
  15091. ASSERT_FALSE(svr.is_running());
  15092. });
  15093. svr.wait_until_ready();
  15094. Client cli(HOST, PORT);
  15095. {
  15096. Request req;
  15097. req.method = "GET";
  15098. req.path = "/";
  15099. req.params.emplace("test", "test_value");
  15100. auto res = cli.send(req);
  15101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15102. }
  15103. {
  15104. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15106. }
  15107. }
  15108. TEST(ClientImplMethods, GetSocketTest) {
  15109. httplib::Server svr;
  15110. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15111. res.status = StatusCode::OK_200;
  15112. });
  15113. auto port = svr.bind_to_any_port("127.0.0.1");
  15114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15115. auto se = detail::scope_exit([&] {
  15116. svr.stop();
  15117. thread.join();
  15118. ASSERT_FALSE(svr.is_running());
  15119. });
  15120. svr.wait_until_ready();
  15121. {
  15122. httplib::Client cli("127.0.0.1", port);
  15123. cli.set_keep_alive(true);
  15124. // Use the behavior of cpp-httplib of opening the connection
  15125. // only when the first request happens. If that changes,
  15126. // this test would be obsolete.
  15127. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15128. // This also implicitly tests the server. But other tests would fail much
  15129. // earlier than this one to be considered.
  15130. auto res = cli.Get("/");
  15131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15132. EXPECT_EQ(StatusCode::OK_200, res->status);
  15133. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15134. }
  15135. }
  15136. #ifdef CPPHTTPLIB_SSL_ENABLED
  15137. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15138. Client cli("http://yahoo.com");
  15139. auto res = cli.Get("/");
  15140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15141. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15142. cli.set_follow_location(true);
  15143. res = cli.Get("/");
  15144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15145. EXPECT_EQ(StatusCode::OK_200, res->status);
  15146. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15147. }
  15148. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15149. Client cli("https://yahoo.com");
  15150. auto res = cli.Get("/");
  15151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15152. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15153. cli.set_follow_location(true);
  15154. res = cli.Get("/");
  15155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15156. EXPECT_EQ(StatusCode::OK_200, res->status);
  15157. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15158. }
  15159. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15160. Client cli("https://yahoo.com");
  15161. auto res = cli.Get("/");
  15162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15163. ASSERT_FALSE(!res);
  15164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15165. ASSERT_FALSE(res == nullptr);
  15166. ASSERT_TRUE(res != nullptr);
  15167. EXPECT_EQ(Error::Success, res.error());
  15168. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15169. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15170. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15171. cli.set_follow_location(true);
  15172. res = cli.Get("/");
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. EXPECT_EQ(Error::Success, res.error());
  15175. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15176. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15177. EXPECT_EQ(StatusCode::OK_200, res->status);
  15178. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15179. }
  15180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15181. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15182. Client cli("https://cdnjs.cloudflare.com");
  15183. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15184. Headers{{"Accept-Encoding", "br"}});
  15185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15186. EXPECT_EQ(StatusCode::OK_200, res->status);
  15187. EXPECT_EQ(287630U, res->body.size());
  15188. EXPECT_EQ("application/javascript; charset=utf-8",
  15189. res->get_header_value("Content-Type"));
  15190. }
  15191. #endif
  15192. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15193. #undef REDIR_HOST // Silence compiler warning
  15194. #define REDIR_HOST "https://httpbingo.org"
  15195. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15196. Client cli(REDIR_HOST);
  15197. cli.set_follow_location(true);
  15198. auto res =
  15199. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15201. EXPECT_EQ(StatusCode::OK_200, res->status);
  15202. }
  15203. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15204. Client cli(REDIR_HOST);
  15205. cli.set_follow_location(true);
  15206. Params params;
  15207. params.emplace("url", "http://example.com");
  15208. params.emplace("status_code", "302");
  15209. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15211. EXPECT_EQ(StatusCode::OK_200, res->status);
  15212. }
  15213. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15214. Client cli(REDIR_HOST);
  15215. cli.set_follow_location(true);
  15216. Params params;
  15217. params.emplace("url", "http://example.com");
  15218. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15220. EXPECT_EQ(StatusCode::OK_200, res->status);
  15221. }
  15222. TEST(HttpToHttpsRedirectTest, CertFile) {
  15223. auto ssl_port = PORT + 1;
  15224. Server svr;
  15225. ASSERT_TRUE(svr.is_valid());
  15226. svr.Get("/index", [&](const Request &, Response &res) {
  15227. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15228. "/index");
  15229. svr.stop();
  15230. });
  15231. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15232. ASSERT_TRUE(ssl_svr.is_valid());
  15233. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15234. res.set_content("test", "text/plain");
  15235. ssl_svr.stop();
  15236. });
  15237. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15238. thread t2 =
  15239. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15240. auto se = detail::scope_exit([&] {
  15241. t2.join();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. ssl_svr.wait_until_ready();
  15247. Client cli("127.0.0.1", PORT);
  15248. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15249. cli.enable_server_certificate_verification(true);
  15250. cli.set_follow_location(true);
  15251. cli.set_connection_timeout(30);
  15252. auto res = cli.Get("/index");
  15253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15254. ASSERT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. TEST(SSLClientRedirectTest, CertFile) {
  15257. auto ssl_port = PORT + 1;
  15258. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15259. ASSERT_TRUE(ssl_svr1.is_valid());
  15260. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15261. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15262. "/index");
  15263. ssl_svr1.stop();
  15264. });
  15265. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15266. ASSERT_TRUE(ssl_svr2.is_valid());
  15267. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15268. res.set_content("test", "text/plain");
  15269. ssl_svr2.stop();
  15270. });
  15271. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15272. thread t2 =
  15273. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15274. auto se = detail::scope_exit([&] {
  15275. t2.join();
  15276. t.join();
  15277. ASSERT_FALSE(ssl_svr1.is_running());
  15278. });
  15279. ssl_svr1.wait_until_ready();
  15280. ssl_svr2.wait_until_ready();
  15281. SSLClient cli("127.0.0.1", PORT);
  15282. std::string cert;
  15283. read_file(SERVER_CERT2_FILE, cert);
  15284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15285. cli.enable_server_certificate_verification(true);
  15286. cli.set_follow_location(true);
  15287. cli.set_connection_timeout(30);
  15288. auto res = cli.Get("/index");
  15289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15290. ASSERT_EQ(StatusCode::OK_200, res->status);
  15291. }
  15292. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15293. // another port, so the client follows it with a new client.
  15294. static Result GetThroughTlsRedirectToDifferentPort(
  15295. const std::function<void(SSLClient &)> &setup,
  15296. const char *target_cert = SERVER_CERT2_FILE,
  15297. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15298. auto ssl_port = PORT + 1;
  15299. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15300. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15301. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15302. "/index");
  15303. });
  15304. SSLServer ssl_svr2(target_cert, target_key);
  15305. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15306. res.set_content("test", "text/plain");
  15307. });
  15308. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15309. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15310. auto se = detail::scope_exit([&] {
  15311. ssl_svr2.stop();
  15312. ssl_svr1.stop();
  15313. t2.join();
  15314. t.join();
  15315. });
  15316. ssl_svr1.wait_until_ready();
  15317. ssl_svr2.wait_until_ready();
  15318. SSLClient cli("127.0.0.1", PORT);
  15319. cli.set_follow_location(true);
  15320. cli.set_connection_timeout(30);
  15321. setup(cli);
  15322. return cli.Get("/index");
  15323. }
  15324. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15325. auto calls = 0;
  15326. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15327. cli.enable_server_certificate_verification(false);
  15328. // Accept the first server only.
  15329. cli.set_session_verifier([&](tls::session_t) {
  15330. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15331. : SSLVerifierResponse::CertificateRejected;
  15332. });
  15333. });
  15334. ASSERT_FALSE(res);
  15335. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15336. EXPECT_EQ(2, calls);
  15337. }
  15338. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15339. std::string pinned;
  15340. auto res = GetThroughTlsRedirectToDifferentPort(
  15341. [&](SSLClient &cli) {
  15342. cli.enable_server_certificate_verification(false);
  15343. // Pin the first certificate seen.
  15344. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15345. if (pinned.empty()) { pinned = ctx.serial(); }
  15346. return ctx.serial() == pinned;
  15347. });
  15348. },
  15349. // A certificate other than the first server's.
  15350. SERVER_CERT_FILE);
  15351. EXPECT_FALSE(res);
  15352. EXPECT_FALSE(pinned.empty());
  15353. }
  15354. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15355. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15356. std::string cert;
  15357. read_file(SERVER_CERT2_FILE, cert);
  15358. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15359. });
  15360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15361. EXPECT_EQ(StatusCode::OK_200, res->status);
  15362. }
  15363. // The target's certificate is signed by the root CA, which the first server's
  15364. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15365. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15366. auto res = GetThroughTlsRedirectToDifferentPort(
  15367. [](SSLClient &cli) {
  15368. std::string root_ca, cert;
  15369. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15370. read_file(SERVER_CERT2_FILE, cert);
  15371. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15372. cli.load_ca_cert_store(cert.data(), cert.size());
  15373. cli.enable_server_hostname_verification(false);
  15374. },
  15375. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. EXPECT_EQ(StatusCode::OK_200, res->status);
  15378. }
  15379. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15380. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15381. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15382. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15383. auto res = GetThroughTlsRedirectToDifferentPort(
  15384. [](SSLClient &cli) {
  15385. std::string root_ca, cert;
  15386. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15387. read_file(SERVER_CERT2_FILE, cert);
  15388. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15389. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15390. cli.enable_server_hostname_verification(false);
  15391. },
  15392. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15393. ASSERT_FALSE(res);
  15394. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15395. }
  15396. #endif
  15397. #endif
  15398. #ifdef CPPHTTPLIB_SSL_ENABLED
  15399. // Test that set_ca_cert_store() skips system certs (consistent with
  15400. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15401. // should be trusted - system certs should NOT be loaded.
  15402. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15403. // Load a specific cert that is NOT a system CA cert
  15404. std::string cert;
  15405. read_file(SERVER_CERT2_FILE, cert);
  15406. SSLClient cli("google.com");
  15407. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15408. cli.enable_server_certificate_verification(true);
  15409. // This should FAIL because:
  15410. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15411. // 2. System certs should NOT be loaded when custom store is set
  15412. // If system certs WERE loaded, this would succeed
  15413. auto res = cli.Get("/");
  15414. ASSERT_FALSE(res);
  15415. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15416. }
  15417. // Same as above, but through the native store handle path. Regression test:
  15418. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15419. // merged system certs into the user-provided store.
  15420. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15421. std::string cert;
  15422. read_file(SERVER_CERT2_FILE, cert);
  15423. SSLClient cli("google.com");
  15424. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15425. cli.enable_server_certificate_verification(true);
  15426. auto res = cli.Get("/");
  15427. ASSERT_FALSE(res);
  15428. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15429. }
  15430. // A custom store set via the native handle must still verify a server whose
  15431. // cert it does contain.
  15432. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15433. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15434. ASSERT_TRUE(svr.is_valid());
  15435. svr.Get("/test", [&](const Request &, Response &res) {
  15436. res.set_content("test", "text/plain");
  15437. });
  15438. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. ASSERT_FALSE(svr.is_running());
  15443. });
  15444. svr.wait_until_ready();
  15445. SSLClient cli("127.0.0.1", PORT);
  15446. std::string cert;
  15447. read_file(SERVER_CERT2_FILE, cert);
  15448. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15449. cli.enable_server_certificate_verification(true);
  15450. cli.set_connection_timeout(30);
  15451. auto res = cli.Get("/test");
  15452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15453. ASSERT_EQ(StatusCode::OK_200, res->status);
  15454. }
  15455. // CA certs loaded through the universal Client must be transferred to the
  15456. // client created internally for following an HTTPS redirect. Regression test:
  15457. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15458. // the CA data for redirect transfer.
  15459. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15460. auto ssl_port = PORT + 1;
  15461. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15462. ASSERT_TRUE(ssl_svr1.is_valid());
  15463. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15464. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15465. "/index");
  15466. });
  15467. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15468. ASSERT_TRUE(ssl_svr2.is_valid());
  15469. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15470. res.set_content("test", "text/plain");
  15471. });
  15472. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15473. thread t2 =
  15474. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15475. auto se = detail::scope_exit([&] {
  15476. ssl_svr2.stop();
  15477. ssl_svr1.stop();
  15478. t2.join();
  15479. t.join();
  15480. ASSERT_FALSE(ssl_svr1.is_running());
  15481. });
  15482. ssl_svr1.wait_until_ready();
  15483. ssl_svr2.wait_until_ready();
  15484. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15485. std::string cert;
  15486. read_file(SERVER_CERT2_FILE, cert);
  15487. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15488. cli.enable_server_certificate_verification(true);
  15489. cli.set_follow_location(true);
  15490. cli.set_connection_timeout(30);
  15491. auto res = cli.Get("/index");
  15492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15493. ASSERT_EQ(StatusCode::OK_200, res->status);
  15494. }
  15495. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15496. // so a host signed by a system CA verifies even though a custom CA is set
  15497. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15498. std::string cert;
  15499. read_file(SERVER_CERT2_FILE, cert);
  15500. SSLClient cli("google.com");
  15501. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15502. cli.enable_system_ca(true);
  15503. cli.enable_server_certificate_verification(true);
  15504. auto res = cli.Get("/");
  15505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15506. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15507. }
  15508. // The custom CA remains effective when combined with the system CA
  15509. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15510. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15511. ASSERT_TRUE(svr.is_valid());
  15512. svr.Get("/test", [&](const Request &, Response &res) {
  15513. res.set_content("test", "text/plain");
  15514. });
  15515. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15516. auto se = detail::scope_exit([&] {
  15517. svr.stop();
  15518. t.join();
  15519. ASSERT_FALSE(svr.is_running());
  15520. });
  15521. svr.wait_until_ready();
  15522. SSLClient cli("127.0.0.1", PORT);
  15523. std::string cert;
  15524. read_file(SERVER_CERT2_FILE, cert);
  15525. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15526. cli.enable_system_ca(true);
  15527. cli.enable_server_certificate_verification(true);
  15528. cli.set_connection_timeout(30);
  15529. auto res = cli.Get("/test");
  15530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15531. ASSERT_EQ(StatusCode::OK_200, res->status);
  15532. }
  15533. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15534. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15535. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15536. static CFDictionaryRef
  15537. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15538. const SecTrustSettingsResult *result) {
  15539. auto constraint =
  15540. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15541. &kCFTypeDictionaryValueCallBacks);
  15542. if (policy) {
  15543. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15544. }
  15545. if (policy_string) {
  15546. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15547. kCFStringEncodingUTF8);
  15548. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15549. CFRelease(str);
  15550. }
  15551. if (result) {
  15552. auto number_value = static_cast<SInt32>(*result);
  15553. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15554. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15555. CFRelease(number);
  15556. }
  15557. return constraint;
  15558. }
  15559. static SecTrustSettingsResult
  15560. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15561. auto trust_settings =
  15562. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15563. for (auto constraint : constraints) {
  15564. CFArrayAppendValue(trust_settings, constraint);
  15565. CFRelease(constraint);
  15566. }
  15567. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15568. CFRelease(trust_settings);
  15569. return result;
  15570. }
  15571. // The system CA loader takes a Keychain certificate as a trusted root only
  15572. // when its Trust Settings say so for SSL, not merely because it has some.
  15573. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15574. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15575. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15576. const auto deny = kSecTrustSettingsResultDeny;
  15577. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15578. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15579. auto x509_policy = SecPolicyCreateBasicX509();
  15580. // "Always Trust", which stores no constraint at all
  15581. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15582. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15583. ssl_trust_settings_result(
  15584. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15585. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15586. ssl_trust_settings_result(
  15587. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15588. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15589. ssl_trust_settings_result(
  15590. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15591. // "Never Trust", for everything or for SSL
  15592. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15593. ssl_trust_settings_result(
  15594. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15595. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15596. ssl_trust_settings_result(
  15597. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15598. // Trusted for another policy, for one host, or not at all
  15599. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15600. ssl_trust_settings_result(
  15601. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15602. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15603. ssl_trust_settings_result({make_usage_constraint(
  15604. ssl_policy, "www.example.com", &trust_root)}));
  15605. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15606. ssl_trust_settings_result(
  15607. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15608. // The first constraint that applies to SSL decides
  15609. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15610. ssl_trust_settings_result(
  15611. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15612. make_usage_constraint(nullptr, nullptr, &deny)}));
  15613. CFRelease(x509_policy);
  15614. CFRelease(ssl_policy);
  15615. }
  15616. #endif
  15617. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15618. // skip chain verification entirely (only the certificate identity was
  15619. // checked), so a server presenting an untrusted certificate with a matching
  15620. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15621. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15622. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15623. ASSERT_TRUE(svr.is_valid());
  15624. svr.Get("/test", [&](const Request &, Response &res) {
  15625. res.set_content("test", "text/plain");
  15626. });
  15627. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. t.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. SSLClient cli("127.0.0.1", PORT);
  15635. std::string cert;
  15636. // A trusted CA that did not sign the server certificate. The server cert
  15637. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15638. // this connection.
  15639. read_file(CLIENT_CA_CERT_FILE, cert);
  15640. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15641. cli.enable_server_certificate_verification(true);
  15642. cli.set_connection_timeout(30);
  15643. auto res = cli.Get("/test");
  15644. ASSERT_FALSE(res);
  15645. }
  15646. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15647. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15648. // CA that failed to come through fails verification instead of trusting them.
  15649. // (wolfSSL does not list the system CAs it loaded.)
  15650. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15651. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15652. ASSERT_TRUE(svr.is_valid());
  15653. auto port = svr.bind_to_any_port("127.0.0.1");
  15654. ASSERT_LT(0, port);
  15655. thread t = thread([&] { svr.listen_after_bind(); });
  15656. auto se = detail::scope_exit([&] {
  15657. svr.stop();
  15658. t.join();
  15659. ASSERT_FALSE(svr.is_running());
  15660. });
  15661. svr.wait_until_ready();
  15662. // The CAs a client trusts once its first request has loaded them
  15663. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15664. Client cli("https://127.0.0.1:" + std::to_string(port));
  15665. setup(cli);
  15666. cli.Get("/");
  15667. return tls::get_ca_names(cli.tls_context()).size();
  15668. };
  15669. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15670. EXPECT_EQ(0u,
  15671. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15672. }
  15673. #endif
  15674. // A TLS setting changed between requests applies to the next one, not just to
  15675. // the next connection
  15676. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15678. ASSERT_TRUE(svr.is_valid());
  15679. svr.Get("/", [](const Request &req, Response &res) {
  15680. res.set_content(std::to_string(req.remote_port), "text/plain");
  15681. });
  15682. auto port = svr.bind_to_any_port("127.0.0.1");
  15683. ASSERT_LT(0, port);
  15684. thread t = thread([&] { svr.listen_after_bind(); });
  15685. auto se = detail::scope_exit([&] {
  15686. svr.stop();
  15687. t.join();
  15688. ASSERT_FALSE(svr.is_running());
  15689. });
  15690. svr.wait_until_ready();
  15691. SSLClient cli("127.0.0.1", port);
  15692. cli.set_keep_alive(true);
  15693. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15694. cli.enable_server_certificate_verification(false);
  15695. // The port the request went out from, so a new one means a new connection
  15696. auto client_port = [&] {
  15697. auto res = cli.Get("/");
  15698. return res ? res->body : std::string();
  15699. };
  15700. auto last = client_port();
  15701. ASSERT_FALSE(last.empty());
  15702. // Setting a value it already has keeps the connection
  15703. cli.enable_server_certificate_verification(false);
  15704. cli.enable_server_hostname_verification(true);
  15705. EXPECT_EQ(last, client_port());
  15706. cli.enable_server_certificate_verification(true);
  15707. auto res = cli.Get("/");
  15708. EXPECT_FALSE(res);
  15709. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15710. std::string ca;
  15711. read_file(SERVER_CERT2_FILE, ca);
  15712. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15713. last = client_port();
  15714. ASSERT_FALSE(last.empty());
  15715. std::vector<std::function<void()>> setters = {
  15716. [&] { cli.enable_server_hostname_verification(false); },
  15717. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15718. [&] {
  15719. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15720. },
  15721. [&] {
  15722. cli.set_server_certificate_verifier(
  15723. [](const tls::VerifyContext &) { return true; });
  15724. },
  15725. [&] {
  15726. cli.set_session_verifier(
  15727. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15728. },
  15729. };
  15730. for (const auto &setter : setters) {
  15731. setter();
  15732. auto next = client_port();
  15733. ASSERT_FALSE(next.empty());
  15734. EXPECT_NE(last, next);
  15735. last = next;
  15736. }
  15737. cli.set_session_verifier(
  15738. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15739. auto handle = cli.open_stream("GET", "/");
  15740. EXPECT_FALSE(handle.is_valid());
  15741. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15742. }
  15743. // A PEM given to create_ca_store() needs no NUL after it
  15744. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15745. std::string pem;
  15746. read_file(SERVER_CERT2_FILE, pem);
  15747. auto buf = pem + "X";
  15748. auto store = tls::create_ca_store(buf.data(), pem.size());
  15749. EXPECT_TRUE(store != nullptr);
  15750. SSLClient cli("localhost");
  15751. cli.set_ca_cert_store(store);
  15752. }
  15753. // enable_system_ca(false) prevents system CA loading entirely
  15754. TEST(SSLClientTest, DisableSystemCa_Online) {
  15755. SSLClient cli("google.com");
  15756. cli.enable_system_ca(false);
  15757. cli.enable_server_certificate_verification(true);
  15758. auto res = cli.Get("/");
  15759. ASSERT_FALSE(res);
  15760. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15761. // itself when the CA chain is empty
  15762. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15763. res.error() == Error::SSLConnection);
  15764. }
  15765. // The universal Client forwards enable_system_ca()
  15766. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15767. std::string cert;
  15768. read_file(SERVER_CERT2_FILE, cert);
  15769. Client cli("https://google.com");
  15770. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15771. cli.enable_system_ca(true);
  15772. cli.enable_server_certificate_verification(true);
  15773. auto res = cli.Get("/");
  15774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15775. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15776. }
  15777. // The system CA policy must carry over to the client created internally for
  15778. // following a cross-host HTTPS redirect
  15779. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15780. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15781. ASSERT_TRUE(svr.is_valid());
  15782. svr.Get("/index", [&](const Request &, Response &res) {
  15783. res.set_redirect("https://www.google.com/");
  15784. });
  15785. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15786. auto se = detail::scope_exit([&] {
  15787. svr.stop();
  15788. t.join();
  15789. ASSERT_FALSE(svr.is_running());
  15790. });
  15791. svr.wait_until_ready();
  15792. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15793. std::string cert;
  15794. read_file(SERVER_CERT2_FILE, cert);
  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. cli.set_follow_location(true);
  15799. cli.set_connection_timeout(30);
  15800. // Receiving any response proves the redirect client completed the TLS
  15801. // handshake with a system-CA-signed host
  15802. auto res = cli.Get("/index");
  15803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15804. }
  15805. TEST(MultipartFormDataTest, LargeData) {
  15806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15807. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15808. const ContentReader &content_reader) {
  15809. if (req.is_multipart_form_data()) {
  15810. std::vector<FormData> items;
  15811. content_reader(
  15812. [&](const FormData &file) {
  15813. items.push_back(file);
  15814. return true;
  15815. },
  15816. [&](const char *data, size_t data_length) {
  15817. items.back().content.append(data, data_length);
  15818. return true;
  15819. });
  15820. EXPECT_TRUE(std::string(items[0].name) == "document");
  15821. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15822. EXPECT_TRUE(items[0].filename == "2MB_data");
  15823. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15824. EXPECT_TRUE(items[1].name == "hello");
  15825. EXPECT_TRUE(items[1].content == "world");
  15826. EXPECT_TRUE(items[1].filename == "");
  15827. EXPECT_TRUE(items[1].content_type == "");
  15828. } else {
  15829. std::string body;
  15830. content_reader([&](const char *data, size_t data_length) {
  15831. body.append(data, data_length);
  15832. return true;
  15833. });
  15834. }
  15835. });
  15836. auto port = svr.bind_to_any_port(HOST);
  15837. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. ASSERT_FALSE(svr.is_running());
  15842. });
  15843. svr.wait_until_ready();
  15844. {
  15845. std::string data(1024 * 1024 * 2, '.');
  15846. std::stringstream buffer;
  15847. buffer << data;
  15848. SSLClient cli(HOST, port);
  15849. cli.enable_server_certificate_verification(false);
  15850. UploadFormDataItems items{
  15851. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15852. {"hello", "world", "", ""},
  15853. };
  15854. auto res = cli.Post("/post", items);
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. ASSERT_EQ(StatusCode::OK_200, res->status);
  15857. }
  15858. }
  15859. TEST(MultipartFormDataTest, DataProviderItems) {
  15860. std::random_device seed_gen;
  15861. std::mt19937 random(seed_gen());
  15862. std::string rand1;
  15863. rand1.resize(1000);
  15864. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15865. std::string rand2;
  15866. rand2.resize(3000);
  15867. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15869. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15870. const ContentReader &content_reader) {
  15871. ASSERT_FALSE(req.is_multipart_form_data());
  15872. std::string body;
  15873. content_reader([&](const char *data, size_t data_length) {
  15874. body.append(data, data_length);
  15875. return true;
  15876. });
  15877. EXPECT_EQ(body, "");
  15878. });
  15879. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15880. const ContentReader &content_reader) {
  15881. ASSERT_TRUE(req.is_multipart_form_data());
  15882. std::vector<FormData> items;
  15883. content_reader(
  15884. [&](const FormData &file) {
  15885. items.push_back(file);
  15886. return true;
  15887. },
  15888. [&](const char *data, size_t data_length) {
  15889. items.back().content.append(data, data_length);
  15890. return true;
  15891. });
  15892. ASSERT_TRUE(items.size() == 2);
  15893. EXPECT_EQ(std::string(items[0].name), "name1");
  15894. EXPECT_EQ(items[0].content, "Testing123");
  15895. EXPECT_EQ(items[0].filename, "filename1");
  15896. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15897. EXPECT_EQ(items[1].name, "name2");
  15898. EXPECT_EQ(items[1].content, "Testing456");
  15899. EXPECT_EQ(items[1].filename, "");
  15900. EXPECT_EQ(items[1].content_type, "");
  15901. });
  15902. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15903. const ContentReader &content_reader) {
  15904. ASSERT_TRUE(req.is_multipart_form_data());
  15905. std::vector<FormData> items;
  15906. content_reader(
  15907. [&](const FormData &file) {
  15908. items.push_back(file);
  15909. return true;
  15910. },
  15911. [&](const char *data, size_t data_length) {
  15912. items.back().content.append(data, data_length);
  15913. return true;
  15914. });
  15915. ASSERT_TRUE(items.size() == 2);
  15916. EXPECT_EQ(items[0].name, "name3");
  15917. EXPECT_EQ(items[0].content, rand1);
  15918. EXPECT_EQ(items[0].filename, "filename3");
  15919. EXPECT_EQ(items[0].content_type, "");
  15920. EXPECT_EQ(items[1].name, "name4");
  15921. EXPECT_EQ(items[1].content, rand2);
  15922. EXPECT_EQ(items[1].filename, "filename4");
  15923. EXPECT_EQ(items[1].content_type, "");
  15924. });
  15925. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15926. const ContentReader &content_reader) {
  15927. ASSERT_TRUE(req.is_multipart_form_data());
  15928. std::vector<FormData> items;
  15929. content_reader(
  15930. [&](const FormData &file) {
  15931. items.push_back(file);
  15932. return true;
  15933. },
  15934. [&](const char *data, size_t data_length) {
  15935. items.back().content.append(data, data_length);
  15936. return true;
  15937. });
  15938. ASSERT_TRUE(items.size() == 4);
  15939. EXPECT_EQ(std::string(items[0].name), "name1");
  15940. EXPECT_EQ(items[0].content, "Testing123");
  15941. EXPECT_EQ(items[0].filename, "filename1");
  15942. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15943. EXPECT_EQ(items[1].name, "name2");
  15944. EXPECT_EQ(items[1].content, "Testing456");
  15945. EXPECT_EQ(items[1].filename, "");
  15946. EXPECT_EQ(items[1].content_type, "");
  15947. EXPECT_EQ(items[2].name, "name3");
  15948. EXPECT_EQ(items[2].content, rand1);
  15949. EXPECT_EQ(items[2].filename, "filename3");
  15950. EXPECT_EQ(items[2].content_type, "");
  15951. EXPECT_EQ(items[3].name, "name4");
  15952. EXPECT_EQ(items[3].content, rand2);
  15953. EXPECT_EQ(items[3].filename, "filename4");
  15954. EXPECT_EQ(items[3].content_type, "");
  15955. });
  15956. auto port = svr.bind_to_any_port("localhost");
  15957. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15958. auto se = detail::scope_exit([&] {
  15959. svr.stop();
  15960. t.join();
  15961. ASSERT_FALSE(svr.is_running());
  15962. });
  15963. svr.wait_until_ready();
  15964. {
  15965. SSLClient cli("localhost", port);
  15966. cli.enable_server_certificate_verification(false);
  15967. UploadFormDataItems items{
  15968. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15969. {"name2", "Testing456", "", ""}, // not a file
  15970. };
  15971. {
  15972. auto res = cli.Post("/post-none", {}, {}, {});
  15973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15974. ASSERT_EQ(StatusCode::OK_200, res->status);
  15975. }
  15976. FormDataProviderItems providers;
  15977. {
  15978. auto res =
  15979. cli.Post("/post-items", {}, items, providers); // empty providers
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. ASSERT_EQ(StatusCode::OK_200, res->status);
  15982. }
  15983. providers.push_back({"name3",
  15984. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15985. // test the offset is given correctly at each step
  15986. if (!offset)
  15987. sink.os.write(rand1.data(), 30);
  15988. else if (offset == 30)
  15989. sink.os.write(rand1.data() + 30, 300);
  15990. else if (offset == 330)
  15991. sink.os.write(rand1.data() + 330, 670);
  15992. else if (offset == rand1.size())
  15993. sink.done();
  15994. return true;
  15995. },
  15996. "filename3",
  15997. {}});
  15998. providers.push_back({"name4",
  15999. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16000. // test the offset is given correctly at each step
  16001. if (!offset)
  16002. sink.os.write(rand2.data(), 2000);
  16003. else if (offset == 2000)
  16004. sink.os.write(rand2.data() + 2000, 1);
  16005. else if (offset == 2001)
  16006. sink.os.write(rand2.data() + 2001, 999);
  16007. else if (offset == rand2.size())
  16008. sink.done();
  16009. return true;
  16010. },
  16011. "filename4",
  16012. {}});
  16013. {
  16014. auto res = cli.Post("/post-providers", {}, {}, providers);
  16015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16016. ASSERT_EQ(StatusCode::OK_200, res->status);
  16017. }
  16018. {
  16019. auto res = cli.Post("/post-both", {}, items, providers);
  16020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16021. ASSERT_EQ(StatusCode::OK_200, res->status);
  16022. }
  16023. }
  16024. }
  16025. TEST(MultipartFormDataTest, BadHeader) {
  16026. Server svr;
  16027. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16028. res.set_content("ok", "text/plain");
  16029. });
  16030. thread t = thread([&] { svr.listen(HOST, PORT); });
  16031. auto se = detail::scope_exit([&] {
  16032. svr.stop();
  16033. t.join();
  16034. ASSERT_FALSE(svr.is_running());
  16035. });
  16036. svr.wait_until_ready();
  16037. const std::string body =
  16038. "This is the preamble. It is to be ignored, though it\r\n"
  16039. "is a handy place for composition agents to include an\r\n"
  16040. "explanatory note to non-MIME conformant readers.\r\n"
  16041. "\r\n"
  16042. "\r\n"
  16043. "--simple boundary\r\n"
  16044. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16045. ": BAD...\r\n"
  16046. "\r\n"
  16047. "value1\r\n"
  16048. "--simple boundary\r\n"
  16049. "Content-Disposition: form-data; name=\"field2\"; "
  16050. "filename=\"example.txt\"\r\n"
  16051. "\r\n"
  16052. "value2\r\n"
  16053. "--simple boundary--\r\n"
  16054. "This is the epilogue. It is also to be ignored.\r\n";
  16055. std::string content_type =
  16056. R"(multipart/form-data; boundary="simple boundary")";
  16057. Client cli(HOST, PORT);
  16058. auto res = cli.Post("/post", body, content_type.c_str());
  16059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16061. }
  16062. TEST(MultipartFormDataTest, WithPreamble) {
  16063. Server svr;
  16064. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16065. res.set_content("ok", "text/plain");
  16066. });
  16067. thread t = thread([&] { svr.listen(HOST, PORT); });
  16068. auto se = detail::scope_exit([&] {
  16069. svr.stop();
  16070. t.join();
  16071. ASSERT_FALSE(svr.is_running());
  16072. });
  16073. svr.wait_until_ready();
  16074. const std::string body =
  16075. "This is the preamble. It is to be ignored, though it\r\n"
  16076. "is a handy place for composition agents to include an\r\n"
  16077. "explanatory note to non-MIME conformant readers.\r\n"
  16078. "\r\n"
  16079. "\r\n"
  16080. "--simple boundary\r\n"
  16081. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16082. "\r\n"
  16083. "value1\r\n"
  16084. "--simple boundary\r\n"
  16085. "Content-Disposition: form-data; name=\"field2\"; "
  16086. "filename=\"example.txt\"\r\n"
  16087. "\r\n"
  16088. "value2\r\n"
  16089. "--simple boundary--\r\n"
  16090. "This is the epilogue. It is also to be ignored.\r\n";
  16091. std::string content_type =
  16092. R"(multipart/form-data; boundary="simple boundary")";
  16093. Client cli(HOST, PORT);
  16094. auto res = cli.Post("/post", body, content_type.c_str());
  16095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16096. EXPECT_EQ(StatusCode::OK_200, res->status);
  16097. }
  16098. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16100. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16101. const ContentReader &content_reader) {
  16102. if (req.is_multipart_form_data()) {
  16103. std::vector<FormData> items;
  16104. content_reader(
  16105. [&](const FormData &file) {
  16106. items.push_back(file);
  16107. return true;
  16108. },
  16109. [&](const char *data, size_t data_length) {
  16110. items.back().content.append(data, data_length);
  16111. return true;
  16112. });
  16113. EXPECT_TRUE(std::string(items[0].name) == "document");
  16114. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16115. EXPECT_TRUE(items[0].filename == "2MB_data");
  16116. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16117. EXPECT_TRUE(items[1].name == "hello");
  16118. EXPECT_TRUE(items[1].content == "world");
  16119. EXPECT_TRUE(items[1].filename == "");
  16120. EXPECT_TRUE(items[1].content_type == "");
  16121. } else {
  16122. std::string body;
  16123. content_reader([&](const char *data, size_t data_length) {
  16124. body.append(data, data_length);
  16125. return true;
  16126. });
  16127. }
  16128. });
  16129. auto port = svr.bind_to_any_port("localhost");
  16130. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16131. auto se = detail::scope_exit([&] {
  16132. svr.stop();
  16133. t.join();
  16134. ASSERT_FALSE(svr.is_running());
  16135. });
  16136. svr.wait_until_ready();
  16137. {
  16138. std::string data(1024 * 1024 * 2, '.');
  16139. std::stringstream buffer;
  16140. buffer << data;
  16141. SSLClient cli("localhost", port);
  16142. cli.enable_server_certificate_verification(false);
  16143. UploadFormDataItems items{
  16144. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16145. {"hello", "world", "", ""},
  16146. };
  16147. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. ASSERT_EQ(StatusCode::OK_200, res->status);
  16150. }
  16151. }
  16152. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16153. std::string data(1024 * 1024 * 2, '&');
  16154. std::stringstream buffer;
  16155. buffer << data;
  16156. Client cli("https://localhost:8080");
  16157. UploadFormDataItems items{
  16158. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16159. {"hello", "world", "", ""},
  16160. };
  16161. for (const char &c : " \t\r\n") {
  16162. auto res =
  16163. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16164. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16165. ASSERT_FALSE(res);
  16166. }
  16167. }
  16168. TEST(MultipartFormDataTest, PutFormData) {
  16169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16170. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16171. const ContentReader &content_reader) {
  16172. if (req.is_multipart_form_data()) {
  16173. std::vector<FormData> items;
  16174. content_reader(
  16175. [&](const FormData &file) {
  16176. items.push_back(file);
  16177. return true;
  16178. },
  16179. [&](const char *data, size_t data_length) {
  16180. items.back().content.append(data, data_length);
  16181. return true;
  16182. });
  16183. EXPECT_TRUE(std::string(items[0].name) == "document");
  16184. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16185. EXPECT_TRUE(items[0].filename == "2MB_data");
  16186. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16187. EXPECT_TRUE(items[1].name == "hello");
  16188. EXPECT_TRUE(items[1].content == "world");
  16189. EXPECT_TRUE(items[1].filename == "");
  16190. EXPECT_TRUE(items[1].content_type == "");
  16191. } else {
  16192. std::string body;
  16193. content_reader([&](const char *data, size_t data_length) {
  16194. body.append(data, data_length);
  16195. return true;
  16196. });
  16197. }
  16198. });
  16199. auto port = svr.bind_to_any_port("localhost");
  16200. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16201. auto se = detail::scope_exit([&] {
  16202. svr.stop();
  16203. t.join();
  16204. ASSERT_FALSE(svr.is_running());
  16205. });
  16206. svr.wait_until_ready();
  16207. {
  16208. std::string data(1024 * 1024 * 2, '&');
  16209. std::stringstream buffer;
  16210. buffer << data;
  16211. SSLClient cli("localhost", port);
  16212. cli.enable_server_certificate_verification(false);
  16213. UploadFormDataItems items{
  16214. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16215. {"hello", "world", "", ""},
  16216. };
  16217. auto res = cli.Put("/put", items);
  16218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16219. ASSERT_EQ(StatusCode::OK_200, res->status);
  16220. }
  16221. }
  16222. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16224. svr.Put("/put_customboundary",
  16225. [&](const Request &req, const Response & /*res*/,
  16226. const ContentReader &content_reader) {
  16227. if (req.is_multipart_form_data()) {
  16228. std::vector<FormData> items;
  16229. content_reader(
  16230. [&](const FormData &file) {
  16231. items.push_back(file);
  16232. return true;
  16233. },
  16234. [&](const char *data, size_t data_length) {
  16235. items.back().content.append(data, data_length);
  16236. return true;
  16237. });
  16238. EXPECT_TRUE(std::string(items[0].name) == "document");
  16239. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16240. EXPECT_TRUE(items[0].filename == "2MB_data");
  16241. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16242. EXPECT_TRUE(items[1].name == "hello");
  16243. EXPECT_TRUE(items[1].content == "world");
  16244. EXPECT_TRUE(items[1].filename == "");
  16245. EXPECT_TRUE(items[1].content_type == "");
  16246. } else {
  16247. std::string body;
  16248. content_reader([&](const char *data, size_t data_length) {
  16249. body.append(data, data_length);
  16250. return true;
  16251. });
  16252. }
  16253. });
  16254. auto port = svr.bind_to_any_port("localhost");
  16255. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16256. auto se = detail::scope_exit([&] {
  16257. svr.stop();
  16258. t.join();
  16259. ASSERT_FALSE(svr.is_running());
  16260. });
  16261. svr.wait_until_ready();
  16262. {
  16263. std::string data(1024 * 1024 * 2, '&');
  16264. std::stringstream buffer;
  16265. buffer << data;
  16266. SSLClient cli("localhost", port);
  16267. cli.enable_server_certificate_verification(false);
  16268. UploadFormDataItems items{
  16269. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16270. {"hello", "world", "", ""},
  16271. };
  16272. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16274. ASSERT_EQ(StatusCode::OK_200, res->status);
  16275. }
  16276. }
  16277. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16278. std::string data(1024 * 1024 * 2, '&');
  16279. std::stringstream buffer;
  16280. buffer << data;
  16281. Client cli("https://localhost:8080");
  16282. cli.enable_server_certificate_verification(false);
  16283. UploadFormDataItems items{
  16284. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16285. {"hello", "world", "", ""},
  16286. };
  16287. for (const char &c : " \t\r\n") {
  16288. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16289. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16290. ASSERT_FALSE(res);
  16291. }
  16292. }
  16293. TEST(MultipartFormDataTest, AlternateFilename) {
  16294. auto handled = false;
  16295. Server svr;
  16296. svr.Post("/test", [&](const Request &req, Response &res) {
  16297. ASSERT_EQ(2u, req.form.files.size());
  16298. ASSERT_EQ(1u, req.form.fields.size());
  16299. // Test files
  16300. const auto &file1 = req.form.get_file("file1");
  16301. ASSERT_EQ("file1", file1.name);
  16302. ASSERT_EQ("A.txt", file1.filename);
  16303. ASSERT_EQ("text/plain", file1.content_type);
  16304. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16305. const auto &file2 = req.form.get_file("file2");
  16306. ASSERT_EQ("file2", file2.name);
  16307. ASSERT_EQ("a.html", file2.filename);
  16308. ASSERT_EQ("text/html", file2.content_type);
  16309. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16310. file2.content);
  16311. // Test text field
  16312. const auto &text = req.form.get_field("text");
  16313. ASSERT_EQ("text default", text);
  16314. res.set_content("ok", "text/plain");
  16315. handled = true;
  16316. });
  16317. thread t = thread([&] { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. ASSERT_TRUE(handled);
  16323. });
  16324. svr.wait_until_ready();
  16325. auto req = "POST /test HTTP/1.1\r\n"
  16326. "Host: localhost\r\n"
  16327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16328. "Content-Length: 399\r\n"
  16329. "\r\n"
  16330. "----------\r\n"
  16331. "Content-Disposition: form-data; name=\"text\"\r\n"
  16332. "\r\n"
  16333. "text default\r\n"
  16334. "----------\r\n"
  16335. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16336. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16337. "Content-Type: text/plain\r\n"
  16338. "\r\n"
  16339. "Content of a.txt.\r\n"
  16340. "\r\n"
  16341. "----------\r\n"
  16342. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16343. "\"a.html\"\r\n"
  16344. "Content-Type: text/html\r\n"
  16345. "\r\n"
  16346. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16347. "\r\n"
  16348. "------------\r\n";
  16349. ASSERT_TRUE(send_request(1, req));
  16350. }
  16351. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16352. auto handled = false;
  16353. Server svr;
  16354. svr.Post("/test", [&](const Request &req, Response &res) {
  16355. // Case-insensitive "utf-8''" prefix with a long value
  16356. const auto &file = req.form.get_file("file1");
  16357. ASSERT_EQ("file1", file.name);
  16358. // 8000 chars exercises both the Content-Disposition parser and the
  16359. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16360. // Prior to the fix, std::regex_match on this header would cause O(N)
  16361. // stack recursion in libstdc++, leading to SIGSEGV.
  16362. std::string expected_filename(8000, 'A');
  16363. ASSERT_EQ(expected_filename, file.filename);
  16364. res.set_content("ok", "text/plain");
  16365. handled = true;
  16366. });
  16367. thread t = thread([&] { svr.listen(HOST, PORT); });
  16368. auto se = detail::scope_exit([&] {
  16369. svr.stop();
  16370. t.join();
  16371. ASSERT_FALSE(svr.is_running());
  16372. ASSERT_TRUE(handled);
  16373. });
  16374. svr.wait_until_ready();
  16375. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16376. // Regression test for GHSA-qq6v-r583-3h69
  16377. std::string long_filename(8000, 'A');
  16378. std::string body = "----------\r\n"
  16379. "Content-Disposition: form-data; name=\"file1\"; "
  16380. "filename*=\"Utf-8''" +
  16381. long_filename +
  16382. "\"\r\n"
  16383. "\r\n"
  16384. "hello\r\n"
  16385. "------------\r\n";
  16386. auto req = "POST /test HTTP/1.1\r\n"
  16387. "Host: localhost\r\n"
  16388. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16389. "Content-Length: " +
  16390. std::to_string(body.size()) + "\r\n\r\n" + body;
  16391. ASSERT_TRUE(send_request(1, req));
  16392. }
  16393. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16394. auto handled = false;
  16395. Server svr;
  16396. svr.Post("/test", [&](const Request &req, Response &) {
  16397. ASSERT_EQ(2u, req.form.fields.size());
  16398. const auto &text1 = req.form.get_field("text1");
  16399. ASSERT_EQ("text1", text1);
  16400. const auto &text2 = req.form.get_field("text2");
  16401. ASSERT_EQ("text2", text2);
  16402. handled = true;
  16403. });
  16404. thread t = thread([&] { svr.listen(HOST, PORT); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. ASSERT_TRUE(handled);
  16410. });
  16411. svr.wait_until_ready();
  16412. auto req = "POST /test HTTP/1.1\r\n"
  16413. "Host: localhost\r\n"
  16414. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16415. "Content-Length: 146\r\n"
  16416. "\r\n----------\r\n"
  16417. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16418. "\r\n"
  16419. "text1"
  16420. "\r\n----------\r\n"
  16421. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16422. "\r\n"
  16423. "text2"
  16424. "\r\n------------";
  16425. std::string response;
  16426. ASSERT_TRUE(send_request(1, req, &response));
  16427. ASSERT_EQ("200", response.substr(9, 3));
  16428. }
  16429. TEST(MultipartFormDataTest, ContentLength) {
  16430. auto handled = false;
  16431. Server svr;
  16432. svr.Post("/test", [&](const Request &req, Response &) {
  16433. ASSERT_EQ(2u, req.form.fields.size());
  16434. const auto &text1 = req.form.get_field("text1");
  16435. ASSERT_EQ("text1", text1);
  16436. const auto &text2 = req.form.get_field("text2");
  16437. ASSERT_EQ("text2", text2);
  16438. handled = true;
  16439. });
  16440. thread t = thread([&] { svr.listen(HOST, PORT); });
  16441. auto se = detail::scope_exit([&] {
  16442. svr.stop();
  16443. t.join();
  16444. ASSERT_FALSE(svr.is_running());
  16445. ASSERT_TRUE(handled);
  16446. });
  16447. svr.wait_until_ready();
  16448. auto req = "POST /test HTTP/1.1\r\n"
  16449. "Host: localhost\r\n"
  16450. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16451. "Content-Length: 167\r\n"
  16452. "\r\n----------\r\n"
  16453. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16454. "Content-Length: 5\r\n"
  16455. "\r\n"
  16456. "text1"
  16457. "\r\n----------\r\n"
  16458. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16459. "\r\n"
  16460. "text2"
  16461. "\r\n------------\r\n";
  16462. std::string response;
  16463. ASSERT_TRUE(send_request(1, req, &response));
  16464. ASSERT_EQ("200", response.substr(9, 3));
  16465. }
  16466. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16467. auto handled = false;
  16468. Server svr;
  16469. svr.Post("/test", [&](const Request &req, Response &) {
  16470. ASSERT_EQ(2u, req.form.fields.size());
  16471. const auto &text1 = req.form.get_field("text1");
  16472. ASSERT_EQ("text1", text1);
  16473. // TODO: Add header access for text fields if needed
  16474. const auto &text2 = req.form.get_field("text2");
  16475. ASSERT_EQ("text2", text2);
  16476. // TODO: Header access for text fields needs to be implemented
  16477. // auto &headers = it->second.headers;
  16478. // ASSERT_EQ(3U, headers.size());
  16479. // auto custom_header = headers.find("x-whatever");
  16480. // ASSERT_TRUE(custom_header != headers.end());
  16481. // ASSERT_NE("customvalue", custom_header->second);
  16482. // ASSERT_EQ("CustomValue", custom_header->second);
  16483. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16484. handled = true;
  16485. });
  16486. thread t = thread([&] { svr.listen(HOST, PORT); });
  16487. auto se = detail::scope_exit([&] {
  16488. svr.stop();
  16489. t.join();
  16490. ASSERT_FALSE(svr.is_running());
  16491. ASSERT_TRUE(handled);
  16492. });
  16493. svr.wait_until_ready();
  16494. auto req = "POST /test HTTP/1.1\r\n"
  16495. "Host: localhost\r\n"
  16496. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16497. "Content-Length: 232\r\n"
  16498. "\r\n----------\r\n"
  16499. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16500. "Content-Length: 5\r\n"
  16501. "X-Test: 1\r\n"
  16502. "\r\n"
  16503. "text1"
  16504. "\r\n----------\r\n"
  16505. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16506. "Content-Type: text/plain\r\n"
  16507. "X-Whatever: CustomValue\r\n"
  16508. "\r\n"
  16509. "text2"
  16510. "\r\n------------\r\n"
  16511. "That should be disregarded. Not even read";
  16512. std::string response;
  16513. ASSERT_TRUE(send_request(1, req, &response));
  16514. ASSERT_EQ("200", response.substr(9, 3));
  16515. }
  16516. TEST(MultipartFormDataTest, LargeHeader) {
  16517. auto handled = false;
  16518. Server svr;
  16519. svr.Post("/test", [&](const Request &req, Response &) {
  16520. ASSERT_EQ(1u, req.form.fields.size());
  16521. const auto &text = req.form.get_field("name1");
  16522. ASSERT_EQ("text1", text);
  16523. handled = true;
  16524. });
  16525. thread t = thread([&] { svr.listen(HOST, PORT); });
  16526. auto se = detail::scope_exit([&] {
  16527. svr.stop();
  16528. t.join();
  16529. ASSERT_FALSE(svr.is_running());
  16530. ASSERT_TRUE(handled);
  16531. });
  16532. svr.wait_until_ready();
  16533. auto boundary = std::string("cpp-httplib-multipart-data");
  16534. std::string content = "--" + boundary +
  16535. "\r\n"
  16536. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16537. "\r\n"
  16538. "text1\r\n"
  16539. "--" +
  16540. boundary + "--\r\n";
  16541. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16542. "Host: localhost\r\n"
  16543. "Content-Type: multipart/form-data;boundary=" +
  16544. boundary +
  16545. "\r\n"
  16546. "Content-Length: " +
  16547. std::to_string(content.size()) +
  16548. "\r\n"
  16549. "Dummy-Header: ";
  16550. std::string header_suffix = "\r\n"
  16551. "\r\n";
  16552. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16553. size_t header_dummy_size =
  16554. read_buff_size -
  16555. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16556. auto header_dummy = std::string(header_dummy_size, '@');
  16557. auto req = header_prefix + header_dummy + header_suffix + content;
  16558. std::string response;
  16559. ASSERT_TRUE(send_request(1, req, &response));
  16560. ASSERT_EQ("200", response.substr(9, 3));
  16561. }
  16562. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16563. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16564. // (not chunked Transfer-Encoding) after the streaming refactor.
  16565. auto handled = false;
  16566. Server svr;
  16567. svr.Post("/upload", [&](const Request &req, Response &res) {
  16568. auto cl_it = req.headers.find("Content-Length");
  16569. EXPECT_TRUE(cl_it != req.headers.end());
  16570. auto te_it = req.headers.find("Transfer-Encoding");
  16571. EXPECT_TRUE(te_it == req.headers.end());
  16572. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16573. res.set_content("ok", "text/plain");
  16574. handled = true;
  16575. });
  16576. auto port = svr.bind_to_any_port(HOST);
  16577. auto t = thread([&] { svr.listen_after_bind(); });
  16578. auto se = detail::scope_exit([&] {
  16579. svr.stop();
  16580. t.join();
  16581. ASSERT_FALSE(svr.is_running());
  16582. ASSERT_TRUE(handled);
  16583. });
  16584. svr.wait_until_ready();
  16585. UploadFormDataItems items = {
  16586. {"field1", "hello", "", "text/plain"},
  16587. {"file1", "world", "test.txt", "application/octet-stream"},
  16588. };
  16589. Client cli(HOST, port);
  16590. auto res = cli.Post("/upload", {}, items);
  16591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16592. EXPECT_EQ(StatusCode::OK_200, res->status);
  16593. }
  16594. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16595. // Verify that make_multipart_content_provider coalesces many small segments
  16596. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16597. constexpr size_t kItemCount = 1000;
  16598. UploadFormDataItems items;
  16599. items.reserve(kItemCount);
  16600. for (size_t i = 0; i < kItemCount; i++) {
  16601. items.push_back(
  16602. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16603. }
  16604. const std::string boundary = "----test-boundary";
  16605. auto content_length = detail::get_multipart_content_length(items, boundary);
  16606. auto provider = detail::make_multipart_content_provider(items, boundary);
  16607. // Drive the provider the same way write_content_with_progress does
  16608. size_t write_count = 0;
  16609. size_t total_bytes = 0;
  16610. DataSink sink;
  16611. size_t offset = 0;
  16612. sink.write = [&](const char *d, size_t l) -> bool {
  16613. (void)d;
  16614. write_count++;
  16615. total_bytes += l;
  16616. offset += l;
  16617. return true;
  16618. };
  16619. sink.is_writable = []() -> bool { return true; };
  16620. while (offset < content_length) {
  16621. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16622. }
  16623. EXPECT_EQ(content_length, total_bytes);
  16624. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16625. // With buffering into 64KB blocks, write_count should be much smaller.
  16626. auto segment_count = 3 * kItemCount + 1;
  16627. EXPECT_LT(write_count, segment_count / 10);
  16628. }
  16629. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16630. // Integration test: send many UploadFormDataItems and verify the server
  16631. // receives all of them correctly (#2410).
  16632. constexpr size_t kItemCount = 500;
  16633. auto handled = false;
  16634. Server svr;
  16635. svr.Post("/upload", [&](const Request &req, Response &res) {
  16636. EXPECT_EQ(kItemCount, req.form.fields.size());
  16637. for (size_t i = 0; i < kItemCount; i++) {
  16638. auto key = "field" + std::to_string(i);
  16639. auto val = "value" + std::to_string(i);
  16640. auto it = req.form.fields.find(key);
  16641. if (it != req.form.fields.end()) {
  16642. EXPECT_EQ(val, it->second.content);
  16643. } else {
  16644. ADD_FAILURE() << "Missing field: " << key;
  16645. }
  16646. }
  16647. res.set_content("ok", "text/plain");
  16648. handled = true;
  16649. });
  16650. auto port = svr.bind_to_any_port(HOST);
  16651. auto t = thread([&] { svr.listen_after_bind(); });
  16652. auto se = detail::scope_exit([&] {
  16653. svr.stop();
  16654. t.join();
  16655. ASSERT_FALSE(svr.is_running());
  16656. ASSERT_TRUE(handled);
  16657. });
  16658. svr.wait_until_ready();
  16659. UploadFormDataItems items;
  16660. items.reserve(kItemCount);
  16661. for (size_t i = 0; i < kItemCount; i++) {
  16662. items.push_back(
  16663. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16664. }
  16665. Client cli(HOST, port);
  16666. auto res = cli.Post("/upload", items);
  16667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16668. EXPECT_EQ(StatusCode::OK_200, res->status);
  16669. }
  16670. TEST(MultipartFormDataTest, MakeFileProvider) {
  16671. // Verify make_file_provider sends a file's contents correctly.
  16672. const std::string file_content(4096, 'Z');
  16673. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16674. {
  16675. std::ofstream ofs(tmp_path, std::ios::binary);
  16676. ofs.write(file_content.data(),
  16677. static_cast<std::streamsize>(file_content.size()));
  16678. }
  16679. auto handled = false;
  16680. Server svr;
  16681. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16682. const ContentReader &content_reader) {
  16683. ASSERT_TRUE(req.is_multipart_form_data());
  16684. std::vector<FormData> items;
  16685. content_reader(
  16686. [&](const FormData &file) {
  16687. items.push_back(file);
  16688. return true;
  16689. },
  16690. [&](const char *data, size_t data_length) {
  16691. items.back().content.append(data, data_length);
  16692. return true;
  16693. });
  16694. ASSERT_EQ(1u, items.size());
  16695. EXPECT_EQ("myfile", items[0].name);
  16696. EXPECT_EQ("data.bin", items[0].filename);
  16697. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16698. EXPECT_EQ(file_content, items[0].content);
  16699. handled = true;
  16700. });
  16701. auto port = svr.bind_to_any_port(HOST);
  16702. auto t = thread([&] { svr.listen_after_bind(); });
  16703. auto se = detail::scope_exit([&] {
  16704. svr.stop();
  16705. t.join();
  16706. ASSERT_FALSE(svr.is_running());
  16707. ASSERT_TRUE(handled);
  16708. std::remove(tmp_path.c_str());
  16709. });
  16710. svr.wait_until_ready();
  16711. FormDataProviderItems providers;
  16712. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16713. "application/octet-stream"));
  16714. Client cli(HOST, port);
  16715. auto res = cli.Post("/upload", {}, {}, providers);
  16716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16717. EXPECT_EQ(StatusCode::OK_200, res->status);
  16718. }
  16719. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16720. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16721. // (100) headers is rejected with a 400 Bad Request response.
  16722. Server svr;
  16723. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16724. res.set_content("ok", "text/plain");
  16725. });
  16726. thread t = thread([&] { svr.listen(HOST, PORT); });
  16727. auto se = detail::scope_exit([&] {
  16728. svr.stop();
  16729. t.join();
  16730. ASSERT_FALSE(svr.is_running());
  16731. });
  16732. svr.wait_until_ready();
  16733. // Build a multipart part with 101 custom headers (exceeding
  16734. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16735. std::stringstream body;
  16736. body << "--simpleboundary\r\n"
  16737. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16738. for (int i = 0; i < 101; i++) {
  16739. body << "X-Custom-Header-" << i << ": value\r\n";
  16740. }
  16741. body << "\r\n"
  16742. << "value1\r\n"
  16743. << "--simpleboundary--\r\n";
  16744. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16745. Client cli(HOST, PORT);
  16746. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16749. }
  16750. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16751. // A body that never contains the declared boundary must not be accumulated
  16752. // while the parser waits for it. Buffering it would also make every read
  16753. // rescan everything seen so far, which is quadratic in the body size.
  16754. Server svr;
  16755. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16756. res.set_content("ok", "text/plain");
  16757. });
  16758. auto port = svr.bind_to_any_port(HOST);
  16759. thread t = thread([&] { svr.listen_after_bind(); });
  16760. auto se = detail::scope_exit([&] {
  16761. svr.stop();
  16762. t.join();
  16763. ASSERT_FALSE(svr.is_running());
  16764. });
  16765. svr.wait_until_ready();
  16766. Client cli(HOST, port);
  16767. cli.set_read_timeout(60, 0);
  16768. cli.set_write_timeout(60, 0);
  16769. // '-' is the worst case: it matches the first character of the boundary, so
  16770. // every position has to be checked against it.
  16771. auto post_dashes = [&](size_t size) {
  16772. const std::string body(size, '-');
  16773. auto start = std::chrono::steady_clock::now();
  16774. auto res =
  16775. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16776. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16777. std::chrono::steady_clock::now() - start)
  16778. .count();
  16779. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16780. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16781. return ms;
  16782. };
  16783. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16784. // Windows.
  16785. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16786. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16787. // Comparing the two sizes rather than checking an absolute duration keeps
  16788. // this meaningful across build types and CI load, both of which move the
  16789. // absolute numbers by more than an order of magnitude. Four times the bytes
  16790. // costs about four times the time when parsing is linear, and about sixteen
  16791. // times when the body is buffered and rescanned.
  16792. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16793. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16794. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16795. << "ms, which suggests the body is being buffered and rescanned";
  16796. }
  16797. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16798. // A boundary can only be followed by CRLF or by "--", so anything else is
  16799. // malformed no matter what comes next. The parser must say so right away
  16800. // instead of buffering the rest of the declared body.
  16801. Server svr;
  16802. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16803. res.set_content("ok", "text/plain");
  16804. });
  16805. auto port = svr.bind_to_any_port(HOST);
  16806. thread t = thread([&] { svr.listen_after_bind(); });
  16807. auto se = detail::scope_exit([&] {
  16808. svr.stop();
  16809. t.join();
  16810. ASSERT_FALSE(svr.is_running());
  16811. });
  16812. svr.wait_until_ready();
  16813. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16814. // buffers instead of failing would still be waiting for the remaining bytes.
  16815. const std::string body = "--zzzz\r\n"
  16816. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16817. "\r\n"
  16818. "text1"
  16819. "\r\n--zzzzXX";
  16820. const std::string req = "POST /post HTTP/1.1\r\n"
  16821. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16822. "Content-Length: 1048576\r\n"
  16823. "\r\n" +
  16824. body;
  16825. std::string response;
  16826. ASSERT_TRUE(send_request(3, req, &response, port));
  16827. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16828. EXPECT_EQ("400", response.substr(9, 3));
  16829. }
  16830. // Posts a multipart body split into two writes, so that the server sees the
  16831. // split at whatever offset the caller chose, and expects the single "text1"
  16832. // field to come through.
  16833. static void expect_split_multipart_ok(const std::string &body1,
  16834. const std::string &body2) {
  16835. auto handled = false;
  16836. Server svr;
  16837. svr.Post("/post", [&](const Request &req, Response &) {
  16838. EXPECT_EQ(1u, req.form.fields.size());
  16839. EXPECT_EQ("text1", req.form.get_field("text1"));
  16840. handled = true;
  16841. });
  16842. auto port = svr.bind_to_any_port(HOST);
  16843. thread t = thread([&] { svr.listen_after_bind(); });
  16844. auto se = detail::scope_exit([&] {
  16845. svr.stop();
  16846. t.join();
  16847. ASSERT_FALSE(svr.is_running());
  16848. ASSERT_TRUE(handled);
  16849. });
  16850. svr.wait_until_ready();
  16851. // "Connection: close" makes the server close once it has answered, so the
  16852. // response drain ends immediately instead of idling until the read timeout.
  16853. const std::string head =
  16854. "POST /post HTTP/1.1\r\n"
  16855. "Host: localhost\r\n"
  16856. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16857. "Connection: close\r\n"
  16858. "Content-Length: " +
  16859. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16860. std::string response;
  16861. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16862. ASSERT_GE(response.size(), 12u) << "no response";
  16863. EXPECT_EQ("200", response.substr(9, 3));
  16864. }
  16865. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16866. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16867. // ignored, including when it does not arrive in the same read as the
  16868. // close-delimiter itself.
  16869. expect_split_multipart_ok("--zzzz\r\n"
  16870. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16871. "\r\n"
  16872. "text1"
  16873. "\r\n--zzzz--",
  16874. "\r\nthis epilogue must be ignored\r\n");
  16875. }
  16876. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16877. // The initial boundary may be preceded by a preamble of any length and may
  16878. // straddle a read boundary. Discarding data while waiting for it must not
  16879. // throw away a partial boundary sitting at the end of the buffer.
  16880. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16881. "zz\r\n"
  16882. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16883. "\r\n"
  16884. "text1"
  16885. "\r\n--zzzz--\r\n");
  16886. }
  16887. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16888. // The received boundary was only checked for being non-empty, so it could be
  16889. // as long as a header is allowed to be. The parser scans the body for
  16890. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16891. // costs a nearly full comparison at nearly every position, making the
  16892. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16893. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16894. Server svr;
  16895. svr.Post("/post", [](const Request &req, Response &res) {
  16896. EXPECT_EQ(1u, req.form.fields.size());
  16897. EXPECT_EQ("text1", req.form.get_field("text1"));
  16898. res.set_content("ok", "text/plain");
  16899. });
  16900. auto port = svr.bind_to_any_port(HOST);
  16901. thread t = thread([&] { svr.listen_after_bind(); });
  16902. auto se = detail::scope_exit([&] {
  16903. svr.stop();
  16904. t.join();
  16905. ASSERT_FALSE(svr.is_running());
  16906. });
  16907. svr.wait_until_ready();
  16908. Client cli(HOST, port);
  16909. auto post_with_boundary_of_length = [&](size_t len) {
  16910. const std::string boundary(len, 'a');
  16911. const std::string body =
  16912. "--" + boundary +
  16913. "\r\n"
  16914. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16915. "\r\n"
  16916. "text1"
  16917. "\r\n--" +
  16918. boundary + "--\r\n";
  16919. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16920. };
  16921. auto res = post_with_boundary_of_length(70);
  16922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16923. EXPECT_EQ(StatusCode::OK_200, res->status);
  16924. res = post_with_boundary_of_length(71);
  16925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16926. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16927. }
  16928. TEST(MakeFileBodyTest, Basic) {
  16929. const std::string file_content(4096, 'Z');
  16930. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16931. {
  16932. std::ofstream ofs(tmp_path, std::ios::binary);
  16933. ofs.write(file_content.data(),
  16934. static_cast<std::streamsize>(file_content.size()));
  16935. }
  16936. auto handled = false;
  16937. Server svr;
  16938. svr.Post("/upload", [&](const Request &req, Response &res) {
  16939. EXPECT_EQ(file_content, req.body);
  16940. handled = true;
  16941. res.status = StatusCode::OK_200;
  16942. });
  16943. auto port = svr.bind_to_any_port(HOST);
  16944. auto t = thread([&] { svr.listen_after_bind(); });
  16945. auto se = detail::scope_exit([&] {
  16946. svr.stop();
  16947. t.join();
  16948. ASSERT_FALSE(svr.is_running());
  16949. ASSERT_TRUE(handled);
  16950. std::remove(tmp_path.c_str());
  16951. });
  16952. svr.wait_until_ready();
  16953. auto fb = make_file_body(tmp_path);
  16954. ASSERT_GT(fb.first, 0u);
  16955. Client cli(HOST, port);
  16956. auto res =
  16957. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16959. EXPECT_EQ(StatusCode::OK_200, res->status);
  16960. }
  16961. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16962. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16963. {
  16964. std::ofstream ofs(path, std::ios::binary);
  16965. const std::string content(100, 'A');
  16966. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16967. }
  16968. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16969. auto body = make_file_body(path);
  16970. ASSERT_EQ(100u, body.first);
  16971. ASSERT_TRUE(static_cast<bool>(body.second));
  16972. // Rewritten shorter after its length was measured - and, on a server, after
  16973. // that length has already gone out as Content-Length.
  16974. {
  16975. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16976. const std::string content(10, 'A');
  16977. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16978. }
  16979. std::string written;
  16980. DataSink sink;
  16981. sink.write = [&](const char *d, size_t l) {
  16982. written.append(d, l);
  16983. return true;
  16984. };
  16985. // The provider has to report failure. write_content_with_progress() advances
  16986. // its offset only by what was written, so a provider that returns true
  16987. // without completing the length it promised is called again straight away,
  16988. // and again.
  16989. EXPECT_FALSE(body.second(0, body.first, sink));
  16990. EXPECT_EQ(std::string(10, 'A'), written);
  16991. }
  16992. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16993. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16994. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16995. {
  16996. std::ofstream ofs(path, std::ios::binary);
  16997. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16998. }
  16999. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17000. auto body = make_file_body(path);
  17001. ASSERT_EQ(content.size(), body.first);
  17002. ASSERT_TRUE(static_cast<bool>(body.second));
  17003. std::string written;
  17004. DataSink sink;
  17005. sink.write = [&](const char *d, size_t l) {
  17006. written.append(d, l);
  17007. return true;
  17008. };
  17009. EXPECT_TRUE(body.second(0, body.first, sink));
  17010. EXPECT_EQ(content, written);
  17011. }
  17012. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17013. static constexpr unsigned int number_of_tasks{1000000};
  17014. std::atomic_uint count{0};
  17015. std::unique_ptr<TaskQueue> task_queue{
  17016. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17017. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17018. auto queued = task_queue->enqueue(
  17019. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17020. EXPECT_TRUE(queued);
  17021. }
  17022. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17023. task_queue->shutdown();
  17024. #else
  17025. EXPECT_NO_THROW(task_queue->shutdown());
  17026. #endif
  17027. EXPECT_EQ(number_of_tasks, count.load());
  17028. }
  17029. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17030. static constexpr unsigned int number_of_tasks{1000000};
  17031. static constexpr unsigned int qlimit{2};
  17032. unsigned int queued_count{0};
  17033. std::atomic_uint count{0};
  17034. std::unique_ptr<TaskQueue> task_queue{
  17035. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17036. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17037. if (task_queue->enqueue(
  17038. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17039. queued_count++;
  17040. }
  17041. }
  17042. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17043. task_queue->shutdown();
  17044. #else
  17045. EXPECT_NO_THROW(task_queue->shutdown());
  17046. #endif
  17047. EXPECT_EQ(queued_count, count.load());
  17048. EXPECT_TRUE(queued_count <= number_of_tasks);
  17049. EXPECT_TRUE(queued_count >= qlimit);
  17050. }
  17051. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17052. // Use a short idle timeout so a dynamic thread spawns, times out and
  17053. // exits during the test, and the pool keeps working afterwards.
  17054. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17055. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17056. /*idle_timeout_sec=*/1}};
  17057. std::atomic_uint count{0};
  17058. std::condition_variable cv;
  17059. std::mutex mtx;
  17060. bool release = false;
  17061. // Block the base thread so the second task spawns a dynamic thread.
  17062. EXPECT_TRUE(task_queue->enqueue([&] {
  17063. std::unique_lock<std::mutex> lock(mtx);
  17064. while (!release) {
  17065. cv.wait(lock);
  17066. }
  17067. count++;
  17068. }));
  17069. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17070. // Let the dynamic thread finish its task and exceed the idle timeout.
  17071. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17072. {
  17073. std::unique_lock<std::mutex> lock(mtx);
  17074. release = true;
  17075. }
  17076. cv.notify_all();
  17077. // The pool must still accept and run tasks after the dynamic thread exited.
  17078. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17079. task_queue->shutdown();
  17080. EXPECT_EQ(3u, count.load());
  17081. }
  17082. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17083. static constexpr size_t number_of_tasks{32};
  17084. std::unique_ptr<TaskQueue> task_queue{
  17085. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17086. // Let the base threads go idle so the burst below finds them waiting.
  17087. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17088. std::mutex mtx;
  17089. std::condition_variable cv;
  17090. size_t running = 0;
  17091. bool release = false;
  17092. for (size_t i = 0; i < number_of_tasks; i++) {
  17093. EXPECT_TRUE(task_queue->enqueue([&] {
  17094. std::unique_lock<std::mutex> lock(mtx);
  17095. running++;
  17096. cv.notify_all();
  17097. cv.wait(lock, [&] { return release; });
  17098. }));
  17099. }
  17100. {
  17101. std::unique_lock<std::mutex> lock(mtx);
  17102. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17103. [&] { return running == number_of_tasks; }));
  17104. release = true;
  17105. }
  17106. cv.notify_all();
  17107. task_queue->shutdown();
  17108. }
  17109. TEST(TaskQueueTest, MaxQueuedRequests) {
  17110. static constexpr unsigned int qlimit{3};
  17111. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17112. std::condition_variable sem_cv;
  17113. std::mutex sem_mtx;
  17114. int credits = 0;
  17115. bool queued;
  17116. /* Fill up the queue with tasks that will block until we give them credits to
  17117. * complete. */
  17118. for (unsigned int n = 0; n <= qlimit;) {
  17119. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17120. std::unique_lock<std::mutex> lock(sem_mtx);
  17121. while (credits <= 0) {
  17122. sem_cv.wait(lock);
  17123. }
  17124. /* Consume the credit and signal the test code if they are all gone. */
  17125. if (--credits == 0) { sem_cv.notify_one(); }
  17126. });
  17127. if (n < qlimit) {
  17128. /* The first qlimit enqueues must succeed. */
  17129. EXPECT_TRUE(queued);
  17130. } else {
  17131. /* The last one will succeed only when the worker thread
  17132. * starts and dequeues the first blocking task. Although
  17133. * not necessary for the correctness of this test, we sleep for
  17134. * a short while to avoid busy waiting. */
  17135. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17136. }
  17137. if (queued) { n++; }
  17138. }
  17139. /* Further enqueues must fail since the queue is full. */
  17140. for (auto i = 0; i < 4; i++) {
  17141. queued = task_queue->enqueue([] {});
  17142. EXPECT_FALSE(queued);
  17143. }
  17144. /* Give the credits to allow the previous tasks to complete. */
  17145. {
  17146. std::unique_lock<std::mutex> lock(sem_mtx);
  17147. credits += qlimit + 1;
  17148. }
  17149. sem_cv.notify_all();
  17150. /* Wait for all the credits to be consumed. */
  17151. {
  17152. std::unique_lock<std::mutex> lock(sem_mtx);
  17153. while (credits > 0) {
  17154. sem_cv.wait(lock);
  17155. }
  17156. }
  17157. /* Check that we are able again to enqueue at least qlimit tasks. */
  17158. for (unsigned int i = 0; i < qlimit; i++) {
  17159. queued = task_queue->enqueue([] {});
  17160. EXPECT_TRUE(queued);
  17161. }
  17162. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17163. task_queue->shutdown();
  17164. #else
  17165. EXPECT_NO_THROW(task_queue->shutdown());
  17166. #endif
  17167. }
  17168. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17169. Server svr;
  17170. std::string method;
  17171. std::string body;
  17172. auto has_content_length = false;
  17173. auto has_transfer_encoding = false;
  17174. std::atomic<int> bad_requests{0};
  17175. // Leftover body bytes get parsed as a malformed request and answered with
  17176. // 400
  17177. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17178. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17179. });
  17180. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17181. res.set_redirect("/down", StatusCode::SeeOther_303);
  17182. });
  17183. svr.Get("/down", [&](const Request &req, Response &res) {
  17184. method = req.method;
  17185. body = req.body;
  17186. has_content_length = req.has_header("Content-Length");
  17187. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17188. res.set_content("ok", "text/plain");
  17189. });
  17190. auto port = svr.bind_to_any_port(HOST);
  17191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. const std::string payload = "SECRET-BODY";
  17199. auto check = [&](Client &cli, const Result &res) {
  17200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17201. EXPECT_EQ(StatusCode::OK_200, res->status);
  17202. EXPECT_EQ("ok", res->body);
  17203. EXPECT_EQ("GET", method);
  17204. EXPECT_TRUE(body.empty());
  17205. EXPECT_FALSE(has_content_length);
  17206. EXPECT_FALSE(has_transfer_encoding);
  17207. // Nothing of the original body may be left on the connection
  17208. auto res2 = cli.Get("/down");
  17209. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17210. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17211. EXPECT_EQ("ok", res2->body);
  17212. EXPECT_EQ(0, bad_requests);
  17213. };
  17214. // With content length
  17215. {
  17216. Client cli(HOST, port);
  17217. cli.set_keep_alive(true);
  17218. cli.set_follow_location(true);
  17219. auto res = cli.Post(
  17220. "/up", payload.size(),
  17221. [&](size_t offset, size_t length, DataSink &sink) {
  17222. return sink.write(payload.data() + offset, length);
  17223. },
  17224. "text/plain");
  17225. check(cli, res);
  17226. }
  17227. // Without content length (chunked)
  17228. {
  17229. Client cli(HOST, port);
  17230. cli.set_keep_alive(true);
  17231. cli.set_follow_location(true);
  17232. auto res = cli.Post(
  17233. "/up",
  17234. [&](size_t /*offset*/, DataSink &sink) {
  17235. sink.write(payload.data(), payload.size());
  17236. sink.done();
  17237. return true;
  17238. },
  17239. "text/plain");
  17240. check(cli, res);
  17241. }
  17242. }
  17243. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17244. Server svr;
  17245. std::string target;
  17246. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17247. // Echo the still-encoded name back in the Location
  17248. const std::string prefix = "/start/";
  17249. res.status = StatusCode::Found_302;
  17250. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17251. });
  17252. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17253. target = req.target;
  17254. res.set_content("ok", "text/plain");
  17255. });
  17256. auto port = svr.bind_to_any_port(HOST);
  17257. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17258. auto se = detail::scope_exit([&] {
  17259. svr.stop();
  17260. thread.join();
  17261. ASSERT_FALSE(svr.is_running());
  17262. });
  17263. svr.wait_until_ready();
  17264. // Decoding the Location path would turn the first four into a path
  17265. // separator, a query delimiter, a fragment delimiter and a different
  17266. // percent-encoded octet. The rest must keep reaching the server as they are.
  17267. const std::vector<std::string> names = {
  17268. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17269. };
  17270. for (auto path_encode : {true, false}) {
  17271. Client cli(HOST, port);
  17272. cli.set_follow_location(true);
  17273. cli.set_path_encode(path_encode);
  17274. for (const auto &name : names) {
  17275. target.clear();
  17276. auto res = cli.Get("/start/" + name);
  17277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17278. EXPECT_EQ(StatusCode::OK_200, res->status);
  17279. EXPECT_EQ("/dest/" + name, target);
  17280. }
  17281. }
  17282. }
  17283. TEST(RedirectTest, NotModifiedIsReturned) {
  17284. Server svr;
  17285. svr.Get("/cached", [](const Request &, Response &res) {
  17286. res.status = StatusCode::NotModified_304;
  17287. });
  17288. auto port = svr.bind_to_any_port(HOST);
  17289. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17290. auto se = detail::scope_exit([&] {
  17291. svr.stop();
  17292. thread.join();
  17293. ASSERT_FALSE(svr.is_running());
  17294. });
  17295. svr.wait_until_ready();
  17296. Client cli(HOST, port);
  17297. cli.set_follow_location(true);
  17298. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17300. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17301. }
  17302. TEST(RedirectTest, NoLocationIsReturned) {
  17303. Server svr;
  17304. svr.Get("/no-location", [](const Request &, Response &res) {
  17305. res.status = StatusCode::Found_302;
  17306. res.set_content("no location", "text/plain");
  17307. });
  17308. auto port = svr.bind_to_any_port(HOST);
  17309. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17310. auto se = detail::scope_exit([&] {
  17311. svr.stop();
  17312. thread.join();
  17313. ASSERT_FALSE(svr.is_running());
  17314. });
  17315. svr.wait_until_ready();
  17316. Client cli(HOST, port);
  17317. cli.set_follow_location(true);
  17318. auto res = cli.Get("/no-location");
  17319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17320. EXPECT_EQ(StatusCode::Found_302, res->status);
  17321. EXPECT_EQ("no location", res->body);
  17322. // The callbacks see the body of the response that is returned
  17323. auto handler_called = false;
  17324. auto progress_called = false;
  17325. std::string body;
  17326. auto res2 = cli.Get(
  17327. "/no-location",
  17328. [&](const Response &) {
  17329. handler_called = true;
  17330. return true;
  17331. },
  17332. [&](const char *data, size_t data_length) {
  17333. body.append(data, data_length);
  17334. return true;
  17335. },
  17336. [&](size_t, size_t) {
  17337. progress_called = true;
  17338. return true;
  17339. });
  17340. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17341. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17342. EXPECT_TRUE(handler_called);
  17343. EXPECT_TRUE(progress_called);
  17344. EXPECT_EQ("no location", body);
  17345. }
  17346. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17347. Server svr;
  17348. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17349. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17350. });
  17351. svr.Get("/hello", [](const Request &req, Response &res) {
  17352. res.set_content(req.get_param_value("key"), "text/plain");
  17353. });
  17354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. thread.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. {
  17362. Client cli(HOST, PORT);
  17363. cli.set_follow_location(true);
  17364. auto res = cli.Get("/");
  17365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17366. EXPECT_EQ(StatusCode::OK_200, res->status);
  17367. EXPECT_EQ("val&key2=val2", res->body);
  17368. }
  17369. }
  17370. #endif
  17371. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17372. Server svr;
  17373. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17374. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  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("AByz09 ~-._ &?ü+", res->body);
  17393. }
  17394. }
  17395. TEST(RedirectTest, RedirectWithPlusInPath) {
  17396. Server svr;
  17397. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17398. res.set_redirect("/a+b");
  17399. });
  17400. // Route pattern uses regex; escape + as \\+
  17401. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17402. res.set_content(req.path, "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("/a+b", res->body);
  17418. }
  17419. }
  17420. TEST(RedirectTest, ResolveRelativeLocation) {
  17421. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17422. const std::vector<std::pair<std::string, std::string>> cases = {
  17423. {"g", "/b/c/g"},
  17424. {"./g", "/b/c/g"},
  17425. {"g/", "/b/c/g/"},
  17426. {"?y", "/b/c/d;p?y"},
  17427. {"g?y", "/b/c/g?y"},
  17428. {"#s", "/b/c/d;p?q#s"},
  17429. {"g#s", "/b/c/g#s"},
  17430. {"g?y#s", "/b/c/g?y#s"},
  17431. {";x", "/b/c/;x"},
  17432. {"g;x", "/b/c/g;x"},
  17433. {".", "/b/c/"},
  17434. {"./", "/b/c/"},
  17435. {"..", "/b/"},
  17436. {"../", "/b/"},
  17437. {"../g", "/b/g"},
  17438. {"../..", "/"},
  17439. {"../../", "/"},
  17440. {"../../g", "/g"},
  17441. {"../../../g", "/g"},
  17442. {"g.", "/b/c/g."},
  17443. {".g", "/b/c/.g"},
  17444. {"g..", "/b/c/g.."},
  17445. {"..g", "/b/c/..g"},
  17446. {"./../g", "/b/g"},
  17447. {"./g/.", "/b/c/g/"},
  17448. {"g/./h", "/b/c/g/h"},
  17449. {"g/../h", "/b/c/h"},
  17450. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17451. {"g;x=1/../y", "/b/c/y"},
  17452. {"g?y/./x", "/b/c/g?y/./x"},
  17453. {"g#s/../x", "/b/c/g#s/../x"},
  17454. // Not relative-path references, so left for parse_url.
  17455. {"/g", "/g"},
  17456. {"//g", "//g"},
  17457. {"http://g/x", "http://g/x"},
  17458. {"g:h", "g:h"},
  17459. };
  17460. for (const auto &c : cases) {
  17461. EXPECT_EQ(c.second,
  17462. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17463. << c.first;
  17464. }
  17465. }
  17466. TEST(RedirectTest, RemoveDotSegments) {
  17467. // RFC 3986 section 5.2.4
  17468. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17469. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17470. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17471. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17472. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17473. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17474. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17475. }
  17476. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17477. Server svr;
  17478. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17479. res.set_redirect("/dir/../target?x=1");
  17480. });
  17481. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17482. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17483. "/dir/./../target");
  17484. });
  17485. svr.Get("/target", [](const Request &req, Response &res) {
  17486. res.set_content(req.path, "text/plain");
  17487. });
  17488. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17489. auto se = detail::scope_exit([&] {
  17490. svr.stop();
  17491. th.join();
  17492. ASSERT_FALSE(svr.is_running());
  17493. });
  17494. svr.wait_until_ready();
  17495. Client cli("localhost", PORT);
  17496. cli.set_follow_location(true);
  17497. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17498. auto res = cli.Get(path);
  17499. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17500. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17501. EXPECT_EQ("/target", res->body) << path;
  17502. }
  17503. }
  17504. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17505. Server svr;
  17506. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17507. res.set_redirect(req.get_param_value("to"));
  17508. });
  17509. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17510. res.set_content(req.target, "text/plain");
  17511. });
  17512. svr.Get("/other", [](const Request &req, Response &res) {
  17513. res.set_content(req.target, "text/plain");
  17514. });
  17515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17516. auto se = detail::scope_exit([&] {
  17517. svr.stop();
  17518. thread.join();
  17519. ASSERT_FALSE(svr.is_running());
  17520. });
  17521. svr.wait_until_ready();
  17522. const std::vector<std::pair<std::string, std::string>> cases = {
  17523. {"next", "/dir/next"},
  17524. {"./next?x=1", "/dir/next?x=1"},
  17525. {"../other", "/other"},
  17526. };
  17527. for (const auto &c : cases) {
  17528. Client cli(HOST, PORT);
  17529. cli.set_follow_location(true);
  17530. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17531. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17532. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17533. EXPECT_EQ(c.second, res->body) << c.first;
  17534. }
  17535. }
  17536. #ifdef CPPHTTPLIB_SSL_ENABLED
  17537. TEST(RedirectTest, Issue2185_Online) {
  17538. SSLClient client("github.com");
  17539. client.set_follow_location(true);
  17540. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17541. "Coollab-Windows.zip");
  17542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17543. EXPECT_EQ(StatusCode::OK_200, res->status);
  17544. EXPECT_EQ(9920427U, res->body.size());
  17545. }
  17546. #endif
  17547. TEST(VulnerabilityTest, CRLFInjection) {
  17548. Server svr;
  17549. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17550. res.set_content("Hello 1", "text/plain");
  17551. });
  17552. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17553. res.set_content("Hello 2", "text/plain");
  17554. });
  17555. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17556. res.set_content("Hello 3", "text/plain");
  17557. });
  17558. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17559. res.set_content("Hello 4", "text/plain");
  17560. });
  17561. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17562. for (const auto &x : req.headers) {
  17563. auto key = x.first;
  17564. EXPECT_STRNE("evil", key.c_str());
  17565. }
  17566. });
  17567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17568. auto se = detail::scope_exit([&] {
  17569. svr.stop();
  17570. thread.join();
  17571. ASSERT_FALSE(svr.is_running());
  17572. });
  17573. svr.wait_until_ready();
  17574. {
  17575. Client cli(HOST, PORT);
  17576. cli.Post("/test1", "A=B",
  17577. "application/x-www-form-urlencoded\r\nevil: hello1");
  17578. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17579. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17580. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17581. }
  17582. }
  17583. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17584. auto server_thread = std::thread([] {
  17585. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17586. default_socket_options(srv);
  17587. sockaddr_in addr{};
  17588. addr.sin_family = AF_INET;
  17589. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17591. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17592. ::listen(srv, 1);
  17593. sockaddr_in cli_addr{};
  17594. socklen_t cli_len = sizeof(cli_addr);
  17595. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17596. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17597. std::string buf_all;
  17598. char buf[2048];
  17599. ssize_t n;
  17600. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17601. buf_all.append(buf, static_cast<size_t>(n));
  17602. size_t pos;
  17603. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17604. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17605. auto e = request_block.find("\r\n");
  17606. if (e != std::string::npos) {
  17607. auto request_line = request_block.substr(0, e);
  17608. std::string msg =
  17609. "CRLF injection detected in request line: '" + request_line + "'";
  17610. EXPECT_FALSE(true) << msg;
  17611. }
  17612. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17613. ::send(cli,
  17614. #ifdef _WIN32
  17615. static_cast<const char *>(resp.c_str()),
  17616. static_cast<int>(resp.size()),
  17617. #else
  17618. resp.c_str(), resp.size(),
  17619. #endif
  17620. 0);
  17621. buf_all.erase(0, pos + 4);
  17622. }
  17623. }
  17624. detail::close_socket(cli);
  17625. detail::close_socket(srv);
  17626. });
  17627. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17628. auto cli = Client("127.0.0.1", PORT + 1);
  17629. auto headers = Headers{
  17630. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17631. {"Connection", "keep-alive"}};
  17632. auto res = cli.Get("/hi", headers);
  17633. EXPECT_FALSE(res);
  17634. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17635. server_thread.join();
  17636. }
  17637. // A request rejected before any byte reaches the socket must fail right away
  17638. // instead of waiting for a response the server will never send.
  17639. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17640. // The kernel completes the TCP handshake from the listen backlog, so the
  17641. // client connects, but nothing ever reads, responds or closes.
  17642. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17643. default_socket_options(srv);
  17644. sockaddr_in addr{};
  17645. addr.sin_family = AF_INET;
  17646. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17647. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17648. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17649. ASSERT_EQ(0, ::listen(srv, 8));
  17650. auto cli = Client("127.0.0.1", PORT + 1);
  17651. cli.set_read_timeout(10, 0);
  17652. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17653. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17654. std::chrono::steady_clock::now() - start)
  17655. .count();
  17656. };
  17657. {
  17658. Request req;
  17659. req.method = "GE T";
  17660. req.path = "/";
  17661. auto start = std::chrono::steady_clock::now();
  17662. auto res = cli.send(req);
  17663. EXPECT_FALSE(res);
  17664. EXPECT_EQ(Error::Write, res.error());
  17665. EXPECT_LT(elapsed_ms(start), 1000);
  17666. }
  17667. {
  17668. auto start = std::chrono::steady_clock::now();
  17669. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17670. EXPECT_FALSE(res);
  17671. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17672. EXPECT_LT(elapsed_ms(start), 1000);
  17673. }
  17674. EXPECT_FALSE(cli.is_socket_open());
  17675. detail::close_socket(srv);
  17676. }
  17677. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17678. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17679. default_socket_options(srv);
  17680. sockaddr_in addr{};
  17681. addr.sin_family = AF_INET;
  17682. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17683. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17684. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17685. ASSERT_EQ(0, ::listen(srv, 1));
  17686. std::string received;
  17687. auto server_thread = std::thread([&] {
  17688. auto sock = ::accept(srv, nullptr, nullptr);
  17689. if (sock == INVALID_SOCKET) { return; }
  17690. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17691. char buf[2048];
  17692. ssize_t n;
  17693. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17694. received.append(buf, static_cast<size_t>(n));
  17695. }
  17696. detail::close_socket(sock);
  17697. });
  17698. {
  17699. auto cli = Client("127.0.0.1", PORT + 1);
  17700. // "Z" sorts after the default headers, so writing straight to the socket
  17701. // would have sent the request line and those headers before the rejection.
  17702. auto handle =
  17703. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17704. EXPECT_FALSE(handle.is_valid());
  17705. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17706. }
  17707. server_thread.join();
  17708. detail::close_socket(srv);
  17709. EXPECT_TRUE(received.empty()) << received;
  17710. }
  17711. TEST(PathParamsTest, StaticMatch) {
  17712. const auto pattern = "/users/all";
  17713. detail::PathParamsMatcher matcher(pattern);
  17714. Request request;
  17715. request.path = "/users/all";
  17716. ASSERT_TRUE(matcher.match(request));
  17717. std::unordered_map<std::string, std::string> expected_params = {};
  17718. EXPECT_EQ(request.path_params, expected_params);
  17719. }
  17720. TEST(PathParamsTest, StaticMismatch) {
  17721. const auto pattern = "/users/all";
  17722. detail::PathParamsMatcher matcher(pattern);
  17723. Request request;
  17724. request.path = "/users/1";
  17725. ASSERT_FALSE(matcher.match(request));
  17726. }
  17727. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17728. const auto pattern = "/users/:id/subscriptions";
  17729. detail::PathParamsMatcher matcher(pattern);
  17730. Request request;
  17731. request.path = "/users/42/subscriptions";
  17732. ASSERT_TRUE(matcher.match(request));
  17733. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17734. EXPECT_EQ(request.path_params, expected_params);
  17735. }
  17736. TEST(PathParamsTest, SingleParamInTheEnd) {
  17737. const auto pattern = "/users/:id";
  17738. detail::PathParamsMatcher matcher(pattern);
  17739. Request request;
  17740. request.path = "/users/24";
  17741. ASSERT_TRUE(matcher.match(request));
  17742. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17743. EXPECT_EQ(request.path_params, expected_params);
  17744. }
  17745. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17746. const auto pattern = "/users/:id/";
  17747. detail::PathParamsMatcher matcher(pattern);
  17748. Request request;
  17749. request.path = "/users/42/";
  17750. ASSERT_TRUE(matcher.match(request));
  17751. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17752. EXPECT_EQ(request.path_params, expected_params);
  17753. }
  17754. TEST(PathParamsTest, EmptyParam) {
  17755. const auto pattern = "/users/:id/";
  17756. detail::PathParamsMatcher matcher(pattern);
  17757. Request request;
  17758. request.path = "/users//";
  17759. ASSERT_TRUE(matcher.match(request));
  17760. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17761. EXPECT_EQ(request.path_params, expected_params);
  17762. }
  17763. TEST(PathParamsTest, FragmentMismatch) {
  17764. const auto pattern = "/users/:id/";
  17765. detail::PathParamsMatcher matcher(pattern);
  17766. Request request;
  17767. request.path = "/admins/24/";
  17768. ASSERT_FALSE(matcher.match(request));
  17769. }
  17770. TEST(PathParamsTest, ExtraFragments) {
  17771. const auto pattern = "/users/:id";
  17772. detail::PathParamsMatcher matcher(pattern);
  17773. Request request;
  17774. request.path = "/users/42/subscriptions";
  17775. ASSERT_FALSE(matcher.match(request));
  17776. }
  17777. TEST(PathParamsTest, MissingTrailingParam) {
  17778. const auto pattern = "/users/:id";
  17779. detail::PathParamsMatcher matcher(pattern);
  17780. Request request;
  17781. request.path = "/users";
  17782. ASSERT_FALSE(matcher.match(request));
  17783. }
  17784. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17785. const auto pattern = "/users/:id/subscriptions";
  17786. detail::PathParamsMatcher matcher(pattern);
  17787. Request request;
  17788. request.path = "/users/subscriptions";
  17789. ASSERT_FALSE(matcher.match(request));
  17790. }
  17791. TEST(PathParamsTest, MultipleParams) {
  17792. const auto pattern = "/users/:userid/subscriptions/:subid";
  17793. detail::PathParamsMatcher matcher(pattern);
  17794. Request request;
  17795. request.path = "/users/42/subscriptions/2";
  17796. ASSERT_TRUE(matcher.match(request));
  17797. std::unordered_map<std::string, std::string> expected_params = {
  17798. {"userid", "42"}, {"subid", "2"}};
  17799. EXPECT_EQ(request.path_params, expected_params);
  17800. }
  17801. TEST(PathParamsTest, SequenceOfParams) {
  17802. const auto pattern = "/values/:x/:y/:z";
  17803. detail::PathParamsMatcher matcher(pattern);
  17804. Request request;
  17805. request.path = "/values/1/2/3";
  17806. ASSERT_TRUE(matcher.match(request));
  17807. std::unordered_map<std::string, std::string> expected_params = {
  17808. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17809. EXPECT_EQ(request.path_params, expected_params);
  17810. }
  17811. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17812. const auto pattern = "/prefix:suffix";
  17813. detail::PathParamsMatcher matcher(pattern);
  17814. Request request;
  17815. request.path = "/prefix:suffix";
  17816. ASSERT_TRUE(matcher.match(request));
  17817. const std::unordered_map<std::string, std::string> expected_params = {};
  17818. EXPECT_EQ(request.path_params, expected_params);
  17819. }
  17820. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17821. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17822. // calling thread's stack on a long enough path for a quantified pattern;
  17823. // RegexMatcher must refuse to run regex matching on paths beyond
  17824. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17825. detail::RegexMatcher matcher("/files/(.*)");
  17826. Request within_limit;
  17827. within_limit.path = "/files/" + std::string(10, 'A');
  17828. EXPECT_TRUE(matcher.match(within_limit));
  17829. Request over_limit;
  17830. over_limit.path =
  17831. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17832. EXPECT_FALSE(matcher.match(over_limit));
  17833. }
  17834. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17835. Server svr;
  17836. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17837. res.set_content("ok", "text/plain");
  17838. });
  17839. auto port = svr.bind_to_any_port(HOST);
  17840. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17841. auto se = detail::scope_exit([&] {
  17842. svr.stop();
  17843. thread.join();
  17844. ASSERT_FALSE(svr.is_running());
  17845. });
  17846. svr.wait_until_ready();
  17847. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17848. // request URI limit; this used to be able to crash the process.
  17849. std::string path =
  17850. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17851. std::string req = "GET " + path +
  17852. " HTTP/1.1\r\n"
  17853. "Host: " +
  17854. std::string(HOST) + ":" + std::to_string(port) +
  17855. "\r\n"
  17856. "Connection: close\r\n"
  17857. "\r\n";
  17858. std::string response;
  17859. ASSERT_TRUE(send_request(5, req, &response, port));
  17860. EXPECT_NE(std::string::npos, response.find("404"));
  17861. }
  17862. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17863. Server svr;
  17864. auto handler = [](const Request & /*req*/, Response &res) {
  17865. res.set_content("hit", "text/plain");
  17866. };
  17867. // No regex metacharacter, so this one is compared literally
  17868. svr.Get("/literal/route", handler);
  17869. // '.' is a regex metacharacter, so this one must keep regex semantics
  17870. svr.Get("/a.c", handler);
  17871. auto port = svr.bind_to_any_port(HOST);
  17872. std::thread t([&]() { svr.listen_after_bind(); });
  17873. auto se = detail::scope_exit([&] {
  17874. svr.stop();
  17875. t.join();
  17876. ASSERT_FALSE(svr.is_running());
  17877. });
  17878. svr.wait_until_ready();
  17879. Client cli(HOST, port);
  17880. struct {
  17881. const char *path;
  17882. int status;
  17883. } cases[] = {
  17884. {"/literal/route", StatusCode::OK_200},
  17885. {"/literal/routes", StatusCode::NotFound_404},
  17886. {"/literal/rout", StatusCode::NotFound_404},
  17887. {"/abc", StatusCode::OK_200},
  17888. {"/a.c", StatusCode::OK_200},
  17889. };
  17890. for (const auto &x : cases) {
  17891. auto res = cli.Get(x.path);
  17892. ASSERT_TRUE(res) << x.path;
  17893. EXPECT_EQ(x.status, res->status) << x.path;
  17894. }
  17895. }
  17896. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17897. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17898. // from exhausting the stack, so it must only constrain routes that actually
  17899. // run a regular expression. A literal route is matched by comparison and
  17900. // stays usable at any length.
  17901. Server svr;
  17902. const std::string pattern =
  17903. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17904. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17905. res.set_content("hit", "text/plain");
  17906. });
  17907. auto port = svr.bind_to_any_port(HOST);
  17908. std::thread t([&]() { svr.listen_after_bind(); });
  17909. auto se = detail::scope_exit([&] {
  17910. svr.stop();
  17911. t.join();
  17912. ASSERT_FALSE(svr.is_running());
  17913. });
  17914. svr.wait_until_ready();
  17915. Client cli(HOST, port);
  17916. auto res = cli.Get(pattern);
  17917. ASSERT_TRUE(res);
  17918. EXPECT_EQ(StatusCode::OK_200, res->status);
  17919. }
  17920. TEST(ParseUrlTest, VariousPatterns) {
  17921. {
  17922. detail::UrlComponents uc;
  17923. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17924. EXPECT_EQ("http", uc.scheme);
  17925. EXPECT_EQ("example.com", uc.host);
  17926. EXPECT_EQ("8080", uc.port);
  17927. EXPECT_EQ("/path", uc.path);
  17928. EXPECT_EQ("?q=1", uc.query);
  17929. }
  17930. {
  17931. detail::UrlComponents uc;
  17932. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17933. EXPECT_EQ("https", uc.scheme);
  17934. EXPECT_EQ("example.com", uc.host);
  17935. EXPECT_TRUE(uc.port.empty());
  17936. EXPECT_EQ("/path", uc.path);
  17937. }
  17938. {
  17939. detail::UrlComponents uc;
  17940. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17941. EXPECT_EQ("::1", uc.host);
  17942. EXPECT_EQ("8080", uc.port);
  17943. EXPECT_EQ("/path", uc.path);
  17944. }
  17945. {
  17946. detail::UrlComponents uc;
  17947. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17948. }
  17949. {
  17950. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17951. // the path while the connection still targets the bracketed host.
  17952. detail::UrlComponents uc;
  17953. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17954. }
  17955. {
  17956. detail::UrlComponents uc;
  17957. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17958. }
  17959. {
  17960. detail::UrlComponents uc;
  17961. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17962. EXPECT_EQ("::1", uc.host);
  17963. EXPECT_TRUE(uc.port.empty());
  17964. EXPECT_EQ("/path", uc.path);
  17965. }
  17966. {
  17967. detail::UrlComponents uc;
  17968. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17969. EXPECT_TRUE(uc.scheme.empty());
  17970. EXPECT_EQ("example.com", uc.host);
  17971. EXPECT_EQ("/path", uc.path);
  17972. EXPECT_EQ("?q=1", uc.query);
  17973. }
  17974. {
  17975. detail::UrlComponents uc;
  17976. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17977. EXPECT_TRUE(uc.host.empty());
  17978. EXPECT_EQ("/path", uc.path);
  17979. EXPECT_EQ("?q=1", uc.query);
  17980. }
  17981. {
  17982. detail::UrlComponents uc;
  17983. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17984. EXPECT_EQ("example.com", uc.host);
  17985. EXPECT_EQ("8080", uc.port);
  17986. }
  17987. {
  17988. // Unix socket path — must not be parsed as host
  17989. detail::UrlComponents uc;
  17990. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17991. EXPECT_TRUE(uc.host.empty());
  17992. }
  17993. {
  17994. detail::UrlComponents uc;
  17995. ASSERT_TRUE(detail::parse_url("", uc));
  17996. EXPECT_TRUE(uc.host.empty());
  17997. EXPECT_TRUE(uc.path.empty());
  17998. }
  17999. {
  18000. detail::UrlComponents uc;
  18001. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18002. }
  18003. {
  18004. detail::UrlComponents uc;
  18005. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18006. }
  18007. {
  18008. // Accepted by parse_url; callers restrict to http/https
  18009. detail::UrlComponents uc;
  18010. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18011. EXPECT_EQ("ftp", uc.scheme);
  18012. }
  18013. {
  18014. detail::UrlComponents uc;
  18015. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18016. }
  18017. {
  18018. detail::UrlComponents uc;
  18019. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18020. }
  18021. }
  18022. TEST(ParseUrlTest, FragmentHandling) {
  18023. {
  18024. detail::UrlComponents uc;
  18025. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18026. EXPECT_EQ("/path", uc.path);
  18027. EXPECT_TRUE(uc.query.empty());
  18028. }
  18029. {
  18030. detail::UrlComponents uc;
  18031. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18032. EXPECT_TRUE(uc.path.empty());
  18033. EXPECT_TRUE(uc.query.empty());
  18034. }
  18035. }
  18036. TEST(ParseUrlTest, UserinfoHandling) {
  18037. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18038. // parsers would see evil.com as the host.
  18039. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18040. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18041. for (auto url : urls) {
  18042. detail::UrlComponents uc;
  18043. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18044. }
  18045. }
  18046. TEST(ParseUrlTest, IPv6EdgeCases) {
  18047. {
  18048. detail::UrlComponents uc;
  18049. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18050. EXPECT_TRUE(uc.scheme.empty());
  18051. EXPECT_EQ("::1", uc.host);
  18052. EXPECT_EQ("8080", uc.port);
  18053. }
  18054. {
  18055. // Zone ID '%25' is not in [a-fA-F0-9:]
  18056. detail::UrlComponents uc;
  18057. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18058. }
  18059. }
  18060. TEST(ParseUrlTest, SchemeEdgeCases) {
  18061. {
  18062. detail::UrlComponents uc;
  18063. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18064. }
  18065. {
  18066. detail::UrlComponents uc;
  18067. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18068. }
  18069. {
  18070. detail::UrlComponents uc;
  18071. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18072. }
  18073. }
  18074. TEST(ParseUrlTest, PortEdgeCases) {
  18075. {
  18076. detail::UrlComponents uc;
  18077. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18078. EXPECT_TRUE(uc.port.empty());
  18079. EXPECT_EQ("/path", uc.path);
  18080. }
  18081. {
  18082. // parse_url accepts any port string; validation is done by parse_port
  18083. detail::UrlComponents uc;
  18084. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18085. EXPECT_EQ("abc", uc.port);
  18086. }
  18087. }
  18088. TEST(ParseUrlTest, WebSocketPatterns) {
  18089. {
  18090. detail::UrlComponents uc;
  18091. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18092. EXPECT_EQ("ws", uc.scheme);
  18093. EXPECT_EQ("echo.example.com", uc.host);
  18094. EXPECT_EQ("8080", uc.port);
  18095. EXPECT_EQ("/ws", uc.path);
  18096. }
  18097. {
  18098. detail::UrlComponents uc;
  18099. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18100. EXPECT_EQ("wss", uc.scheme);
  18101. EXPECT_EQ("echo.example.com", uc.host);
  18102. EXPECT_TRUE(uc.port.empty());
  18103. EXPECT_EQ("/ws", uc.path);
  18104. }
  18105. }
  18106. TEST(ParseUrlTest, QueryOnly) {
  18107. detail::UrlComponents uc;
  18108. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18109. EXPECT_TRUE(uc.host.empty());
  18110. EXPECT_TRUE(uc.path.empty());
  18111. EXPECT_EQ("?q=1&r=2", uc.query);
  18112. }
  18113. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18114. detail::UrlComponents uc;
  18115. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18116. EXPECT_TRUE(uc.scheme.empty());
  18117. EXPECT_EQ("example.com", uc.host);
  18118. EXPECT_EQ("443", uc.port);
  18119. EXPECT_EQ("/path", uc.path);
  18120. }
  18121. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18122. // If ipv6 regex working, regex match codepath is taken.
  18123. // else port will default to 80 in Client impl
  18124. int clientImplMagicPort = 80;
  18125. int port = 4321;
  18126. // above ports must be different to avoid false negative
  18127. EXPECT_NE(clientImplMagicPort, port);
  18128. std::string ipV6TestURL = "http://[ff06::c3]";
  18129. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18130. CLIENT_PRIVATE_KEY_FILE);
  18131. EXPECT_EQ(cli.port(), port);
  18132. }
  18133. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18134. auto file_path = "./www/dir/index.html";
  18135. auto dir_path = "./www/dir";
  18136. detail::FileStat stat_file(file_path);
  18137. EXPECT_TRUE(stat_file.is_file());
  18138. EXPECT_FALSE(stat_file.is_dir());
  18139. detail::FileStat stat_dir(dir_path);
  18140. EXPECT_FALSE(stat_dir.is_file());
  18141. EXPECT_TRUE(stat_dir.is_dir());
  18142. }
  18143. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18144. // IPv4 with default HTTP port (80)
  18145. EXPECT_EQ("example.com",
  18146. detail::make_host_and_port_string("example.com", 80, false));
  18147. // IPv4 with default HTTPS port (443)
  18148. EXPECT_EQ("example.com",
  18149. detail::make_host_and_port_string("example.com", 443, true));
  18150. // IPv4 with non-default HTTP port
  18151. EXPECT_EQ("example.com:8080",
  18152. detail::make_host_and_port_string("example.com", 8080, false));
  18153. // IPv4 with non-default HTTPS port
  18154. EXPECT_EQ("example.com:8443",
  18155. detail::make_host_and_port_string("example.com", 8443, true));
  18156. // IPv6 with default HTTP port (80)
  18157. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18158. // IPv6 with default HTTPS port (443)
  18159. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18160. // IPv6 with non-default HTTP port
  18161. EXPECT_EQ("[::1]:8080",
  18162. detail::make_host_and_port_string("::1", 8080, false));
  18163. // IPv6 with non-default HTTPS port
  18164. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18165. // IPv6 full address with default port
  18166. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18167. detail::make_host_and_port_string(
  18168. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18169. // IPv6 full address with non-default port
  18170. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18171. detail::make_host_and_port_string(
  18172. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18173. // IPv6 localhost with non-default port
  18174. EXPECT_EQ("[::1]:3000",
  18175. detail::make_host_and_port_string("::1", 3000, false));
  18176. // IPv6 with zone ID (link-local address) with default port
  18177. EXPECT_EQ("[fe80::1%eth0]",
  18178. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18179. // IPv6 with zone ID (link-local address) with non-default port
  18180. EXPECT_EQ("[fe80::1%eth0]:8080",
  18181. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18182. // Edge case: Port 443 with is_ssl=false (should add port)
  18183. EXPECT_EQ("example.com:443",
  18184. detail::make_host_and_port_string("example.com", 443, false));
  18185. // Edge case: Port 80 with is_ssl=true (should add port)
  18186. EXPECT_EQ("example.com:80",
  18187. detail::make_host_and_port_string("example.com", 80, true));
  18188. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18189. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18190. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18191. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18192. // Security fix: Already bracketed IPv6 should not get double brackets
  18193. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18194. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18195. EXPECT_EQ("[::1]:8080",
  18196. detail::make_host_and_port_string("[::1]", 8080, false));
  18197. EXPECT_EQ("[2001:db8::1]:8080",
  18198. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18199. EXPECT_EQ("[fe80::1%eth0]",
  18200. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18201. EXPECT_EQ("[fe80::1%eth0]:8080",
  18202. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18203. // Edge case: Empty host (should return as-is)
  18204. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18205. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18206. // This is a known limitation but shouldn't crash
  18207. EXPECT_EQ("[host:name]",
  18208. detail::make_host_and_port_string("host:name", 80, false));
  18209. // Port number edge cases (no validation, but should not crash)
  18210. EXPECT_EQ("example.com:0",
  18211. detail::make_host_and_port_string("example.com", 0, false));
  18212. EXPECT_EQ("example.com:-1",
  18213. detail::make_host_and_port_string("example.com", -1, false));
  18214. EXPECT_EQ("example.com:65535",
  18215. detail::make_host_and_port_string("example.com", 65535, false));
  18216. EXPECT_EQ("example.com:65536",
  18217. detail::make_host_and_port_string("example.com", 65536, false));
  18218. }
  18219. namespace httplib {
  18220. namespace detail {
  18221. std::string
  18222. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18223. const std::string &host, int port);
  18224. } // namespace detail
  18225. } // namespace httplib
  18226. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18227. std::map<std::string, std::string> addr_map = {
  18228. {"ipv4.example", "192.0.2.10"},
  18229. {"ipv6.example", "2001:db8::1"},
  18230. {"name.example", "internal.example.lan"},
  18231. {"empty.example", ""}};
  18232. EXPECT_EQ("192.0.2.10:443",
  18233. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18234. EXPECT_EQ("[2001:db8::1]:443",
  18235. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18236. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18237. addr_map, "name.example", 8443));
  18238. // An empty or absent mapping keeps the hostname as the target
  18239. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18240. addr_map, "empty.example", 443));
  18241. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18242. addr_map, "other.example", 443));
  18243. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18244. }
  18245. #ifdef CPPHTTPLIB_SSL_ENABLED
  18246. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18247. httplib::SSLClient cli("roblox.com", 443);
  18248. cli.set_follow_location(true);
  18249. auto res = cli.Get("/");
  18250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18251. EXPECT_EQ(StatusCode::OK_200, res->status);
  18252. }
  18253. #endif
  18254. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18255. Server svr;
  18256. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18257. EXPECT_EQ(res.status, 400);
  18258. });
  18259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18260. auto se = detail::scope_exit([&] {
  18261. svr.stop();
  18262. thread.join();
  18263. ASSERT_FALSE(svr.is_running());
  18264. });
  18265. svr.wait_until_ready();
  18266. Client cli(HOST, PORT);
  18267. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18268. }
  18269. TEST(InvalidHeaderCharsTest, is_field_name) {
  18270. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18271. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18272. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18273. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18274. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18275. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18276. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18277. EXPECT_FALSE(detail::fields::is_field_name(""));
  18278. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18279. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18280. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18281. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18282. }
  18283. TEST(InvalidHeaderCharsTest, is_field_value) {
  18284. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18285. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18286. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18287. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18288. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18289. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18290. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18291. EXPECT_TRUE(detail::fields::is_field_value(""));
  18292. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18293. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18294. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18295. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18296. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18297. }
  18298. TEST(InvalidHeaderCharsTest, OnServer) {
  18299. Server svr;
  18300. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18301. std::string header = "Not Set";
  18302. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18303. res.set_header(header, "value");
  18304. res.set_content("Page Content Page Content", "text/plain");
  18305. });
  18306. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18307. std::string header = "Not Set";
  18308. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18309. res.set_header("X-Test", header);
  18310. res.set_content("Page Content Page Content", "text/plain");
  18311. });
  18312. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18313. auto se = detail::scope_exit([&] {
  18314. svr.stop();
  18315. thread.join();
  18316. ASSERT_FALSE(svr.is_running());
  18317. });
  18318. svr.wait_until_ready();
  18319. Client cli(HOST, PORT);
  18320. {
  18321. auto res = cli.Get(
  18322. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18324. EXPECT_EQ("Page Content Page Content", res->body);
  18325. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18326. }
  18327. {
  18328. auto res = cli.Get(
  18329. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18331. EXPECT_EQ("Page Content Page Content", res->body);
  18332. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18333. }
  18334. }
  18335. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18336. auto handled = false;
  18337. Server svr;
  18338. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18339. thread t = thread([&] { svr.listen(HOST, PORT); });
  18340. auto se = detail::scope_exit([&] {
  18341. svr.stop();
  18342. t.join();
  18343. ASSERT_FALSE(svr.is_running());
  18344. ASSERT_FALSE(handled);
  18345. });
  18346. svr.wait_until_ready();
  18347. auto req = "POST /test HTTP/1.1\r\n"
  18348. "Content-Length: x\r\n"
  18349. "\r\n";
  18350. std::string response;
  18351. ASSERT_TRUE(send_request(1, req, &response));
  18352. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18353. response.substr(0, response.find("\r\n")));
  18354. }
  18355. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18356. // case-insensitive, and a server that receives a 100-continue expectation in
  18357. // an HTTP/1.0 request MUST ignore it.
  18358. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18359. std::string response;
  18360. ASSERT_TRUE(send_request(1, req, &response, port));
  18361. *got_100 = response.find("100 Continue") != std::string::npos;
  18362. }
  18363. class ExpectTokenTest : public ::testing::Test {
  18364. protected:
  18365. void SetUp() override {
  18366. svr_.Post("/p", [](const Request &, Response &res) {
  18367. res.set_content("ok", "text/plain");
  18368. });
  18369. port_ = svr_.bind_to_any_port(HOST);
  18370. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18371. svr_.wait_until_ready();
  18372. }
  18373. void TearDown() override {
  18374. svr_.stop();
  18375. if (thread_.joinable()) { thread_.join(); }
  18376. }
  18377. std::string request(const char *version, const char *expect_value) const {
  18378. return std::string("POST /p ") + version +
  18379. "\r\n"
  18380. "Host: localhost\r\n"
  18381. "Content-Length: 2\r\n"
  18382. "Connection: close\r\n"
  18383. "Expect: " +
  18384. expect_value +
  18385. "\r\n"
  18386. "\r\n"
  18387. "hi";
  18388. }
  18389. Server svr_;
  18390. int port_ = 0;
  18391. thread thread_;
  18392. };
  18393. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18394. bool got_100 = false;
  18395. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18396. EXPECT_TRUE(got_100);
  18397. }
  18398. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18399. bool got_100 = true;
  18400. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18401. EXPECT_FALSE(got_100);
  18402. }
  18403. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18404. bool got_100 = false;
  18405. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18406. EXPECT_TRUE(got_100);
  18407. }
  18408. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18409. bool got_100 = false;
  18410. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18411. EXPECT_TRUE(got_100);
  18412. }
  18413. // `100 Continue` is sent only when the server starts reading the body, so a
  18414. // request rejected before that never invites the client to send it. The
  18415. // requests below carry the expectation but withhold the body, as a client
  18416. // waiting for `100 Continue` would.
  18417. // A POST that expects `100 Continue` and withholds its two-byte body.
  18418. static std::string expect_headers_only(const std::string &path) {
  18419. return "POST " + path +
  18420. " HTTP/1.1\r\n"
  18421. "Host: localhost\r\n"
  18422. "Content-Length: 2\r\n"
  18423. "Expect: 100-continue\r\n"
  18424. "\r\n";
  18425. }
  18426. class ExpectLazyContinueTest : public ::testing::Test {
  18427. protected:
  18428. void SetUp() override {
  18429. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18430. if (req.path == "/pre-routing") {
  18431. res.status = StatusCode::Unauthorized_401;
  18432. return Server::HandlerResponse::Handled;
  18433. }
  18434. return Server::HandlerResponse::Unhandled;
  18435. });
  18436. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18437. if (req.matched_route == "/pre-request") {
  18438. res.status = StatusCode::Forbidden_403;
  18439. return Server::HandlerResponse::Handled;
  18440. }
  18441. return Server::HandlerResponse::Unhandled;
  18442. });
  18443. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18444. res.set_content("ok", "text/plain");
  18445. });
  18446. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18447. res.set_content("ok", "text/plain");
  18448. });
  18449. svr_.Post("/reader-used", [](const Request &, Response &res,
  18450. const ContentReader &content_reader) {
  18451. std::string body;
  18452. content_reader([&](const char *data, size_t len) {
  18453. body.append(data, len);
  18454. return true;
  18455. });
  18456. res.set_content(body, "text/plain");
  18457. });
  18458. svr_.Post("/reader-unused",
  18459. [](const Request &, Response &res, const ContentReader &) {
  18460. res.set_content("ignored", "text/plain");
  18461. });
  18462. port_ = svr_.bind_to_any_port(HOST);
  18463. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18464. svr_.wait_until_ready();
  18465. }
  18466. void TearDown() override {
  18467. svr_.stop();
  18468. if (thread_.joinable()) { thread_.join(); }
  18469. }
  18470. // Sends `req` and reads until the server closes the connection. Returns
  18471. // false if the read had to wait for the client-side timeout instead.
  18472. bool send_until_closed(const std::string &req, std::string *resp) const {
  18473. auto start = std::chrono::steady_clock::now();
  18474. if (!send_request(3, req, resp, port_)) { return false; }
  18475. auto elapsed = std::chrono::steady_clock::now() - start;
  18476. return elapsed < std::chrono::seconds(2);
  18477. }
  18478. // The final response comes without `100 Continue`, and the server closes
  18479. // the connection since the body may or may not follow.
  18480. void expect_final_without_interim(const std::string &path,
  18481. const char *status_line) const {
  18482. std::string resp;
  18483. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18484. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18485. EXPECT_EQ(0u, resp.find(status_line));
  18486. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18487. }
  18488. Server svr_;
  18489. int port_ = 0;
  18490. thread thread_;
  18491. };
  18492. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18493. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18494. }
  18495. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18496. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18497. }
  18498. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18499. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18500. }
  18501. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18502. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18503. }
  18504. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18505. // The body follows once `100 Continue` has had time to arrive.
  18506. auto req = expect_headers_only("/reader-used");
  18507. req.insert(req.size() - 2, "Connection: close\r\n");
  18508. std::string resp;
  18509. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18510. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18511. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18512. EXPECT_NE(std::string::npos, resp.find("hi"));
  18513. }
  18514. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18515. // Large enough for the client to add `Expect: 100-continue` itself.
  18516. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18517. std::atomic<bool> body_sent{false};
  18518. Client cli(HOST, port_);
  18519. auto res = cli.Post(
  18520. "/pre-request", length,
  18521. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18522. body_sent = true;
  18523. std::string chunk(len, 'x');
  18524. sink.write(chunk.data(), chunk.size());
  18525. return true;
  18526. },
  18527. "application/octet-stream");
  18528. ASSERT_TRUE(res);
  18529. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18530. EXPECT_FALSE(body_sent);
  18531. }
  18532. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18533. Server svr;
  18534. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18535. return StatusCode::ExpectationFailed_417;
  18536. });
  18537. svr.Post("/p", [](const Request &, Response &res) {
  18538. res.set_content("ok", "text/plain");
  18539. });
  18540. auto port = svr.bind_to_any_port(HOST);
  18541. thread t = thread([&] { svr.listen_after_bind(); });
  18542. auto se = detail::scope_exit([&] {
  18543. svr.stop();
  18544. t.join();
  18545. });
  18546. svr.wait_until_ready();
  18547. std::string resp;
  18548. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18549. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18550. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18551. // Exactly one response: the route handler must not run after the 417.
  18552. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18553. }
  18554. #ifndef _WIN32
  18555. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18556. static constexpr char reject[] = "Unauthorized";
  18557. static constexpr char accept[] = "Upload accepted";
  18558. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18559. Server svr;
  18560. svr.set_expect_100_continue_handler(
  18561. [](const Request & /*req*/, Response &res) {
  18562. res.status = StatusCode::Unauthorized_401;
  18563. res.set_content(reject, "text/plain");
  18564. return res.status;
  18565. });
  18566. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18567. res.set_content(accept, "text/plain");
  18568. });
  18569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18570. auto se = detail::scope_exit([&] {
  18571. svr.stop();
  18572. thread.join();
  18573. ASSERT_FALSE(svr.is_running());
  18574. });
  18575. svr.wait_until_ready();
  18576. {
  18577. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18578. curl_easy_init(), &curl_easy_cleanup};
  18579. ASSERT_NE(curl, nullptr);
  18580. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18581. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18582. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18583. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18584. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18585. &curl_slist_free_all};
  18586. ASSERT_NE(list, nullptr);
  18587. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18588. struct read_data {
  18589. uint64_t read_size;
  18590. uint64_t total_size;
  18591. } data = {0, total_size};
  18592. using read_callback_t =
  18593. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18594. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18595. void *userdata) -> size_t {
  18596. read_data *d = (read_data *)userdata;
  18597. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18598. std::fill_n(ptr, size * nmemb, 'A');
  18599. d->read_size += size * nmemb;
  18600. return size * nmemb;
  18601. };
  18602. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18603. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18604. std::vector<char> buffer;
  18605. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18606. using write_callback_t =
  18607. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18608. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18609. void *userdata) -> size_t {
  18610. std::vector<char> *buf = (std::vector<char> *)userdata;
  18611. buf->reserve(buf->size() + size * nmemb + 1);
  18612. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18613. return size * nmemb;
  18614. };
  18615. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18616. {
  18617. const auto res = curl_easy_perform(curl.get());
  18618. ASSERT_EQ(res, CURLE_OK);
  18619. }
  18620. {
  18621. auto response_code = long{};
  18622. const auto res =
  18623. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18624. ASSERT_EQ(res, CURLE_OK);
  18625. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18626. }
  18627. {
  18628. auto dl = curl_off_t{};
  18629. const auto res =
  18630. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18631. ASSERT_EQ(res, CURLE_OK);
  18632. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18633. }
  18634. {
  18635. buffer.push_back('\0');
  18636. ASSERT_STRCASEEQ(buffer.data(), reject);
  18637. }
  18638. }
  18639. }
  18640. #endif
  18641. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18642. // Regression test for #2458.
  18643. //
  18644. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18645. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18646. // ticket can make the client socket spuriously readable during the
  18647. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18648. // the client withholds the body and then blocks reading a response that never
  18649. // comes, failing with `Failed to read connection`.
  18650. //
  18651. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18652. // within the timeout. This raw OpenSSL server deliberately never sends
  18653. // `100 Continue`; the client must still deliver the body and receive 200.
  18654. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18655. signal(SIGPIPE, SIG_IGN);
  18656. const auto port = PORT + 4;
  18657. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18658. ASSERT_NE(srv, INVALID_SOCKET);
  18659. int opt = 1;
  18660. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18661. sockaddr_in addr{};
  18662. addr.sin_family = AF_INET;
  18663. addr.sin_port = htons(static_cast<uint16_t>(port));
  18664. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18665. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18666. ASSERT_EQ(0, ::listen(srv, 1));
  18667. std::atomic<size_t> server_body_bytes{0};
  18668. auto server_thread = std::thread([&] {
  18669. sockaddr_in cli_addr{};
  18670. socklen_t cli_len = sizeof(cli_addr);
  18671. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18672. if (cli == INVALID_SOCKET) { return; }
  18673. // Bound the lifetime of the server side so a buggy client (which never
  18674. // sends the body) cannot make this thread block forever on join.
  18675. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18676. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18677. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18678. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18679. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18680. SSL *ssl = SSL_new(ctx);
  18681. SSL_set_fd(ssl, static_cast<int>(cli));
  18682. if (SSL_accept(ssl) > 0) {
  18683. // Read the request headers. Reading here also flushes the TLS 1.3
  18684. // session tickets to the client. Deliberately do NOT send
  18685. // `100 Continue`.
  18686. std::string buf;
  18687. char tmp[1024];
  18688. while (buf.find("\r\n\r\n") == std::string::npos) {
  18689. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18690. if (n <= 0) { break; }
  18691. buf.append(tmp, static_cast<size_t>(n));
  18692. }
  18693. // A correct client sends the body now; count what arrives.
  18694. auto pos = buf.find("\r\n\r\n");
  18695. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18696. while (body < 4096) {
  18697. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18698. if (n <= 0) { break; }
  18699. body += static_cast<size_t>(n);
  18700. }
  18701. server_body_bytes = body;
  18702. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18703. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18704. SSL_shutdown(ssl);
  18705. }
  18706. SSL_free(ssl);
  18707. detail::close_socket(cli);
  18708. SSL_CTX_free(ctx);
  18709. });
  18710. auto se = detail::scope_exit([&] {
  18711. server_thread.join();
  18712. detail::close_socket(srv);
  18713. });
  18714. SSLClient cli("127.0.0.1", port);
  18715. cli.enable_server_certificate_verification(false);
  18716. cli.set_connection_timeout(5, 0);
  18717. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18718. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18719. std::string body(4096, 'A');
  18720. auto res = cli.Put("/api/test", body, "application/json");
  18721. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18722. EXPECT_EQ(StatusCode::OK_200, res->status);
  18723. EXPECT_EQ(body.size(), server_body_bytes.load());
  18724. }
  18725. #endif
  18726. template <typename S, typename C>
  18727. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18728. svr.Get("/stream", [&](const Request &, Response &res) {
  18729. auto data = new std::string("01234567890123456789");
  18730. res.set_content_provider(
  18731. data->size(), "text/plain",
  18732. [&, data](size_t offset, size_t length, DataSink &sink) {
  18733. const size_t DATA_CHUNK_SIZE = 4;
  18734. const auto &d = *data;
  18735. std::this_thread::sleep_for(std::chrono::seconds(1));
  18736. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18737. return true;
  18738. },
  18739. [data](bool success) {
  18740. EXPECT_FALSE(success);
  18741. delete data;
  18742. });
  18743. });
  18744. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18745. auto i = new size_t(0);
  18746. res.set_content_provider(
  18747. "text/plain",
  18748. [i](size_t, DataSink &sink) {
  18749. if (*i < 5) {
  18750. std::this_thread::sleep_for(std::chrono::seconds(1));
  18751. sink.write("abcd", 4);
  18752. (*i)++;
  18753. } else {
  18754. sink.done();
  18755. }
  18756. return true;
  18757. },
  18758. [i](bool success) {
  18759. EXPECT_FALSE(success);
  18760. delete i;
  18761. });
  18762. });
  18763. svr.Get("/chunked", [&](const Request &, Response &res) {
  18764. auto i = new size_t(0);
  18765. res.set_chunked_content_provider(
  18766. "text/plain",
  18767. [i](size_t, DataSink &sink) {
  18768. if (*i < 5) {
  18769. std::this_thread::sleep_for(std::chrono::seconds(1));
  18770. sink.os << "abcd";
  18771. (*i)++;
  18772. } else {
  18773. sink.done();
  18774. }
  18775. return true;
  18776. },
  18777. [i](bool success) {
  18778. EXPECT_FALSE(success);
  18779. delete i;
  18780. });
  18781. });
  18782. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. listen_thread.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18790. {
  18791. auto start = std::chrono::steady_clock::now();
  18792. auto res = cli.Get("/stream");
  18793. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18794. std::chrono::steady_clock::now() - start)
  18795. .count();
  18796. ASSERT_FALSE(res);
  18797. EXPECT_EQ(Error::Read, res.error());
  18798. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18799. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18800. }
  18801. {
  18802. auto start = std::chrono::steady_clock::now();
  18803. auto res = cli.Get("/stream_without_length");
  18804. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18805. std::chrono::steady_clock::now() - start)
  18806. .count();
  18807. ASSERT_FALSE(res);
  18808. EXPECT_EQ(Error::Read, res.error());
  18809. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18810. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18811. }
  18812. {
  18813. auto start = std::chrono::steady_clock::now();
  18814. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18815. EXPECT_EQ("abcd", string(data, data_length));
  18816. return true;
  18817. });
  18818. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18819. std::chrono::steady_clock::now() - start)
  18820. .count();
  18821. ASSERT_FALSE(res);
  18822. EXPECT_EQ(Error::Read, res.error());
  18823. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18824. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18825. }
  18826. }
  18827. TEST(MaxTimeoutTest, ContentStream) {
  18828. time_t timeout = 2000;
  18829. time_t threshold = 200;
  18830. Server svr;
  18831. Client cli("localhost", PORT);
  18832. max_timeout_test(svr, cli, timeout, threshold);
  18833. }
  18834. #ifdef CPPHTTPLIB_SSL_ENABLED
  18835. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18836. time_t timeout = 2000;
  18837. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18839. SSLClient cli("localhost", PORT);
  18840. cli.enable_server_certificate_verification(false);
  18841. max_timeout_test(svr, cli, timeout, threshold);
  18842. }
  18843. #endif
  18844. class EventDispatcher {
  18845. public:
  18846. EventDispatcher() {}
  18847. bool wait_event(DataSink *sink) {
  18848. unique_lock<mutex> lk(m_);
  18849. int id = id_;
  18850. // Wait with timeout to prevent hanging if client disconnects
  18851. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18852. [&] { return cid_ == id; })) {
  18853. return false; // Timeout occurred
  18854. }
  18855. sink->write(message_.data(), message_.size());
  18856. return true;
  18857. }
  18858. void send_event(const string &message) {
  18859. lock_guard<mutex> lk(m_);
  18860. cid_ = id_++;
  18861. message_ = message;
  18862. cv_.notify_all();
  18863. }
  18864. private:
  18865. mutex m_;
  18866. condition_variable cv_;
  18867. atomic_int id_{0};
  18868. atomic_int cid_{-1};
  18869. string message_;
  18870. };
  18871. TEST(ClientInThreadTest, Issue2068) {
  18872. EventDispatcher ed;
  18873. Server svr;
  18874. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18875. res.set_chunked_content_provider("text/event-stream",
  18876. [&](size_t /*offset*/, DataSink &sink) {
  18877. return ed.wait_event(&sink);
  18878. });
  18879. });
  18880. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18881. svr.wait_until_ready();
  18882. thread event_thread([&] {
  18883. int id = 0;
  18884. while (svr.is_running()) {
  18885. this_thread::sleep_for(chrono::milliseconds(500));
  18886. std::stringstream ss;
  18887. ss << "data: " << id << "\n\n";
  18888. ed.send_event(ss.str());
  18889. id++;
  18890. }
  18891. });
  18892. auto se = detail::scope_exit([&] {
  18893. svr.stop();
  18894. listen_thread.join();
  18895. event_thread.join();
  18896. ASSERT_FALSE(svr.is_running());
  18897. });
  18898. {
  18899. auto client = detail::make_unique<Client>(HOST, PORT);
  18900. client->set_read_timeout(std::chrono::minutes(10));
  18901. std::atomic<bool> stop{false};
  18902. std::thread t([&] {
  18903. client->Get("/event1",
  18904. [&](const char *, size_t) -> bool { return !stop; });
  18905. });
  18906. std::this_thread::sleep_for(std::chrono::seconds(2));
  18907. stop = true;
  18908. client->stop();
  18909. t.join();
  18910. // Reset client after thread has finished
  18911. client.reset();
  18912. }
  18913. }
  18914. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18915. auto handled = false;
  18916. Server svr;
  18917. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18918. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18919. auto se = detail::scope_exit([&] {
  18920. svr.stop();
  18921. t.join();
  18922. ASSERT_FALSE(svr.is_running());
  18923. ASSERT_FALSE(handled);
  18924. });
  18925. svr.wait_until_ready();
  18926. // Two Content-Length headers with different values — must be rejected
  18927. auto req = "POST /test HTTP/1.1\r\n"
  18928. "Content-Length: 5\r\n"
  18929. "Content-Length: 10\r\n"
  18930. "\r\n"
  18931. "hello";
  18932. std::string response;
  18933. ASSERT_TRUE(send_request(1, req, &response));
  18934. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18935. response.substr(0, response.find("\r\n")));
  18936. }
  18937. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18938. auto handled = false;
  18939. Server svr;
  18940. svr.Post("/test", [&](const Request &, Response &res) {
  18941. handled = true;
  18942. res.set_content("ok", "text/plain");
  18943. });
  18944. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18945. auto se = detail::scope_exit([&] {
  18946. svr.stop();
  18947. t.join();
  18948. ASSERT_FALSE(svr.is_running());
  18949. ASSERT_TRUE(handled);
  18950. });
  18951. svr.wait_until_ready();
  18952. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18953. auto req = "POST /test HTTP/1.1\r\n"
  18954. "Host: localhost\r\n"
  18955. "Content-Length: 5\r\n"
  18956. "Content-Length: 5\r\n"
  18957. "\r\n"
  18958. "hello";
  18959. std::string response;
  18960. ASSERT_TRUE(send_request(1, req, &response));
  18961. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18962. }
  18963. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18964. Server svr;
  18965. svr.Get("/test", [](const Request &, Response &res) {
  18966. res.set_content("ok", "text/plain");
  18967. });
  18968. auto port = svr.bind_to_any_port(HOST);
  18969. thread t = thread([&] { svr.listen_after_bind(); });
  18970. auto se = detail::scope_exit([&] {
  18971. svr.stop();
  18972. t.join();
  18973. ASSERT_FALSE(svr.is_running());
  18974. });
  18975. svr.wait_until_ready();
  18976. auto status_line = [&](const std::string &host_lines) {
  18977. std::string res;
  18978. send_request(
  18979. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18980. &res, port);
  18981. return res.substr(0, res.find("\r\n"));
  18982. };
  18983. const char *accepted[] = {
  18984. "Host: localhost\r\n",
  18985. "Host: a.example:8080\r\n",
  18986. "Host: my_service\r\n",
  18987. "Host: [::1]:8080\r\n",
  18988. "Host: [fe80::1%25eth0]\r\n",
  18989. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18990. };
  18991. for (auto host_lines : accepted) {
  18992. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18993. }
  18994. const char *rejected[] = {
  18995. "Host: a.example\r\nHost: b.example\r\n",
  18996. "Host: a.example\r\nHost: a.example\r\n",
  18997. "Host: a@b.example\r\n",
  18998. "Host: a.example/b\r\n",
  18999. "Host: a.example\\b\r\n",
  19000. "Host: a.example?b\r\n",
  19001. "Host: a.example#b\r\n",
  19002. "Host: a.example b.example\r\n",
  19003. };
  19004. for (auto host_lines : rejected) {
  19005. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19006. << host_lines;
  19007. }
  19008. }
  19009. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19010. Server svr;
  19011. svr.Get("/", [](const Request &req, Response &res) {
  19012. EXPECT_EQ(2U, req.trailers.size());
  19013. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19014. // Denied
  19015. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19016. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19017. // Accepted
  19018. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19019. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19020. EXPECT_TRUE(req.has_trailer("X-World"));
  19021. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19022. res.set_content("ok", "text/plain");
  19023. });
  19024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19025. auto se = detail::scope_exit([&] {
  19026. svr.stop();
  19027. t.join();
  19028. ASSERT_FALSE(svr.is_running());
  19029. });
  19030. svr.wait_until_ready();
  19031. const std::string req = "GET / HTTP/1.1\r\n"
  19032. "Transfer-Encoding: chunked\r\n"
  19033. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19034. "\r\n"
  19035. "0\r\n"
  19036. "Content-Length: 10\r\n"
  19037. "Host: internal.local\r\n"
  19038. "Content-Type: malicious/content\r\n"
  19039. "Cookie: any\r\n"
  19040. "Set-Cookie: any\r\n"
  19041. "X-Forwarded-For: attacker.com\r\n"
  19042. "X-Real-Ip: 1.1.1.1\r\n"
  19043. "X-Hello: hello\r\n"
  19044. "X-World: world\r\n"
  19045. "\r\n";
  19046. std::string res;
  19047. ASSERT_TRUE(send_request(1, req, &res));
  19048. }
  19049. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19050. // several field lines, and the combined value is what has to be parsed. A
  19051. // Trailer field split across lines therefore declares every name it lists;
  19052. // reading only the first line silently drops the trailers the later lines
  19053. // declare. The prohibited-trailer filter still applies to every line.
  19054. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19055. Server svr;
  19056. size_t observed_trailer_count = 0;
  19057. std::string observed_hello;
  19058. std::string observed_world;
  19059. bool observed_content_length = true;
  19060. svr.Get("/", [&](const Request &req, Response &res) {
  19061. observed_trailer_count = req.trailers.size();
  19062. observed_hello = req.get_trailer_value("X-Hello");
  19063. observed_world = req.get_trailer_value("X-World");
  19064. observed_content_length = req.has_trailer("Content-Length");
  19065. res.set_content("ok", "text/plain");
  19066. });
  19067. auto port = svr.bind_to_any_port(HOST);
  19068. thread t = thread([&]() { svr.listen_after_bind(); });
  19069. auto se = detail::scope_exit([&] {
  19070. svr.stop();
  19071. t.join();
  19072. ASSERT_FALSE(svr.is_running());
  19073. });
  19074. svr.wait_until_ready();
  19075. const std::string req = "GET / HTTP/1.1\r\n"
  19076. "Host: localhost\r\n"
  19077. "Transfer-Encoding: chunked\r\n"
  19078. "Trailer: X-Hello\r\n"
  19079. "Trailer: X-World, Content-Length\r\n"
  19080. "\r\n"
  19081. "0\r\n"
  19082. "X-Hello: hello\r\n"
  19083. "X-World: world\r\n"
  19084. "Content-Length: 10\r\n"
  19085. "\r\n";
  19086. std::string res;
  19087. ASSERT_TRUE(send_request(1, req, &res, port));
  19088. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19089. // Accepted: both field lines contribute to the declared set
  19090. EXPECT_EQ(2U, observed_trailer_count);
  19091. EXPECT_EQ(observed_hello, "hello");
  19092. EXPECT_EQ(observed_world, "world");
  19093. // Denied: a prohibited name stays prohibited on a later field line
  19094. EXPECT_FALSE(observed_content_length);
  19095. }
  19096. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19097. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19098. // unbounded run of fields that are never declared, because the counter would
  19099. // only advance for declared fields.
  19100. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19101. Server svr;
  19102. bool handler_called = false;
  19103. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19104. handler_called = true;
  19105. res.set_content("ok", "text/plain");
  19106. });
  19107. auto port = svr.bind_to_any_port(HOST);
  19108. thread t = thread([&]() { svr.listen_after_bind(); });
  19109. auto se = detail::scope_exit([&] {
  19110. svr.stop();
  19111. t.join();
  19112. ASSERT_FALSE(svr.is_running());
  19113. });
  19114. svr.wait_until_ready();
  19115. // Declare nothing, then send far more undeclared trailer fields than the
  19116. // header-count limit. Parsing must stop and reject the request rather than
  19117. // read every line.
  19118. std::string req = "GET / HTTP/1.1\r\n"
  19119. "Transfer-Encoding: chunked\r\n"
  19120. "\r\n"
  19121. "0\r\n";
  19122. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19123. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19124. }
  19125. req += "\r\n";
  19126. std::string res;
  19127. ASSERT_TRUE(send_request(1, req, &res, port));
  19128. // The request is rejected before the handler runs.
  19129. EXPECT_FALSE(handler_called);
  19130. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19131. }
  19132. // The set of declared trailer names is capped so a peer cannot grow it without
  19133. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19134. // declared past the cap is not honored, even if the field is actually sent.
  19135. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19136. Server svr;
  19137. // One name inside the cap and one past it, so the test tracks the cap rather
  19138. // than a fixed count.
  19139. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19140. const std::string within_cap_name = "X-T-0";
  19141. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19142. bool observed_within_cap = false;
  19143. bool observed_past_cap = false;
  19144. svr.Get("/", [&](const Request &req, Response &res) {
  19145. observed_within_cap = req.has_trailer(within_cap_name);
  19146. observed_past_cap = req.has_trailer(past_cap_name);
  19147. res.set_content("ok", "text/plain");
  19148. });
  19149. auto port = svr.bind_to_any_port(HOST);
  19150. thread t = thread([&]() { svr.listen_after_bind(); });
  19151. auto se = detail::scope_exit([&] {
  19152. svr.stop();
  19153. t.join();
  19154. ASSERT_FALSE(svr.is_running());
  19155. });
  19156. svr.wait_until_ready();
  19157. // Declare more trailer names than the cap in a single Trailer field, then
  19158. // actually send the first (within the cap) and the last (past it).
  19159. std::string trailer_decl = "Trailer: ";
  19160. for (int i = 0; i < declared_count; i++) {
  19161. if (i != 0) { trailer_decl += ", "; }
  19162. trailer_decl += "X-T-" + std::to_string(i);
  19163. }
  19164. trailer_decl += "\r\n";
  19165. const std::string req = "GET / HTTP/1.1\r\n"
  19166. "Host: localhost\r\n"
  19167. "Transfer-Encoding: chunked\r\n" +
  19168. trailer_decl +
  19169. "\r\n"
  19170. "0\r\n" +
  19171. within_cap_name + ": a\r\n" + past_cap_name +
  19172. ": b\r\n"
  19173. "\r\n";
  19174. std::string res;
  19175. ASSERT_TRUE(send_request(1, req, &res, port));
  19176. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19177. // A name within the cap is honored; one declared past the cap is dropped.
  19178. EXPECT_TRUE(observed_within_cap);
  19179. EXPECT_FALSE(observed_past_cap);
  19180. }
  19181. // A direct client that is not listed in trusted_proxies must not be able to
  19182. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19183. // the peer address on the actual TCP connection determines whether the
  19184. // header is honored.
  19185. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19186. Server svr;
  19187. // Deliberately does NOT include the loopback address the test client
  19188. // actually connects from, so the direct connection is not a trusted proxy.
  19189. svr.set_trusted_proxies({"203.0.113.66"});
  19190. std::string observed_remote_addr;
  19191. svr.Get("/ip", [&](const Request &req, Response &res) {
  19192. observed_remote_addr = req.remote_addr;
  19193. res.set_content("ok", "text/plain");
  19194. });
  19195. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19196. auto se = detail::scope_exit([&] {
  19197. svr.stop();
  19198. t.join();
  19199. ASSERT_FALSE(svr.is_running());
  19200. });
  19201. svr.wait_until_ready();
  19202. Client cli(HOST, PORT);
  19203. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19205. EXPECT_EQ(StatusCode::OK_200, res->status);
  19206. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19207. // ignored entirely and the real connection-level address retained.
  19208. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19209. observed_remote_addr == "127.0.0.1");
  19210. }
  19211. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19212. Server svr;
  19213. std::string observed_remote_addr;
  19214. std::string observed_xff;
  19215. svr.Get("/ip", [&](const Request &req, Response &res) {
  19216. observed_remote_addr = req.remote_addr;
  19217. observed_xff = req.get_header_value("X-Forwarded-For");
  19218. res.set_content("ok", "text/plain");
  19219. });
  19220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19221. auto se = detail::scope_exit([&] {
  19222. svr.stop();
  19223. t.join();
  19224. ASSERT_FALSE(svr.is_running());
  19225. });
  19226. svr.wait_until_ready();
  19227. Client cli(HOST, PORT);
  19228. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19230. EXPECT_EQ(StatusCode::OK_200, res->status);
  19231. EXPECT_EQ(observed_xff, "203.0.113.66");
  19232. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19233. observed_remote_addr == "127.0.0.1");
  19234. }
  19235. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19236. Server svr;
  19237. svr.set_trusted_proxies({"203.0.113.66"});
  19238. std::string observed_remote_addr;
  19239. std::string observed_xff;
  19240. svr.Get("/ip", [&](const Request &req, Response &res) {
  19241. observed_remote_addr = req.remote_addr;
  19242. observed_xff = req.get_header_value("X-Forwarded-For");
  19243. res.set_content("ok", "text/plain");
  19244. });
  19245. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19246. auto se = detail::scope_exit([&] {
  19247. svr.stop();
  19248. t.join();
  19249. ASSERT_FALSE(svr.is_running());
  19250. });
  19251. svr.wait_until_ready();
  19252. Client cli(HOST, PORT);
  19253. auto res = cli.Get("/ip");
  19254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19255. EXPECT_EQ(StatusCode::OK_200, res->status);
  19256. EXPECT_EQ(observed_xff, "");
  19257. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19258. observed_remote_addr == "127.0.0.1");
  19259. }
  19260. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19261. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19262. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19263. Server svr;
  19264. svr.set_trusted_proxies({"127.0.0.1"});
  19265. svr.Get("/ip", [](const Request &req, Response &res) {
  19266. res.set_content(req.remote_addr, "text/plain");
  19267. });
  19268. auto port = svr.bind_to_any_port("::");
  19269. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19270. thread t = thread([&] { svr.listen_after_bind(); });
  19271. auto se = detail::scope_exit([&] {
  19272. svr.stop();
  19273. t.join();
  19274. ASSERT_FALSE(svr.is_running());
  19275. });
  19276. svr.wait_until_ready();
  19277. Client cli("127.0.0.1", port);
  19278. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19280. EXPECT_EQ("198.51.100.23", res->body);
  19281. }
  19282. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19283. Server svr;
  19284. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19285. svr.Get("/ip", [](const Request &req, Response &res) {
  19286. res.set_content(req.remote_addr, "text/plain");
  19287. });
  19288. auto port = svr.bind_to_any_port(HOST);
  19289. ASSERT_GT(port, 0);
  19290. thread t = thread([&] { svr.listen_after_bind(); });
  19291. auto se = detail::scope_exit([&] {
  19292. svr.stop();
  19293. t.join();
  19294. ASSERT_FALSE(svr.is_running());
  19295. });
  19296. svr.wait_until_ready();
  19297. Client cli(HOST, port);
  19298. auto res = cli.Get(
  19299. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19301. EXPECT_EQ("198.51.100.23", res->body);
  19302. }
  19303. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19304. Server svr;
  19305. // Include the loopback address the test client actually connects from, so
  19306. // the direct connection itself is recognized as the trusted proxy hop.
  19307. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19308. std::string observed_remote_addr;
  19309. std::string observed_xff;
  19310. svr.Get("/ip", [&](const Request &req, Response &res) {
  19311. observed_remote_addr = req.remote_addr;
  19312. observed_xff = req.get_header_value("X-Forwarded-For");
  19313. res.set_content("ok", "text/plain");
  19314. });
  19315. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19316. auto se = detail::scope_exit([&] {
  19317. svr.stop();
  19318. t.join();
  19319. ASSERT_FALSE(svr.is_running());
  19320. });
  19321. svr.wait_until_ready();
  19322. Client cli(HOST, PORT);
  19323. auto res = cli.Get(
  19324. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19326. EXPECT_EQ(StatusCode::OK_200, res->status);
  19327. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19328. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19329. }
  19330. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19331. Server svr;
  19332. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19333. std::string observed_remote_addr;
  19334. std::string observed_xff;
  19335. svr.Get("/ip", [&](const Request &req, Response &res) {
  19336. observed_remote_addr = req.remote_addr;
  19337. observed_xff = req.get_header_value("X-Forwarded-For");
  19338. res.set_content("ok", "text/plain");
  19339. });
  19340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19341. auto se = detail::scope_exit([&] {
  19342. svr.stop();
  19343. t.join();
  19344. ASSERT_FALSE(svr.is_running());
  19345. });
  19346. svr.wait_until_ready();
  19347. Client cli(HOST, PORT);
  19348. auto res = cli.Get(
  19349. "/ip",
  19350. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19352. EXPECT_EQ(StatusCode::OK_200, res->status);
  19353. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19354. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19355. }
  19356. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19357. Server svr;
  19358. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19359. std::string observed_remote_addr;
  19360. std::string observed_xff;
  19361. svr.Get("/ip", [&](const Request &req, Response &res) {
  19362. observed_remote_addr = req.remote_addr;
  19363. observed_xff = req.get_header_value("X-Forwarded-For");
  19364. res.set_content("ok", "text/plain");
  19365. });
  19366. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19367. auto se = detail::scope_exit([&] {
  19368. svr.stop();
  19369. t.join();
  19370. ASSERT_FALSE(svr.is_running());
  19371. });
  19372. svr.wait_until_ready();
  19373. Client cli(HOST, PORT);
  19374. auto res = cli.Get(
  19375. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19377. EXPECT_EQ(StatusCode::OK_200, res->status);
  19378. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19379. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19380. // and must not be selected.
  19381. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19382. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19383. }
  19384. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19385. Server svr;
  19386. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19387. std::string observed_remote_addr;
  19388. svr.Get("/ip", [&](const Request &req, Response &res) {
  19389. observed_remote_addr = req.remote_addr;
  19390. res.set_content("ok", "text/plain");
  19391. });
  19392. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19393. auto se = detail::scope_exit([&] {
  19394. svr.stop();
  19395. t.join();
  19396. ASSERT_FALSE(svr.is_running());
  19397. });
  19398. svr.wait_until_ready();
  19399. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19400. // a forged address and the trusted proxy's own address; the forged value must
  19401. // not win over the address the trusted proxy actually recorded.
  19402. Client cli(HOST, PORT);
  19403. auto res = cli.Get(
  19404. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19406. EXPECT_EQ(StatusCode::OK_200, res->status);
  19407. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19408. }
  19409. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19410. Server svr;
  19411. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19412. std::string observed_remote_addr;
  19413. std::string observed_xff;
  19414. svr.Get("/ip", [&](const Request &req, Response &res) {
  19415. observed_remote_addr = req.remote_addr;
  19416. observed_xff = req.get_header_value("X-Forwarded-For");
  19417. res.set_content("ok", "text/plain");
  19418. });
  19419. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19420. auto se = detail::scope_exit([&] {
  19421. svr.stop();
  19422. t.join();
  19423. ASSERT_FALSE(svr.is_running());
  19424. });
  19425. svr.wait_until_ready();
  19426. Client cli(HOST, PORT);
  19427. auto res = cli.Get(
  19428. "/ip",
  19429. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19431. EXPECT_EQ(StatusCode::OK_200, res->status);
  19432. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19433. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19434. }
  19435. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19436. Server svr;
  19437. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19438. std::string observed_remote_addr;
  19439. std::string observed_xff;
  19440. svr.Get("/ip", [&](const Request &req, Response &res) {
  19441. observed_remote_addr = req.remote_addr;
  19442. observed_xff = req.get_header_value("X-Forwarded-For");
  19443. res.set_content("ok", "text/plain");
  19444. });
  19445. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19446. auto se = detail::scope_exit([&] {
  19447. svr.stop();
  19448. t.join();
  19449. ASSERT_FALSE(svr.is_running());
  19450. });
  19451. svr.wait_until_ready();
  19452. std::string raw_req =
  19453. "GET /ip HTTP/1.1\r\n"
  19454. "Host: localhost\r\n"
  19455. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19456. "Connection: close\r\n"
  19457. "\r\n";
  19458. std::string out;
  19459. ASSERT_TRUE(send_request(5, raw_req, &out));
  19460. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19461. // Header parser trims surrounding whitespace of the header value
  19462. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19463. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19464. }
  19465. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19466. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19467. // their own X-Forwarded-For as a separate field line rather than extending the
  19468. // one the client sent, so every occurrence has to be taken into account.
  19469. // Reading only the first one hands back the address the client chose.
  19470. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19471. Server svr;
  19472. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19473. std::string observed_remote_addr;
  19474. size_t observed_xff_count = 0;
  19475. svr.Get("/ip", [&](const Request &req, Response &res) {
  19476. observed_remote_addr = req.remote_addr;
  19477. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19478. res.set_content("ok", "text/plain");
  19479. });
  19480. auto port = svr.bind_to_any_port(HOST);
  19481. thread t = thread([&]() { svr.listen_after_bind(); });
  19482. auto se = detail::scope_exit([&] {
  19483. svr.stop();
  19484. t.join();
  19485. ASSERT_FALSE(svr.is_running());
  19486. });
  19487. svr.wait_until_ready();
  19488. // The client supplies the first field line; the trusted proxy appends the
  19489. // address it observed as a second one.
  19490. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19491. "Host: localhost\r\n"
  19492. "X-Forwarded-For: 1.2.3.4\r\n"
  19493. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19494. "Connection: close\r\n"
  19495. "\r\n";
  19496. std::string out;
  19497. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19498. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19499. EXPECT_EQ(observed_xff_count, 2U);
  19500. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19501. // The same chain spread over one field line per hop derives the same client
  19502. // address, i.e. the split and the comma-joined representations agree.
  19503. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19504. "Host: localhost\r\n"
  19505. "X-Forwarded-For: 1.2.3.4\r\n"
  19506. "X-Forwarded-For: 198.51.100.23\r\n"
  19507. "X-Forwarded-For: 192.0.2.45\r\n"
  19508. "Connection: close\r\n"
  19509. "\r\n";
  19510. out.clear();
  19511. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19512. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19513. EXPECT_EQ(observed_xff_count, 3U);
  19514. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19515. }
  19516. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19517. // crash the server (it used to call front() on an empty vector inside
  19518. // get_client_ip). The connection-level remote address must be retained instead.
  19519. static void run_malformed_xff_test(const std::string &xff_value) {
  19520. Server svr;
  19521. svr.set_trusted_proxies({"192.0.2.45"});
  19522. std::string observed_remote_addr;
  19523. svr.Get("/ip", [&](const Request &req, Response &res) {
  19524. observed_remote_addr = req.remote_addr;
  19525. res.set_content("ok", "text/plain");
  19526. });
  19527. int port = 0;
  19528. thread t = thread([&]() {
  19529. port = svr.bind_to_any_port(HOST);
  19530. svr.listen_after_bind();
  19531. });
  19532. auto se = detail::scope_exit([&] {
  19533. svr.stop();
  19534. t.join();
  19535. ASSERT_FALSE(svr.is_running());
  19536. });
  19537. svr.wait_until_ready();
  19538. Client cli(HOST, port);
  19539. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19541. EXPECT_EQ(StatusCode::OK_200, res->status);
  19542. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19543. observed_remote_addr == "127.0.0.1");
  19544. }
  19545. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19546. run_malformed_xff_test("");
  19547. }
  19548. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19549. run_malformed_xff_test(",");
  19550. }
  19551. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19552. run_malformed_xff_test(", , ,");
  19553. }
  19554. // The same rule applies to Accept: a request whose acceptable types are spread
  19555. // over several field lines must be negotiated against all of them.
  19556. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19557. // case-insensitive connection options. Comparing the whole field value against
  19558. // one option misses a client that sends several of them, and misses every
  19559. // casing but the one written in the comparison.
  19560. //
  19561. // Sends req, reads the response, then reuses the same socket for a second
  19562. // request to find out whether the server kept the connection.
  19563. static void probe_connection_reuse(int port, const std::string &req,
  19564. bool *announced_close, bool *reusable) {
  19565. auto error = Error::Success;
  19566. auto sock = detail::create_client_socket(
  19567. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19568. /*connection_timeout_sec=*/5, 0,
  19569. /*read_timeout_sec=*/1, 0,
  19570. /*write_timeout_sec=*/5, 0, std::string(), error);
  19571. ASSERT_NE(sock, INVALID_SOCKET);
  19572. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19573. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19574. "Host: localhost\r\n"
  19575. "Connection: close\r\n"
  19576. "\r\n";
  19577. std::string first_response;
  19578. std::string second_response;
  19579. detail::process_client_socket(
  19580. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19581. [&](Stream &strm) {
  19582. if (strm.write(req.data(), req.size()) !=
  19583. static_cast<ssize_t>(req.size())) {
  19584. return false;
  19585. }
  19586. char buf[512];
  19587. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19588. // Headers plus the two-byte body of the handler below
  19589. while (reader.getline()) {
  19590. first_response += reader.ptr();
  19591. if (first_response.find("ok") != std::string::npos) { break; }
  19592. }
  19593. if (strm.write(second.data(), second.size()) !=
  19594. static_cast<ssize_t>(second.size())) {
  19595. return true;
  19596. }
  19597. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19598. while (reader2.getline()) {
  19599. second_response += reader2.ptr();
  19600. if (second_response.find("ok") != std::string::npos) { break; }
  19601. }
  19602. return true;
  19603. });
  19604. *announced_close =
  19605. first_response.find("Connection: close") != std::string::npos;
  19606. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19607. }
  19608. class ConnectionTokenTest : public ::testing::Test {
  19609. protected:
  19610. void SetUp() override {
  19611. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19612. res.set_content("ok", "text/plain");
  19613. });
  19614. port_ = svr_.bind_to_any_port(HOST);
  19615. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19616. svr_.wait_until_ready();
  19617. }
  19618. void TearDown() override {
  19619. svr_.stop();
  19620. if (thread_.joinable()) { thread_.join(); }
  19621. }
  19622. Server svr_;
  19623. int port_ = 0;
  19624. thread thread_;
  19625. };
  19626. // "close" alongside another option still closes the connection, and the
  19627. // response says so rather than leaving the peer to discover it.
  19628. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19629. bool announced_close = false;
  19630. bool reusable = true;
  19631. probe_connection_reuse(port_,
  19632. "GET /keepalive HTTP/1.1\r\n"
  19633. "Host: localhost\r\n"
  19634. "Connection: keep-alive, close\r\n"
  19635. "\r\n",
  19636. &announced_close, &reusable);
  19637. EXPECT_TRUE(announced_close);
  19638. EXPECT_FALSE(reusable);
  19639. }
  19640. // "close" split over two field lines is the same list, so it is honored too.
  19641. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19642. bool announced_close = false;
  19643. bool reusable = true;
  19644. probe_connection_reuse(port_,
  19645. "GET /keepalive HTTP/1.1\r\n"
  19646. "Host: localhost\r\n"
  19647. "Connection: keep-alive\r\n"
  19648. "Connection: close\r\n"
  19649. "\r\n",
  19650. &announced_close, &reusable);
  19651. EXPECT_TRUE(announced_close);
  19652. EXPECT_FALSE(reusable);
  19653. }
  19654. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19655. // keep-alive in the spelling everyone actually sends keeps its connection.
  19656. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19657. bool announced_close = false;
  19658. bool reusable = false;
  19659. probe_connection_reuse(port_,
  19660. "GET /keepalive HTTP/1.0\r\n"
  19661. "Host: localhost\r\n"
  19662. "Connection: keep-alive\r\n"
  19663. "\r\n",
  19664. &announced_close, &reusable);
  19665. EXPECT_FALSE(announced_close);
  19666. EXPECT_TRUE(reusable);
  19667. }
  19668. // A token the value merely contains is not the token itself.
  19669. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19670. bool announced_close = false;
  19671. bool reusable = false;
  19672. probe_connection_reuse(port_,
  19673. "GET /keepalive HTTP/1.1\r\n"
  19674. "Host: localhost\r\n"
  19675. "Connection: notclose\r\n"
  19676. "\r\n",
  19677. &announced_close, &reusable);
  19678. EXPECT_FALSE(announced_close);
  19679. EXPECT_TRUE(reusable);
  19680. }
  19681. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19682. Server svr;
  19683. std::vector<std::string> observed_types;
  19684. svr.Get("/", [&](const Request &req, Response &res) {
  19685. observed_types = req.accept_content_types;
  19686. res.set_content("ok", "text/plain");
  19687. });
  19688. auto port = svr.bind_to_any_port(HOST);
  19689. thread t = thread([&]() { svr.listen_after_bind(); });
  19690. auto se = detail::scope_exit([&] {
  19691. svr.stop();
  19692. t.join();
  19693. ASSERT_FALSE(svr.is_running());
  19694. });
  19695. svr.wait_until_ready();
  19696. Client cli(HOST, port);
  19697. Headers headers;
  19698. headers.emplace("Accept", "text/plain;q=0.5");
  19699. headers.emplace("Accept", "application/json");
  19700. auto res = cli.Get("/", headers);
  19701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19702. EXPECT_EQ(StatusCode::OK_200, res->status);
  19703. // Sorted by q-value, so the second field line's type comes first
  19704. ASSERT_EQ(2U, observed_types.size());
  19705. EXPECT_EQ("application/json", observed_types[0]);
  19706. EXPECT_EQ("text/plain", observed_types[1]);
  19707. }
  19708. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19709. // empty field line must not contribute a bare comma to the combined value.
  19710. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19711. Server svr;
  19712. std::vector<std::string> observed_types;
  19713. svr.Get("/", [&](const Request &req, Response &res) {
  19714. observed_types = req.accept_content_types;
  19715. res.set_content("ok", "text/plain");
  19716. });
  19717. auto port = svr.bind_to_any_port(HOST);
  19718. thread t = thread([&]() { svr.listen_after_bind(); });
  19719. auto se = detail::scope_exit([&] {
  19720. svr.stop();
  19721. t.join();
  19722. ASSERT_FALSE(svr.is_running());
  19723. });
  19724. svr.wait_until_ready();
  19725. // Empty first field line, then a real one
  19726. std::string raw_req = "GET / HTTP/1.1\r\n"
  19727. "Host: localhost\r\n"
  19728. "Accept:\r\n"
  19729. "Accept: application/json\r\n"
  19730. "Connection: close\r\n"
  19731. "\r\n";
  19732. std::string out;
  19733. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19734. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19735. ASSERT_EQ(1U, observed_types.size());
  19736. EXPECT_EQ("application/json", observed_types[0]);
  19737. }
  19738. // The skip in get_combined_header_value() is what keeps an empty field line
  19739. // from contributing a bare comma. Only a trailing empty field line exercises
  19740. // it: a leading one is already covered by the "combined is still empty" check,
  19741. // and parse_accept_header() now ignores the empty element either way, so the
  19742. // request-level test above can no longer tell the two apart.
  19743. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19744. Headers headers;
  19745. headers.emplace("Accept", "text/html");
  19746. headers.emplace("Accept", "");
  19747. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19748. headers.clear();
  19749. headers.emplace("Accept", "");
  19750. headers.emplace("Accept", "application/json");
  19751. EXPECT_EQ("application/json",
  19752. detail::get_combined_header_value(headers, "Accept"));
  19753. }
  19754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19755. // An encoding offered on a later Accept-Encoding field line is still offered.
  19756. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19757. Server svr;
  19758. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19759. res.set_content(std::string(1024, 'x'), "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. cli.set_decompress(false);
  19771. Headers headers;
  19772. headers.emplace("Accept-Encoding", "identity");
  19773. headers.emplace("Accept-Encoding", "gzip");
  19774. auto res = cli.Get("/", headers);
  19775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19776. EXPECT_EQ(StatusCode::OK_200, res->status);
  19777. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19778. }
  19779. #endif
  19780. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19781. // Transfer-Encoding is not its body.
  19782. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19783. Server svr;
  19784. svr.set_payload_max_length(8);
  19785. svr.Post("/test", [](const Request &, Response &res) {
  19786. res.set_content("ok", "text/plain");
  19787. });
  19788. auto port = svr.bind_to_any_port(HOST);
  19789. ASSERT_GT(port, 0);
  19790. thread t = thread([&] { svr.listen_after_bind(); });
  19791. auto se = detail::scope_exit([&] {
  19792. svr.stop();
  19793. t.join();
  19794. ASSERT_FALSE(svr.is_running());
  19795. });
  19796. svr.wait_until_ready();
  19797. std::string resp;
  19798. ASSERT_TRUE(send_request(1,
  19799. "POST /test HTTP/1.1\r\n"
  19800. "Host: localhost\r\n"
  19801. "Connection: close\r\n"
  19802. "\r\n" +
  19803. std::string(16, 'X'),
  19804. &resp, port));
  19805. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19806. }
  19807. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19808. Server svr;
  19809. svr.Post("/post", [&](const Request &req, Response &res) {
  19810. res.set_content(req.body, "text/plain");
  19811. });
  19812. svr.Put("/put", [&](const Request &req, Response &res) {
  19813. res.set_content(req.body, "text/plain");
  19814. });
  19815. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19816. res.set_content(req.body, "text/plain");
  19817. });
  19818. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19819. res.set_content(req.body, "text/plain");
  19820. });
  19821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19822. auto se = detail::scope_exit([&] {
  19823. svr.stop();
  19824. t.join();
  19825. ASSERT_FALSE(svr.is_running());
  19826. });
  19827. svr.wait_until_ready();
  19828. std::string resp;
  19829. // POST without Content-Length
  19830. ASSERT_TRUE(send_request(5,
  19831. "POST /post HTTP/1.1\r\n"
  19832. "Host: localhost\r\n"
  19833. "Connection: close\r\n"
  19834. "\r\n",
  19835. &resp));
  19836. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19837. // PUT without Content-Length
  19838. resp.clear();
  19839. ASSERT_TRUE(send_request(5,
  19840. "PUT /put HTTP/1.1\r\n"
  19841. "Host: localhost\r\n"
  19842. "Connection: close\r\n"
  19843. "\r\n",
  19844. &resp));
  19845. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19846. // PATCH without Content-Length
  19847. resp.clear();
  19848. ASSERT_TRUE(send_request(5,
  19849. "PATCH /patch HTTP/1.1\r\n"
  19850. "Host: localhost\r\n"
  19851. "Connection: close\r\n"
  19852. "\r\n",
  19853. &resp));
  19854. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19855. // DELETE without Content-Length
  19856. resp.clear();
  19857. ASSERT_TRUE(send_request(5,
  19858. "DELETE /delete HTTP/1.1\r\n"
  19859. "Host: localhost\r\n"
  19860. "Connection: close\r\n"
  19861. "\r\n",
  19862. &resp));
  19863. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19864. }
  19865. //==============================================================================
  19866. // open_stream() Tests
  19867. //==============================================================================
  19868. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19869. std::string result;
  19870. char buf[8192];
  19871. ssize_t n;
  19872. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19873. result.append(buf, static_cast<size_t>(n));
  19874. }
  19875. return result;
  19876. }
  19877. // Mock stream for unit tests
  19878. class MockStream : public Stream {
  19879. public:
  19880. std::string data;
  19881. size_t pos = 0;
  19882. ssize_t error_after = -1; // -1 = no error
  19883. explicit MockStream(const std::string &d, ssize_t err = -1)
  19884. : data(d), error_after(err) {}
  19885. bool is_readable() const override { return true; }
  19886. bool wait_readable() const override { return true; }
  19887. bool wait_writable() const override { return true; }
  19888. ssize_t read(char *ptr, size_t size) override {
  19889. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19890. if (pos >= data.size()) return 0;
  19891. size_t limit =
  19892. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19893. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19894. std::memcpy(ptr, data.data() + pos, to_read);
  19895. pos += to_read;
  19896. return static_cast<ssize_t>(to_read);
  19897. }
  19898. ssize_t write(const char *, size_t) override { return -1; }
  19899. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19900. ip = "127.0.0.1";
  19901. port = 0;
  19902. }
  19903. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19904. ip = "127.0.0.1";
  19905. port = 0;
  19906. }
  19907. socket_t socket() const override { return INVALID_SOCKET; }
  19908. time_t duration() const override { return 0; }
  19909. };
  19910. TEST(StreamHandleTest, Basic) {
  19911. ClientImpl::StreamHandle handle;
  19912. EXPECT_FALSE(handle.is_valid());
  19913. handle.response = detail::make_unique<Response>();
  19914. handle.error = Error::Connection;
  19915. EXPECT_FALSE(handle.is_valid());
  19916. handle.error = Error::Success;
  19917. EXPECT_TRUE(handle.is_valid());
  19918. }
  19919. TEST(BodyReaderTest, Basic) {
  19920. MockStream stream("Hello, World!");
  19921. detail::BodyReader reader;
  19922. reader.stream = &stream;
  19923. reader.content_length = 13;
  19924. char buf[32];
  19925. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19926. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19927. EXPECT_TRUE(reader.eof);
  19928. }
  19929. TEST(BodyReaderTest, NoStream) {
  19930. detail::BodyReader reader;
  19931. char buf[32];
  19932. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19933. EXPECT_EQ(Error::Connection, reader.last_error);
  19934. }
  19935. TEST(BodyReaderTest, Error) {
  19936. MockStream stream("Hello, World!", 5);
  19937. detail::BodyReader reader;
  19938. reader.stream = &stream;
  19939. reader.content_length = 13;
  19940. char buf[32];
  19941. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19942. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19943. EXPECT_EQ(Error::Read, reader.last_error);
  19944. }
  19945. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19946. // Mock-based StreamHandle tests relying on private internals are removed.
  19947. class OpenStreamTest : public ::testing::Test {
  19948. protected:
  19949. void SetUp() override {
  19950. svr_.Get("/hello", [](const Request &, Response &res) {
  19951. res.set_content("Hello World!", "text/plain");
  19952. });
  19953. svr_.Get("/large", [](const Request &, Response &res) {
  19954. res.set_content(std::string(10000, 'X'), "text/plain");
  19955. });
  19956. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19957. res.set_content("Hello World!", "image/jpeg");
  19958. res.set_header("Content-Encoding", "UTF-8");
  19959. });
  19960. svr_.Get("/chunked", [](const Request &, Response &res) {
  19961. res.set_chunked_content_provider("text/plain",
  19962. [](size_t offset, DataSink &sink) {
  19963. if (offset < 15) {
  19964. sink.write("chunk", 5);
  19965. return true;
  19966. }
  19967. sink.done();
  19968. return true;
  19969. });
  19970. });
  19971. svr_.Get("/compressible", [](const Request &, Response &res) {
  19972. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19973. DataSink &sink) {
  19974. if (offset < 100 * 1024) {
  19975. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19976. sink.write(chunk.data(), chunk.size());
  19977. return true;
  19978. }
  19979. sink.done();
  19980. return true;
  19981. });
  19982. });
  19983. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19984. [](const Request & /*req*/, Response &res) {
  19985. auto i = new int(0);
  19986. res.set_header("Trailer", "Content-Length, X-Allowed");
  19987. res.set_chunked_content_provider(
  19988. "text/plain",
  19989. [i](size_t /*offset*/, DataSink &sink) {
  19990. switch (*i) {
  19991. case 0: sink.os << "123"; break;
  19992. case 1: sink.os << "456"; break;
  19993. case 2: sink.os << "789"; break;
  19994. case 3: {
  19995. sink.done_with_trailer(
  19996. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19997. } break;
  19998. }
  19999. (*i)++;
  20000. return true;
  20001. },
  20002. [i](bool success) {
  20003. EXPECT_TRUE(success);
  20004. delete i;
  20005. });
  20006. });
  20007. // Echo headers endpoint for header-related tests
  20008. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20009. std::string body;
  20010. for (const auto &h : req.headers) {
  20011. body.append(h.first);
  20012. body.push_back(':');
  20013. body.append(h.second);
  20014. body.push_back('\n');
  20015. }
  20016. res.set_content(body, "text/plain");
  20017. });
  20018. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20019. std::string body;
  20020. for (const auto &h : req.headers) {
  20021. body.append(h.first);
  20022. body.push_back(':');
  20023. body.append(h.second);
  20024. body.push_back('\n');
  20025. }
  20026. res.set_content(body, "text/plain");
  20027. });
  20028. port_ = svr_.bind_to_any_port("127.0.0.1");
  20029. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20030. svr_.wait_until_ready();
  20031. }
  20032. void TearDown() override {
  20033. svr_.stop();
  20034. if (thread_.joinable()) thread_.join();
  20035. }
  20036. Server svr_;
  20037. std::thread thread_;
  20038. int port_ = 0;
  20039. };
  20040. TEST_F(OpenStreamTest, Basic) {
  20041. Client cli("127.0.0.1", port_);
  20042. auto handle = cli.open_stream("GET", "/hello");
  20043. EXPECT_TRUE(handle.is_valid());
  20044. EXPECT_EQ("Hello World!", read_all(handle));
  20045. }
  20046. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20047. Client cli("127.0.0.1", port_);
  20048. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20049. ASSERT_TRUE(handle.is_valid());
  20050. EXPECT_EQ("Hello World!", read_all(handle));
  20051. }
  20052. TEST_F(OpenStreamTest, SmallBuffer) {
  20053. Client cli("127.0.0.1", port_);
  20054. auto handle = cli.open_stream("GET", "/hello");
  20055. std::string result;
  20056. char buf[4];
  20057. ssize_t n;
  20058. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20059. result.append(buf, static_cast<size_t>(n));
  20060. EXPECT_EQ("Hello World!", result);
  20061. }
  20062. TEST_F(OpenStreamTest, DefaultHeaders) {
  20063. Client cli("127.0.0.1", port_);
  20064. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20065. {
  20066. auto handle = cli.open_stream("GET", "/echo-headers");
  20067. ASSERT_TRUE(handle.is_valid());
  20068. auto body = read_all(handle);
  20069. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20070. std::string::npos);
  20071. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20072. std::string::npos);
  20073. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20074. }
  20075. // open_stream POST with body and no explicit content_type should NOT add
  20076. // text/plain Content-Type (behavior differs from non-streaming path), but
  20077. // should include Content-Length
  20078. {
  20079. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20080. ASSERT_TRUE(handle.is_valid());
  20081. auto body = read_all(handle);
  20082. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20083. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20084. }
  20085. // open_stream POST with explicit Content-Type should preserve it
  20086. {
  20087. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20088. {{"Content-Type", "application/custom"}},
  20089. "{}", "application/custom");
  20090. ASSERT_TRUE(handle.is_valid());
  20091. auto body = read_all(handle);
  20092. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20093. }
  20094. // User-specified User-Agent must not be overwritten for stream API
  20095. {
  20096. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20097. {{"User-Agent", "MyAgent/1.2"}});
  20098. ASSERT_TRUE(handle.is_valid());
  20099. auto body = read_all(handle);
  20100. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20101. }
  20102. }
  20103. TEST_F(OpenStreamTest, Large) {
  20104. Client cli("127.0.0.1", port_);
  20105. auto handle = cli.open_stream("GET", "/large");
  20106. EXPECT_EQ(10000u, read_all(handle).size());
  20107. }
  20108. TEST_F(OpenStreamTest, ConnectionError) {
  20109. Client cli("127.0.0.1", 9999);
  20110. auto handle = cli.open_stream("GET", "/hello");
  20111. EXPECT_FALSE(handle.is_valid());
  20112. }
  20113. TEST_F(OpenStreamTest, Chunked) {
  20114. Client cli("127.0.0.1", port_);
  20115. auto handle = cli.open_stream("GET", "/chunked");
  20116. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20117. "Transfer-Encoding") == "chunked");
  20118. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20119. }
  20120. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20121. Client cli("127.0.0.1", port_);
  20122. auto handle =
  20123. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20124. ASSERT_TRUE(handle.is_valid());
  20125. // Consume body to allow trailers to be received/parsed
  20126. auto body = read_all(handle);
  20127. // Explicitly parse trailers (ensure trailers are available for assertion)
  20128. handle.parse_trailers_if_needed();
  20129. EXPECT_EQ(std::string("123456789"), body);
  20130. // The response should include a Trailer header declaring both names
  20131. ASSERT_TRUE(handle.response);
  20132. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20133. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20134. handle.response->get_header_value("Trailer"));
  20135. // Prohibited trailer must not be present
  20136. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20137. // Allowed trailer should be present
  20138. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20139. EXPECT_EQ(std::string("yes"),
  20140. handle.response->get_trailer_value("X-Allowed"));
  20141. // Verify trailers are NOT present as regular headers
  20142. EXPECT_EQ(std::string(""),
  20143. handle.response->get_header_value("Content-Length"));
  20144. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20145. }
  20146. // Accepts one connection on an OS-assigned port, which it hands over through
  20147. // port_promise, reads the request head and sends back response. after_send,
  20148. // if given, runs on the connection before it is closed.
  20149. static std::thread
  20150. serve_single_response(std::promise<int> &port_promise,
  20151. const std::string &response,
  20152. std::function<void(socket_t)> after_send = nullptr) {
  20153. return std::thread([&port_promise, response, after_send] {
  20154. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20155. default_socket_options(srv);
  20156. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20157. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20158. sockaddr_in addr{};
  20159. addr.sin_family = AF_INET;
  20160. addr.sin_port = htons(0); // Let OS assign a free port
  20161. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20162. int opt = 1;
  20163. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20164. #ifdef _WIN32
  20165. reinterpret_cast<const char *>(&opt),
  20166. #else
  20167. &opt,
  20168. #endif
  20169. sizeof(opt));
  20170. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20171. ::listen(srv, 1) != 0) {
  20172. port_promise.set_value(-1);
  20173. detail::close_socket(srv);
  20174. return;
  20175. }
  20176. socklen_t addr_len = sizeof(addr);
  20177. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20178. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20179. sockaddr_in cli_addr{};
  20180. socklen_t cli_len = sizeof(cli_addr);
  20181. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20182. if (cli != INVALID_SOCKET) {
  20183. // Read the complete HTTP request (until the blank line that terminates
  20184. // headers) before sending the response. If the server closes the socket
  20185. // while the client's request data is still unread in the kernel receive
  20186. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20187. // connection on both sides: it discards the client's receive buffer
  20188. // (which already holds our response) and causes any in-progress write on
  20189. // the client to fail with ECONNRESET. Reading all request data first
  20190. // ensures close() emits a graceful FIN.
  20191. {
  20192. char rbuf[256];
  20193. std::string req;
  20194. while (req.find("\r\n\r\n") == std::string::npos) {
  20195. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20196. if (n <= 0) { break; }
  20197. req.append(rbuf, static_cast<size_t>(n));
  20198. }
  20199. }
  20200. ::send(cli,
  20201. #ifdef _WIN32
  20202. static_cast<const char *>(response.c_str()),
  20203. static_cast<int>(response.size()),
  20204. #else
  20205. response.c_str(), response.size(),
  20206. #endif
  20207. 0);
  20208. if (after_send) { after_send(cli); }
  20209. detail::close_socket(cli);
  20210. }
  20211. detail::close_socket(srv);
  20212. });
  20213. }
  20214. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20215. #ifndef _WIN32
  20216. signal(SIGPIPE, SIG_IGN);
  20217. #endif
  20218. std::promise<int> port_promise;
  20219. auto port_future = port_promise.get_future();
  20220. auto server_thread =
  20221. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20222. "Content-Type: text/plain\r\n"
  20223. "Content-Length: not-a-number\r\n"
  20224. "Connection: close\r\n"
  20225. "\r\n"
  20226. "hello");
  20227. auto port = port_future.get();
  20228. ASSERT_GT(port, 0);
  20229. Client cli("127.0.0.1", port);
  20230. auto handle = cli.open_stream("GET", "/");
  20231. EXPECT_FALSE(handle.is_valid());
  20232. server_thread.join();
  20233. }
  20234. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20235. #ifndef _WIN32
  20236. signal(SIGPIPE, SIG_IGN);
  20237. #endif
  20238. std::promise<int> port_promise;
  20239. auto port_future = port_promise.get_future();
  20240. auto server_thread = serve_single_response(
  20241. port_promise, "HTTP/1.1 200 OK\r\n"
  20242. "Content-Type: text/plain\r\n"
  20243. "Content-Length: 99999999999999999999999999\r\n"
  20244. "Connection: close\r\n"
  20245. "\r\n"
  20246. "hello");
  20247. auto port = port_future.get();
  20248. ASSERT_GT(port, 0);
  20249. // Historically std::stoull would throw std::out_of_range here and crash
  20250. // the process, then parsing silently clamped to a bogus framing length and
  20251. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20252. // so the stream fails to open, matching the not-a-number case above. The
  20253. // process still must NOT terminate.
  20254. Client cli("127.0.0.1", port);
  20255. auto handle = cli.open_stream("GET", "/");
  20256. EXPECT_FALSE(handle.is_valid());
  20257. server_thread.join();
  20258. }
  20259. #ifndef _WIN32
  20260. // As above for the body of a streamed request: a send() cut short by the write
  20261. // timeout must not leave the rest of the body unsent.
  20262. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20263. signal(SIGPIPE, SIG_IGN);
  20264. Server svr;
  20265. svr.set_socket_options([](socket_t sock) {
  20266. int size = 8192;
  20267. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20268. reinterpret_cast<const char *>(&size), sizeof(size));
  20269. });
  20270. svr.Post("/size", [](const Request &, Response &res,
  20271. const ContentReader &content_reader) {
  20272. // Outlast the client's write timeout before reading the body.
  20273. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20274. size_t received = 0;
  20275. content_reader([&](const char *, size_t len) {
  20276. received += len;
  20277. return true;
  20278. });
  20279. res.set_content(std::to_string(received), "text/plain");
  20280. });
  20281. auto port = svr.bind_to_any_port(HOST);
  20282. std::thread t([&]() { svr.listen_after_bind(); });
  20283. auto se = detail::scope_exit([&] {
  20284. svr.stop();
  20285. t.join();
  20286. });
  20287. svr.wait_until_ready();
  20288. Client cli(HOST, port);
  20289. cli.set_write_timeout(0, 500000);
  20290. cli.set_socket_options([](socket_t sock) {
  20291. int size = 8192;
  20292. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20293. reinterpret_cast<const char *>(&size), sizeof(size));
  20294. });
  20295. const std::string body(4 * 1024 * 1024, 'A');
  20296. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20297. "application/octet-stream");
  20298. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20299. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20300. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20301. }
  20302. #endif
  20303. // Serves `response` to the single request `fn` makes with a fresh client.
  20304. template <typename Fn>
  20305. static void with_single_response(const std::string &response, Fn fn) {
  20306. #ifndef _WIN32
  20307. signal(SIGPIPE, SIG_IGN);
  20308. #endif
  20309. std::promise<int> port_promise;
  20310. auto port_future = port_promise.get_future();
  20311. auto server_thread = serve_single_response(port_promise, response);
  20312. auto se = detail::scope_exit([&] { server_thread.join(); });
  20313. auto port = port_future.get();
  20314. ASSERT_GT(port, 0);
  20315. Client cli("127.0.0.1", port);
  20316. fn(cli);
  20317. }
  20318. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20319. // too, also in a build without the decoder for the advertised coding.
  20320. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20321. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20322. const auto response = "HTTP/1.1 200 OK\r\n"
  20323. "Content-Encoding: gzip\r\n"
  20324. "Content-Length: " +
  20325. std::to_string(gzipped.size()) +
  20326. "\r\n"
  20327. "Connection: close\r\n\r\n" +
  20328. gzipped;
  20329. with_single_response(response, [&](Client &cli) {
  20330. cli.set_decompress(false);
  20331. auto handle = cli.open_stream("GET", "/");
  20332. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20333. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20334. EXPECT_EQ(gzipped, read_all(handle));
  20335. EXPECT_FALSE(handle.has_read_error());
  20336. });
  20337. with_single_response(response, [&](Client &cli) {
  20338. cli.set_decompress(false);
  20339. auto res = stream::Get(cli, "/", 7);
  20340. ASSERT_TRUE(res) << to_string(res.error());
  20341. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20342. EXPECT_EQ(gzipped, res.read_all());
  20343. EXPECT_FALSE(res.has_read_error());
  20344. });
  20345. }
  20346. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20347. // Neither Content-Length nor chunked: the body ends at the close
  20348. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20349. "Connection: close\r\n"
  20350. "\r\n"
  20351. "hello";
  20352. with_single_response(close_delimited, [](Client &cli) {
  20353. auto handle = cli.open_stream("GET", "/");
  20354. ASSERT_TRUE(handle.is_valid());
  20355. EXPECT_EQ("hello", read_all(handle));
  20356. EXPECT_FALSE(handle.has_read_error());
  20357. });
  20358. // A close before the end of the Content-Length is still an error
  20359. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20360. "Content-Length: 10\r\n"
  20361. "\r\n"
  20362. "hello";
  20363. with_single_response(short_content_length, [](Client &cli) {
  20364. auto handle = cli.open_stream("GET", "/");
  20365. ASSERT_TRUE(handle.is_valid());
  20366. read_all(handle);
  20367. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20368. });
  20369. // So is a close before the last chunk
  20370. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20371. "Transfer-Encoding: chunked\r\n"
  20372. "\r\n"
  20373. "5\r\nhello\r\n";
  20374. with_single_response(short_chunked, [](Client &cli) {
  20375. auto handle = cli.open_stream("GET", "/");
  20376. ASSERT_TRUE(handle.is_valid());
  20377. read_all(handle);
  20378. EXPECT_TRUE(handle.has_read_error());
  20379. });
  20380. }
  20381. #ifdef CPPHTTPLIB_SSL_ENABLED
  20382. // Serves `response` to one request, then closes with or without a close_notify
  20383. template <typename Fn>
  20384. static void with_single_tls_response(const std::string &response,
  20385. bool close_notify, Fn fn) {
  20386. #ifndef _WIN32
  20387. signal(SIGPIPE, SIG_IGN);
  20388. #endif
  20389. std::promise<int> port_promise;
  20390. auto port_future = port_promise.get_future();
  20391. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20392. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20393. default_socket_options(srv);
  20394. sockaddr_in addr{};
  20395. addr.sin_family = AF_INET;
  20396. addr.sin_port = htons(0);
  20397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20398. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20399. ::listen(srv, 1) != 0) {
  20400. port_promise.set_value(-1);
  20401. detail::close_socket(srv);
  20402. return;
  20403. }
  20404. socklen_t addr_len = sizeof(addr);
  20405. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20406. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20407. auto cli = ::accept(srv, nullptr, nullptr);
  20408. if (cli != INVALID_SOCKET) {
  20409. auto ctx = tls::create_server_context();
  20410. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20411. nullptr);
  20412. auto session = tls::create_session(ctx, cli);
  20413. tls::TlsError err;
  20414. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20415. // The request head first, so that closing the socket sends a FIN
  20416. // rather than an RST for the unread bytes.
  20417. std::string req;
  20418. char buf[256];
  20419. while (req.find("\r\n\r\n") == std::string::npos) {
  20420. auto n = tls::read(session, buf, sizeof(buf), err);
  20421. if (n <= 0) { break; }
  20422. req.append(buf, static_cast<size_t>(n));
  20423. }
  20424. size_t sent = 0;
  20425. while (sent < response.size()) {
  20426. auto n = tls::write(session, response.data() + sent,
  20427. response.size() - sent, err);
  20428. if (n <= 0) { break; }
  20429. sent += static_cast<size_t>(n);
  20430. }
  20431. if (close_notify) { tls::shutdown(session, true); }
  20432. }
  20433. tls::free_session(session);
  20434. detail::close_socket(cli);
  20435. tls::free_context(ctx);
  20436. }
  20437. detail::close_socket(srv);
  20438. });
  20439. auto se = detail::scope_exit([&] { server_thread.join(); });
  20440. auto port = port_future.get();
  20441. ASSERT_GT(port, 0);
  20442. SSLClient cli("127.0.0.1", port);
  20443. cli.enable_server_certificate_verification(false);
  20444. fn(cli);
  20445. }
  20446. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20447. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20448. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20449. "Connection: close\r\n"
  20450. "\r\n"
  20451. "hello";
  20452. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20453. auto res = cli.Get("/");
  20454. ASSERT_TRUE(res) << to_string(res.error());
  20455. EXPECT_EQ("hello", res->body);
  20456. });
  20457. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20458. auto res = cli.Get("/");
  20459. ASSERT_FALSE(res);
  20460. EXPECT_EQ(Error::Read, res.error());
  20461. });
  20462. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20463. auto handle = cli.open_stream("GET", "/");
  20464. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20465. read_all(handle);
  20466. EXPECT_TRUE(handle.has_read_error());
  20467. });
  20468. // A framed body ends where its framing says, with or without the alert
  20469. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20470. "Content-Length: 5\r\n"
  20471. "Connection: close\r\n"
  20472. "\r\n"
  20473. "hello";
  20474. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20475. auto res = cli.Get("/");
  20476. ASSERT_TRUE(res) << to_string(res.error());
  20477. EXPECT_EQ("hello", res->body);
  20478. });
  20479. }
  20480. #endif
  20481. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20482. const char *responses[] = {
  20483. "HTTP/1.1 103 Early Hints\r\n"
  20484. "Link: </style.css>; rel=preload\r\n"
  20485. "\r\n"
  20486. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20487. "HTTP/1.1 100 Continue\r\n"
  20488. "X-Note: interim\r\n"
  20489. "\r\n"
  20490. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20491. };
  20492. for (auto response : responses) {
  20493. with_single_response(response, [](Client &cli) {
  20494. auto res = cli.Get("/");
  20495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20496. EXPECT_EQ(StatusCode::OK_200, res->status);
  20497. EXPECT_EQ("ok", res->body);
  20498. });
  20499. }
  20500. }
  20501. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20502. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20503. const std::string final_response =
  20504. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20505. std::string interims;
  20506. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20507. interims += interim;
  20508. }
  20509. with_single_response(interims + final_response, [](Client &cli) {
  20510. auto res = cli.Get("/");
  20511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20512. EXPECT_EQ("ok", res->body);
  20513. });
  20514. with_single_response(interims + interim + final_response, [](Client &cli) {
  20515. auto res = cli.Get("/");
  20516. ASSERT_FALSE(res);
  20517. EXPECT_EQ(Error::Read, res.error());
  20518. });
  20519. }
  20520. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20521. #ifndef _WIN32
  20522. signal(SIGPIPE, SIG_IGN);
  20523. #endif
  20524. // The server answers the head without asking for the body. Bytes it then
  20525. // reads on the connection would be taken for the body the request declared.
  20526. auto closed_by_client = false;
  20527. std::promise<int> port_promise;
  20528. auto server_thread = serve_single_response(
  20529. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20530. [&](socket_t sock) {
  20531. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20532. char buf[256];
  20533. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20534. });
  20535. Client cli("127.0.0.1", port_promise.get_future().get());
  20536. cli.set_keep_alive(true);
  20537. cli.set_read_timeout(1, 0);
  20538. // Long enough for the client to send Expect: 100-continue.
  20539. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20541. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20542. cli.Get("/second");
  20543. server_thread.join();
  20544. EXPECT_TRUE(closed_by_client);
  20545. }
  20546. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20547. // Long enough for the client to send Expect: 100-continue
  20548. with_single_response(
  20549. "HTTP/1.1 103 Early Hints\r\n"
  20550. "Link: </style.css>; rel=preload\r\n"
  20551. "\r\n"
  20552. "HTTP/1.1 401 Unauthorized\r\n"
  20553. "Content-Length: 0\r\n\r\n",
  20554. [](Client &cli) {
  20555. cli.set_read_timeout(2, 0);
  20556. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20558. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20559. });
  20560. }
  20561. #ifdef CPPHTTPLIB_SSL_ENABLED
  20562. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20563. #ifndef _WIN32
  20564. signal(SIGPIPE, SIG_IGN);
  20565. #endif
  20566. auto reused = false;
  20567. std::promise<int> port_promise;
  20568. auto server_thread = serve_single_response(
  20569. port_promise,
  20570. "HTTP/1.1 401 Unauthorized\r\n"
  20571. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20572. "Content-Length: 0\r\n\r\n",
  20573. [&](socket_t sock) {
  20574. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20575. char buf[256];
  20576. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20577. });
  20578. Client cli("127.0.0.1", port_promise.get_future().get());
  20579. cli.set_keep_alive(true);
  20580. cli.set_digest_auth("user", "pass");
  20581. cli.set_read_timeout(1, 0);
  20582. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20583. server_thread.join();
  20584. EXPECT_FALSE(reused);
  20585. }
  20586. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20587. // Any other answer to CONNECT would read as the origin's response.
  20588. struct {
  20589. const char *response;
  20590. bool passed_on;
  20591. } cases[] = {
  20592. {"HTTP/1.1 201 Created\r\n"
  20593. "Set-Cookie: session=from-proxy\r\n"
  20594. "Content-Length: 0\r\n\r\n",
  20595. false},
  20596. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20597. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20598. "Content-Length: 0\r\n\r\n",
  20599. true},
  20600. };
  20601. for (const auto &c : cases) {
  20602. std::promise<int> port_promise;
  20603. auto server_thread = serve_single_response(port_promise, c.response);
  20604. SSLClient cli("example.com", 443);
  20605. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20606. auto res = cli.Get("/");
  20607. server_thread.join();
  20608. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20609. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20610. if (res) {
  20611. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20612. }
  20613. }
  20614. }
  20615. #endif
  20616. // Records the client's error logger calls as "error METHOD path", or
  20617. // "error null" for a call without a request
  20618. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20619. return [&log](const Error &err, const Request *req) {
  20620. log.push_back(to_string(err) + " " +
  20621. (req ? req->method + " " + req->path : "null"));
  20622. };
  20623. }
  20624. // A failed request is reported once, with the request the caller made
  20625. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20626. Server svr;
  20627. svr.Get("/big", [](const Request &, Response &res) {
  20628. res.set_content(std::string(100000, 'b'), "text/plain");
  20629. });
  20630. auto port = svr.bind_to_any_port(HOST);
  20631. std::thread t([&]() { svr.listen_after_bind(); });
  20632. auto se = detail::scope_exit([&] {
  20633. svr.stop();
  20634. t.join();
  20635. });
  20636. svr.wait_until_ready();
  20637. Client cli(HOST, port);
  20638. std::vector<std::string> log;
  20639. cli.set_error_logger(record_errors(log));
  20640. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20641. cli.Get("/big", [](const char *, size_t) { return false; });
  20642. EXPECT_EQ(expected, log);
  20643. log.clear();
  20644. cli.Get("/big", [](size_t, size_t) { return false; });
  20645. EXPECT_EQ(expected, log);
  20646. }
  20647. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20648. // Fails while the body is read
  20649. auto broken = [](const Request &, Response &res) {
  20650. res.set_content_provider(10, "text/plain",
  20651. [](size_t, size_t, DataSink &) { return false; });
  20652. };
  20653. Server other;
  20654. other.Get("/broken", broken);
  20655. auto other_port = other.bind_to_any_port(HOST);
  20656. std::thread other_t([&]() { other.listen_after_bind(); });
  20657. auto other_se = detail::scope_exit([&] {
  20658. other.stop();
  20659. other_t.join();
  20660. });
  20661. other.wait_until_ready();
  20662. Server svr;
  20663. svr.Get("/broken", broken);
  20664. svr.Get("/same-origin",
  20665. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20666. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20667. res.set_redirect("http://" + std::string(HOST) + ":" +
  20668. std::to_string(other_port) + "/broken");
  20669. });
  20670. auto port = svr.bind_to_any_port(HOST);
  20671. std::thread t([&]() { svr.listen_after_bind(); });
  20672. auto se = detail::scope_exit([&] {
  20673. svr.stop();
  20674. t.join();
  20675. });
  20676. svr.wait_until_ready();
  20677. Client cli(HOST, port);
  20678. cli.set_follow_location(true);
  20679. std::vector<std::string> log;
  20680. cli.set_error_logger(record_errors(log));
  20681. for (auto path : {"/same-origin", "/cross-origin"}) {
  20682. log.clear();
  20683. auto res = cli.Get(path);
  20684. ASSERT_FALSE(res);
  20685. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20686. log);
  20687. }
  20688. }
  20689. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20690. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20691. std::vector<std::string> log;
  20692. cli.set_error_logger(record_errors(log));
  20693. auto handle = cli.open_stream("GET", "/x");
  20694. EXPECT_FALSE(handle.is_valid());
  20695. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20696. log);
  20697. });
  20698. }
  20699. #ifdef CPPHTTPLIB_SSL_ENABLED
  20700. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20701. // Not a TLS server, so the handshake fails. It waits for a request line in
  20702. // the handshake bytes, so a short read timeout lets it close quickly.
  20703. Server svr;
  20704. svr.set_read_timeout(0, 100000);
  20705. svr.Get("/x", [](const Request &, Response &res) {
  20706. res.set_content("x", "text/plain");
  20707. });
  20708. auto port = svr.bind_to_any_port(HOST);
  20709. std::thread t([&]() { svr.listen_after_bind(); });
  20710. auto se = detail::scope_exit([&] {
  20711. svr.stop();
  20712. t.join();
  20713. });
  20714. svr.wait_until_ready();
  20715. std::vector<std::string> log;
  20716. SSLClient cli(HOST, port);
  20717. cli.enable_server_certificate_verification(false);
  20718. cli.set_error_logger(record_errors(log));
  20719. auto res = cli.Get("/x");
  20720. ASSERT_FALSE(res);
  20721. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20722. log.clear();
  20723. auto handle = cli.open_stream("GET", "/x");
  20724. EXPECT_FALSE(handle.is_valid());
  20725. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20726. log.clear();
  20727. SSLClient no_ca(HOST, port);
  20728. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20729. no_ca.set_error_logger(record_errors(log));
  20730. res = no_ca.Get("/x");
  20731. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20732. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20733. }
  20734. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20735. #ifndef _WIN32
  20736. signal(SIGPIPE, SIG_IGN);
  20737. #endif
  20738. // Refused, answered with a challenge, or closed without an answer
  20739. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20740. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20741. "Content-Length: 0\r\n\r\n",
  20742. ""}) {
  20743. std::promise<int> port_promise;
  20744. auto server_thread = serve_single_response(port_promise, response);
  20745. SSLClient cli("example.com", 443);
  20746. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20747. std::vector<std::string> log;
  20748. cli.set_error_logger(record_errors(log));
  20749. auto res = cli.Get("/");
  20750. server_thread.join();
  20751. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20752. << response;
  20753. }
  20754. }
  20755. #endif
  20756. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20757. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20758. // the chunked coding and drop Content-Length, so a front-end that trusts
  20759. // Content-Length would disagree about where the body ends (response
  20760. // smuggling). The client must reject such a response.
  20761. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20762. for (const char *te : {"chunked", "gzip, chunked"}) {
  20763. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20764. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20765. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20766. "5\r\nhello\r\n0\r\n\r\n";
  20767. with_single_response(response, [&](Client &cli) {
  20768. auto res = cli.Get("/");
  20769. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20770. EXPECT_EQ(Error::Read, res.error()) << te;
  20771. });
  20772. with_single_response(response, [&](Client &cli) {
  20773. auto handle = cli.open_stream("GET", "/");
  20774. EXPECT_FALSE(handle.is_valid()) << te;
  20775. EXPECT_EQ(Error::Read, handle.error) << te;
  20776. });
  20777. }
  20778. }
  20779. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20780. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20781. // closing the connection (unlike a request, which must be rejected).
  20782. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20783. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20784. "Transfer-Encoding: chunked\r\n"
  20785. "Connection: close\r\n"
  20786. "\r\n"
  20787. "5\r\nhello\r\n0\r\n\r\n",
  20788. "HTTP/1.1 200 OK\r\n"
  20789. "Transfer-Encoding: gzip\r\n"
  20790. "Connection: close\r\n"
  20791. "\r\n"
  20792. "hello"}) {
  20793. with_single_response(response, [&](Client &cli) {
  20794. auto res = cli.Get("/");
  20795. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20796. EXPECT_EQ("hello", res->body);
  20797. });
  20798. with_single_response(response, [&](Client &cli) {
  20799. auto handle = cli.open_stream("GET", "/");
  20800. ASSERT_TRUE(handle.is_valid()) << response;
  20801. EXPECT_EQ("hello", read_all(handle));
  20802. });
  20803. }
  20804. }
  20805. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20806. // framing headers describe nothing to read and must not be rejected.
  20807. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20808. const std::string framing = "Content-Length: 5\r\n"
  20809. "Transfer-Encoding: chunked\r\n"
  20810. "Connection: close\r\n"
  20811. "\r\n";
  20812. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20813. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20814. });
  20815. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20816. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20817. });
  20818. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20819. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20820. with_single_response(response, [&](Client &cli) {
  20821. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20822. });
  20823. with_single_response(response, [&](Client &cli) {
  20824. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20825. });
  20826. }
  20827. }
  20828. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20829. // header section, so a stream opened on one has nothing to read, whatever
  20830. // framing or coding headers it carries.
  20831. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20832. struct Case {
  20833. const char *method;
  20834. const char *status;
  20835. };
  20836. // A reader of the declared body reports an early close when nothing
  20837. // follows, and hands back what does.
  20838. struct Framing {
  20839. const char *headers;
  20840. const char *after;
  20841. };
  20842. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20843. Case{"GET", "304 Not Modified"}}) {
  20844. for (const auto &f :
  20845. {Framing{"Content-Length: 5\r\n", ""},
  20846. Framing{"Content-Length: 5\r\n", "hello"},
  20847. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20848. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20849. // Not decoded, so a build without Brotli opens it too
  20850. Framing{"Content-Encoding: br\r\n", ""}}) {
  20851. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20852. "Connection: close\r\n"
  20853. "\r\n" +
  20854. f.after;
  20855. with_single_response(response, [&](Client &cli) {
  20856. auto handle = cli.open_stream(c.method, "/");
  20857. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20858. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20859. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20860. });
  20861. }
  20862. }
  20863. }
  20864. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20865. // response, is faulty framing, so the connection is not reused after it.
  20866. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20867. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20868. "Content-Length: 0\r\n"
  20869. "Transfer-Encoding: chunked\r\n"
  20870. "\r\n"
  20871. "5\r\nhello\r\n0\r\n\r\n",
  20872. "HTTP/1.0 200 Connection established\r\n"
  20873. "Connection: keep-alive\r\n"
  20874. "Transfer-Encoding: chunked\r\n"
  20875. "\r\n"
  20876. "5\r\nhello\r\n0\r\n\r\n"}) {
  20877. with_single_response(response, [&](Client &cli) {
  20878. cli.set_keep_alive(true);
  20879. auto res = cli.Get("/");
  20880. ASSERT_TRUE(res) << response;
  20881. EXPECT_EQ("hello", res->body);
  20882. EXPECT_FALSE(cli.is_socket_open()) << response;
  20883. });
  20884. }
  20885. }
  20886. // A payload max length of 0 means no limit, however the body is framed.
  20887. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20888. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20889. "Transfer-Encoding: chunked\r\n"
  20890. "\r\n"
  20891. "5\r\nhello\r\n0\r\n\r\n",
  20892. "HTTP/1.1 200 OK\r\n"
  20893. "Connection: close\r\n"
  20894. "\r\n"
  20895. "hello"}) {
  20896. with_single_response(response, [&](Client &cli) {
  20897. cli.set_payload_max_length(0);
  20898. auto res = cli.Get("/");
  20899. ASSERT_TRUE(res) << response;
  20900. EXPECT_EQ("hello", res->body) << response;
  20901. });
  20902. }
  20903. }
  20904. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20905. Server svr;
  20906. svr.set_payload_max_length(0);
  20907. svr.Post("/echo", [](const Request &req, Response &res) {
  20908. res.set_content(req.body, "text/plain");
  20909. });
  20910. auto port = svr.bind_to_any_port(HOST);
  20911. thread t = thread([&] { svr.listen_after_bind(); });
  20912. auto se = detail::scope_exit([&] {
  20913. svr.stop();
  20914. t.join();
  20915. ASSERT_FALSE(svr.is_running());
  20916. });
  20917. svr.wait_until_ready();
  20918. Client cli(HOST, port);
  20919. auto res = cli.Post(
  20920. "/echo",
  20921. [](size_t /*offset*/, DataSink &sink) {
  20922. sink.write("hello", 5);
  20923. sink.done();
  20924. return true;
  20925. },
  20926. "text/plain");
  20927. ASSERT_TRUE(res);
  20928. EXPECT_EQ(StatusCode::OK_200, res->status);
  20929. EXPECT_EQ("hello", res->body);
  20930. }
  20931. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20932. TEST_F(OpenStreamTest, Gzip) {
  20933. Client cli("127.0.0.1", port_);
  20934. auto handle = cli.open_stream("GET", "/compressible", {},
  20935. {{"Accept-Encoding", "gzip"}});
  20936. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20937. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20938. }
  20939. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20940. Client cli("127.0.0.1", port_);
  20941. auto handle =
  20942. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20943. {{"Accept-Encoding", "gzip"}});
  20944. ASSERT_TRUE(handle.is_valid());
  20945. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20946. EXPECT_EQ("123456789", read_all(handle));
  20947. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20948. }
  20949. #endif
  20950. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20951. TEST_F(OpenStreamTest, Brotli) {
  20952. Client cli("127.0.0.1", port_);
  20953. auto handle =
  20954. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20955. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20956. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20957. }
  20958. #endif
  20959. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20960. TEST_F(OpenStreamTest, Zstd) {
  20961. Client cli("127.0.0.1", port_);
  20962. auto handle = cli.open_stream("GET", "/compressible", {},
  20963. {{"Accept-Encoding", "zstd"}});
  20964. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20965. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20966. }
  20967. #endif
  20968. #ifdef CPPHTTPLIB_SSL_ENABLED
  20969. class SSLOpenStreamTest : public ::testing::Test {
  20970. protected:
  20971. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20972. void SetUp() override {
  20973. svr_.Get("/hello", [](const Request &, Response &res) {
  20974. res.set_content("Hello SSL World!", "text/plain");
  20975. });
  20976. svr_.Get("/chunked", [](const Request &, Response &res) {
  20977. res.set_chunked_content_provider("text/plain",
  20978. [](size_t offset, DataSink &sink) {
  20979. if (offset < 15) {
  20980. sink.write("chunk", 5);
  20981. return true;
  20982. }
  20983. sink.done();
  20984. return true;
  20985. });
  20986. });
  20987. svr_.Post("/echo", [](const Request &req, Response &res) {
  20988. res.set_content(req.body, req.get_header_value("Content-Type"));
  20989. });
  20990. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20991. std::string body = req.body;
  20992. res.set_chunked_content_provider(
  20993. "text/plain", [body](size_t offset, DataSink &sink) {
  20994. if (offset < body.size()) {
  20995. sink.write(body.data() + offset, body.size() - offset);
  20996. }
  20997. sink.done();
  20998. return true;
  20999. });
  21000. });
  21001. port_ = svr_.bind_to_any_port("127.0.0.1");
  21002. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21003. svr_.wait_until_ready();
  21004. }
  21005. void TearDown() override {
  21006. svr_.stop();
  21007. if (thread_.joinable()) thread_.join();
  21008. }
  21009. SSLServer svr_;
  21010. std::thread thread_;
  21011. int port_ = 0;
  21012. };
  21013. TEST_F(SSLOpenStreamTest, Basic) {
  21014. SSLClient cli("127.0.0.1", port_);
  21015. cli.enable_server_certificate_verification(false);
  21016. auto handle = cli.open_stream("GET", "/hello");
  21017. ASSERT_TRUE(handle.is_valid());
  21018. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21019. }
  21020. TEST_F(SSLOpenStreamTest, Chunked) {
  21021. SSLClient cli("127.0.0.1", port_);
  21022. cli.enable_server_certificate_verification(false);
  21023. auto handle = cli.open_stream("GET", "/chunked");
  21024. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21025. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21026. "Transfer-Encoding") == "chunked");
  21027. auto body = read_all(handle);
  21028. EXPECT_EQ("chunkchunkchunk", body);
  21029. }
  21030. TEST_F(SSLOpenStreamTest, Post) {
  21031. SSLClient cli("127.0.0.1", port_);
  21032. cli.enable_server_certificate_verification(false);
  21033. auto handle =
  21034. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21035. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21036. EXPECT_EQ(200, handle.response->status);
  21037. auto body = read_all(handle);
  21038. EXPECT_EQ("Hello SSL POST", body);
  21039. }
  21040. TEST_F(SSLOpenStreamTest, PostChunked) {
  21041. SSLClient cli("127.0.0.1", port_);
  21042. cli.enable_server_certificate_verification(false);
  21043. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21044. "Chunked SSL Data", "text/plain");
  21045. ASSERT_TRUE(handle.is_valid());
  21046. EXPECT_EQ(200, handle.response->status);
  21047. auto body = read_all(handle);
  21048. EXPECT_EQ("Chunked SSL Data", body);
  21049. }
  21050. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21051. // Content-Length is terminated by the server closing the connection. When the
  21052. // SSL peer sends a close_notify after the body, the client must treat it as a
  21053. // clean EOF and return a successful response rather than an error.
  21054. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21055. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21056. ASSERT_TRUE(svr.is_valid());
  21057. svr.set_keep_alive_max_count(1);
  21058. const std::string expected_body = "Hello from connection-close response!";
  21059. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21060. res.set_content_provider("text/plain",
  21061. [&](size_t offset, DataSink &sink) -> bool {
  21062. if (offset < expected_body.size()) {
  21063. sink.write(expected_body.data() + offset,
  21064. expected_body.size() - offset);
  21065. }
  21066. sink.done();
  21067. return true;
  21068. });
  21069. });
  21070. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21071. auto se = detail::scope_exit([&] {
  21072. svr.stop();
  21073. listen_thread.join();
  21074. ASSERT_FALSE(svr.is_running());
  21075. });
  21076. svr.wait_until_ready();
  21077. SSLClient cli(HOST, PORT);
  21078. cli.enable_server_certificate_verification(false);
  21079. auto res = cli.Get("/no-content-length");
  21080. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21081. EXPECT_EQ(StatusCode::OK_200, res->status);
  21082. EXPECT_EQ(expected_body, res->body);
  21083. }
  21084. #endif // CPPHTTPLIB_SSL_ENABLED
  21085. //==============================================================================
  21086. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21087. // results for various scenarios.
  21088. //==============================================================================
  21089. TEST(ParityTest, GetVsOpenStream) {
  21090. Server svr;
  21091. const std::string path = "/parity";
  21092. const std::string content = "Parity test content: hello world";
  21093. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21094. res.set_content(content, "text/plain");
  21095. });
  21096. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21097. auto se = detail::scope_exit([&] {
  21098. svr.stop();
  21099. t.join();
  21100. ASSERT_FALSE(svr.is_running());
  21101. });
  21102. svr.wait_until_ready();
  21103. Client cli(HOST, PORT);
  21104. // Non-stream path
  21105. auto r1 = cli.Get(path);
  21106. ASSERT_TRUE(r1);
  21107. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21108. // Stream path
  21109. auto h = cli.open_stream("GET", path);
  21110. ASSERT_TRUE(h.is_valid());
  21111. EXPECT_EQ(r1->body, read_all(h));
  21112. }
  21113. // Helper to compress data with provided compressor type T
  21114. template <typename Compressor>
  21115. static std::string compress_payload_for_parity(const std::string &in) {
  21116. std::string out;
  21117. Compressor compressor;
  21118. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21119. [&](const char *data, size_t n) {
  21120. out.append(data, n);
  21121. return true;
  21122. });
  21123. EXPECT_TRUE(ok);
  21124. return out;
  21125. }
  21126. // Helper function for compression parity tests
  21127. template <typename Compressor>
  21128. static void test_compression_parity(const std::string &original,
  21129. const std::string &path,
  21130. const std::string &encoding) {
  21131. const std::string compressed =
  21132. compress_payload_for_parity<Compressor>(original);
  21133. Server svr;
  21134. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21135. res.set_content(compressed, "application/octet-stream");
  21136. res.set_header("Content-Encoding", encoding);
  21137. });
  21138. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21139. auto se = detail::scope_exit([&] {
  21140. svr.stop();
  21141. t.join();
  21142. ASSERT_FALSE(svr.is_running());
  21143. });
  21144. svr.wait_until_ready();
  21145. Client cli(HOST, PORT);
  21146. // Non-streaming
  21147. {
  21148. auto res = cli.Get(path);
  21149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21150. EXPECT_EQ(StatusCode::OK_200, res->status);
  21151. EXPECT_EQ(original, res->body);
  21152. }
  21153. // Streaming
  21154. {
  21155. auto h = cli.open_stream("GET", path);
  21156. ASSERT_TRUE(h.is_valid());
  21157. EXPECT_EQ(original, read_all(h));
  21158. }
  21159. }
  21160. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21161. TEST(ParityTest, Gzip) {
  21162. test_compression_parity<detail::gzip_compressor>(
  21163. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21164. }
  21165. #endif
  21166. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21167. TEST(ParityTest, Brotli) {
  21168. test_compression_parity<detail::brotli_compressor>(
  21169. "Hello, brotli parity test payload", "/parity-br", "br");
  21170. }
  21171. #endif
  21172. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21173. TEST(ParityTest, Zstd) {
  21174. test_compression_parity<detail::zstd_compressor>(
  21175. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21176. }
  21177. #endif
  21178. //==============================================================================
  21179. // New Stream API Tests
  21180. //==============================================================================
  21181. inline std::string read_body(httplib::stream::Result &result) {
  21182. std::string body;
  21183. while (result.next()) {
  21184. body.append(result.data(), result.size());
  21185. }
  21186. return body;
  21187. }
  21188. TEST(ClientConnectionTest, Basic) {
  21189. httplib::ClientConnection conn;
  21190. EXPECT_FALSE(conn.is_open());
  21191. conn.sock = 1;
  21192. EXPECT_TRUE(conn.is_open());
  21193. httplib::ClientConnection conn2(std::move(conn));
  21194. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21195. conn2.sock = INVALID_SOCKET;
  21196. }
  21197. // Unified test server for all stream::* tests
  21198. class StreamApiTest : public ::testing::Test {
  21199. protected:
  21200. void SetUp() override {
  21201. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21202. res.set_content("Hello World!", "text/plain");
  21203. });
  21204. svr_.Get("/echo-params",
  21205. [](const httplib::Request &req, httplib::Response &res) {
  21206. std::string r;
  21207. for (const auto &p : req.params) {
  21208. if (!r.empty()) r += "&";
  21209. r += p.first + "=" + p.second;
  21210. }
  21211. res.set_content(r, "text/plain");
  21212. });
  21213. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21214. res.set_content(req.body, req.get_header_value("Content-Type"));
  21215. });
  21216. svr_.Post("/echo-headers",
  21217. [](const httplib::Request &req, httplib::Response &res) {
  21218. std::string r;
  21219. for (const auto &h : req.headers)
  21220. r += h.first + ": " + h.second + "\n";
  21221. res.set_content(r, "text/plain");
  21222. });
  21223. svr_.Post("/echo-params",
  21224. [](const httplib::Request &req, httplib::Response &res) {
  21225. std::string r = "params:";
  21226. for (const auto &p : req.params)
  21227. r += p.first + "=" + p.second + ";";
  21228. res.set_content(r + " body:" + req.body, "text/plain");
  21229. });
  21230. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21231. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21232. });
  21233. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21234. res.set_content("PUT:" + req.body, "text/plain");
  21235. });
  21236. svr_.Patch("/echo",
  21237. [](const httplib::Request &req, httplib::Response &res) {
  21238. res.set_content("PATCH:" + req.body, "text/plain");
  21239. });
  21240. svr_.Delete(
  21241. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21242. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21243. "text/plain");
  21244. });
  21245. svr_.Get("/head-test",
  21246. [](const httplib::Request &, httplib::Response &res) {
  21247. res.set_content("body for HEAD", "text/plain");
  21248. });
  21249. svr_.Options("/options",
  21250. [](const httplib::Request &, httplib::Response &res) {
  21251. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21252. });
  21253. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21254. svr_.wait_until_ready();
  21255. }
  21256. void TearDown() override {
  21257. svr_.stop();
  21258. if (thread_.joinable()) thread_.join();
  21259. }
  21260. httplib::Server svr_;
  21261. std::thread thread_;
  21262. };
  21263. // stream::Get tests
  21264. TEST_F(StreamApiTest, GetBasic) {
  21265. httplib::Client cli(HOST, PORT);
  21266. auto result = httplib::stream::Get(cli, "/hello");
  21267. ASSERT_TRUE(result.is_valid());
  21268. EXPECT_EQ(200, result.status());
  21269. EXPECT_EQ("Hello World!", read_body(result));
  21270. }
  21271. TEST_F(StreamApiTest, GetWithParams) {
  21272. httplib::Client cli(HOST, PORT);
  21273. httplib::Params params{{"foo", "bar"}};
  21274. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21275. ASSERT_TRUE(result.is_valid());
  21276. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21277. }
  21278. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21279. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21280. httplib::Client cli(HOST, PORT);
  21281. cli.set_payload_max_length(0);
  21282. auto result = httplib::stream::Get(cli, "/hello");
  21283. ASSERT_TRUE(result.is_valid());
  21284. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21285. EXPECT_EQ("Hello World!", read_body(result));
  21286. }
  21287. #endif
  21288. TEST_F(StreamApiTest, GetConnectionError) {
  21289. httplib::Client cli(HOST, 9999);
  21290. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21291. }
  21292. TEST_F(StreamApiTest, Get404) {
  21293. httplib::Client cli(HOST, PORT);
  21294. auto result = httplib::stream::Get(cli, "/nonexistent");
  21295. EXPECT_TRUE(result.is_valid());
  21296. EXPECT_EQ(404, result.status());
  21297. }
  21298. // stream::Post tests
  21299. TEST_F(StreamApiTest, PostBasic) {
  21300. httplib::Client cli(HOST, PORT);
  21301. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21302. "application/json");
  21303. ASSERT_TRUE(result.is_valid());
  21304. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21305. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21306. }
  21307. TEST_F(StreamApiTest, PostWithHeaders) {
  21308. httplib::Client cli(HOST, PORT);
  21309. httplib::Headers headers{{"X-Custom", "value"}};
  21310. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21311. "text/plain");
  21312. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21313. }
  21314. TEST_F(StreamApiTest, PostWithParams) {
  21315. httplib::Client cli(HOST, PORT);
  21316. httplib::Params params{{"k", "v"}};
  21317. auto result =
  21318. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21319. auto body = read_body(result);
  21320. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21321. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21322. }
  21323. TEST_F(StreamApiTest, PostLarge) {
  21324. httplib::Client cli(HOST, PORT);
  21325. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21326. size_t total = 0;
  21327. while (result.next()) {
  21328. total += result.size();
  21329. }
  21330. EXPECT_EQ(100u * 1024u, total);
  21331. }
  21332. // stream::Put/Patch tests
  21333. TEST_F(StreamApiTest, PutAndPatch) {
  21334. httplib::Client cli(HOST, PORT);
  21335. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21336. EXPECT_EQ("PUT:test", read_body(put));
  21337. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21338. EXPECT_EQ("PATCH:test", read_body(patch));
  21339. }
  21340. // stream::Delete tests
  21341. TEST_F(StreamApiTest, Delete) {
  21342. httplib::Client cli(HOST, PORT);
  21343. auto del1 = httplib::stream::Delete(cli, "/resource");
  21344. EXPECT_EQ("Deleted", read_body(del1));
  21345. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21346. EXPECT_EQ("Deleted:data", read_body(del2));
  21347. }
  21348. // stream::Head/Options tests
  21349. TEST_F(StreamApiTest, HeadAndOptions) {
  21350. httplib::Client cli(HOST, PORT);
  21351. auto head = httplib::stream::Head(cli, "/head-test");
  21352. EXPECT_TRUE(head.is_valid());
  21353. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21354. auto opts = httplib::stream::Options(cli, "/options");
  21355. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21356. }
  21357. // SSL stream::* tests
  21358. #ifdef CPPHTTPLIB_SSL_ENABLED
  21359. class SSLStreamApiTest : public ::testing::Test {
  21360. protected:
  21361. void SetUp() override {
  21362. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21363. res.set_content("Hello SSL!", "text/plain");
  21364. });
  21365. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21366. res.set_content(req.body, "text/plain");
  21367. });
  21368. port_ = svr_.bind_to_any_port("127.0.0.1");
  21369. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21370. svr_.wait_until_ready();
  21371. }
  21372. void TearDown() override {
  21373. svr_.stop();
  21374. if (thread_.joinable()) thread_.join();
  21375. }
  21376. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21377. std::thread thread_;
  21378. int port_ = 0;
  21379. };
  21380. TEST_F(SSLStreamApiTest, GetAndPost) {
  21381. httplib::SSLClient cli("127.0.0.1", port_);
  21382. cli.enable_server_certificate_verification(false);
  21383. auto get = httplib::stream::Get(cli, "/hello");
  21384. EXPECT_EQ("Hello SSL!", read_body(get));
  21385. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21386. EXPECT_EQ("test", read_body(post));
  21387. }
  21388. #endif
  21389. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21390. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21391. // BodyReader
  21392. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21393. // Test that read timeout during streaming is detected
  21394. // Use a large content-length response where server delays mid-stream
  21395. Server svr;
  21396. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21397. // Send a large response with delay in the middle
  21398. res.set_content_provider(
  21399. 1000, // content_length
  21400. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21401. if (offset < 100) {
  21402. // Send first 100 bytes immediately
  21403. std::string data(100, 'A');
  21404. sink.write(data.c_str(), data.size());
  21405. return true;
  21406. }
  21407. // Then delay longer than client timeout
  21408. std::this_thread::sleep_for(std::chrono::seconds(3));
  21409. std::string data(900, 'B');
  21410. sink.write(data.c_str(), data.size());
  21411. return true;
  21412. });
  21413. });
  21414. auto port = 8091;
  21415. std::thread t([&]() { svr.listen("localhost", port); });
  21416. svr.wait_until_ready();
  21417. Client cli("localhost", port);
  21418. cli.set_read_timeout(1, 0); // 1 second timeout
  21419. auto handle = cli.open_stream("GET", "/slow-stream");
  21420. ASSERT_TRUE(handle.is_valid());
  21421. char buf[256];
  21422. ssize_t total = 0;
  21423. ssize_t n;
  21424. bool got_error = false;
  21425. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21426. total += n;
  21427. }
  21428. if (n < 0) {
  21429. got_error = true;
  21430. // Should be timeout or read error
  21431. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21432. handle.get_read_error() == Error::Read)
  21433. << "Actual error: " << to_string(handle.get_read_error());
  21434. }
  21435. // Either we got an error, or we got less data than expected
  21436. EXPECT_TRUE(got_error || total < 1000)
  21437. << "Expected timeout but got all " << total << " bytes";
  21438. svr.stop();
  21439. t.join();
  21440. }
  21441. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21442. // Test connection closed detection via BodyReader
  21443. Server svr;
  21444. std::atomic<bool> close_now{false};
  21445. svr.Get("/will-close", [&](const Request &, Response &res) {
  21446. res.set_content_provider(
  21447. 10000, // Large content_length that we won't fully send
  21448. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21449. if (offset < 100) {
  21450. std::string data(100, 'X');
  21451. sink.write(data.c_str(), data.size());
  21452. return true;
  21453. }
  21454. // Wait for signal then abort
  21455. while (!close_now) {
  21456. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21457. }
  21458. return false; // Abort - server will close connection
  21459. });
  21460. });
  21461. auto port = 8092;
  21462. std::thread t([&]() { svr.listen("localhost", port); });
  21463. svr.wait_until_ready();
  21464. Client cli("localhost", port);
  21465. auto handle = cli.open_stream("GET", "/will-close");
  21466. ASSERT_TRUE(handle.is_valid());
  21467. char buf[256];
  21468. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21469. EXPECT_GT(n, 0) << "First read should succeed";
  21470. // Signal server to close
  21471. close_now = true;
  21472. // Keep reading until error or EOF
  21473. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21474. // Keep reading
  21475. }
  21476. // Should get an error since content_length wasn't satisfied
  21477. if (n < 0) {
  21478. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21479. handle.get_read_error() == Error::Read)
  21480. << "Actual error: " << to_string(handle.get_read_error());
  21481. }
  21482. svr.stop();
  21483. t.join();
  21484. }
  21485. #ifdef CPPHTTPLIB_SSL_ENABLED
  21486. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21487. // Test that read timeout during SSL streaming is detected
  21488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21489. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21490. res.set_content_provider(
  21491. 1000, "text/plain",
  21492. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21493. if (offset < 100) {
  21494. std::string data(100, 'A');
  21495. sink.write(data.c_str(), data.size());
  21496. return true;
  21497. }
  21498. std::this_thread::sleep_for(std::chrono::seconds(3));
  21499. std::string data(900, 'B');
  21500. sink.write(data.c_str(), data.size());
  21501. return true;
  21502. });
  21503. });
  21504. auto port = 8093;
  21505. std::thread t([&]() { svr.listen("localhost", port); });
  21506. svr.wait_until_ready();
  21507. SSLClient cli("localhost", port);
  21508. cli.enable_server_certificate_verification(false);
  21509. cli.set_read_timeout(1, 0); // 1 second timeout
  21510. auto handle = cli.open_stream("GET", "/slow-stream");
  21511. ASSERT_TRUE(handle.is_valid());
  21512. char buf[256];
  21513. ssize_t total = 0;
  21514. ssize_t n;
  21515. bool got_error = false;
  21516. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21517. total += n;
  21518. }
  21519. if (n < 0) {
  21520. got_error = true;
  21521. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21522. handle.get_read_error() == Error::Read)
  21523. << "Actual error: " << to_string(handle.get_read_error());
  21524. }
  21525. EXPECT_TRUE(got_error || total < 1000)
  21526. << "Expected timeout but got all " << total << " bytes";
  21527. svr.stop();
  21528. t.join();
  21529. }
  21530. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21531. // Test SSL connection closed detection
  21532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21533. std::atomic<bool> close_now{false};
  21534. svr.Get("/will-close", [&](const Request &, Response &res) {
  21535. res.set_content_provider(
  21536. 10000, "text/plain",
  21537. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21538. if (offset < 100) {
  21539. std::string data(100, 'X');
  21540. sink.write(data.c_str(), data.size());
  21541. return true;
  21542. }
  21543. while (!close_now) {
  21544. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21545. }
  21546. return false;
  21547. });
  21548. });
  21549. auto port = 8094;
  21550. std::thread t([&]() { svr.listen("localhost", port); });
  21551. svr.wait_until_ready();
  21552. SSLClient cli("localhost", port);
  21553. cli.enable_server_certificate_verification(false);
  21554. auto handle = cli.open_stream("GET", "/will-close");
  21555. ASSERT_TRUE(handle.is_valid());
  21556. char buf[256];
  21557. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21558. EXPECT_GT(n, 0);
  21559. // Signal server to close
  21560. close_now = true;
  21561. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21562. // Keep reading
  21563. }
  21564. if (n < 0) {
  21565. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21566. handle.get_read_error() == Error::Read)
  21567. << "Actual error: " << to_string(handle.get_read_error());
  21568. }
  21569. svr.stop();
  21570. t.join();
  21571. }
  21572. #endif
  21573. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21574. using namespace httplib;
  21575. // Create a test file
  21576. const char *fname = "etag_testfile.txt";
  21577. const char *content = "etag-content";
  21578. {
  21579. std::ofstream ofs(fname);
  21580. ofs << content;
  21581. ASSERT_TRUE(ofs.good());
  21582. }
  21583. Server svr;
  21584. svr.set_mount_point("/static", ".");
  21585. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21586. svr.wait_until_ready();
  21587. Client cli(HOST, PORT);
  21588. // First request: should get 200 with ETag header
  21589. auto res1 = cli.Get("/static/etag_testfile.txt");
  21590. ASSERT_TRUE(res1);
  21591. ASSERT_EQ(200, res1->status);
  21592. ASSERT_TRUE(res1->has_header("ETag"));
  21593. std::string etag = res1->get_header_value("ETag");
  21594. EXPECT_FALSE(etag.empty());
  21595. // Verify ETag format: W/"hex-hex"
  21596. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21597. EXPECT_EQ('W', etag[0]);
  21598. EXPECT_EQ('/', etag[1]);
  21599. EXPECT_EQ('"', etag[2]);
  21600. EXPECT_EQ('"', etag.back());
  21601. // Exact match: expect 304 Not Modified
  21602. Headers h2 = {{"If-None-Match", etag}};
  21603. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21604. ASSERT_TRUE(res2);
  21605. EXPECT_EQ(304, res2->status);
  21606. // Wildcard match: expect 304 Not Modified
  21607. Headers h3 = {{"If-None-Match", "*"}};
  21608. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21609. ASSERT_TRUE(res3);
  21610. EXPECT_EQ(304, res3->status);
  21611. // Non-matching ETag: expect 200
  21612. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21613. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21614. ASSERT_TRUE(res4);
  21615. EXPECT_EQ(200, res4->status);
  21616. // Multiple ETags with one matching: expect 304
  21617. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21618. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21619. ASSERT_TRUE(res5);
  21620. EXPECT_EQ(304, res5->status);
  21621. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21622. // that equivalent to the single comma-separated list above, so the match on
  21623. // the second line must still be found.
  21624. Headers h6;
  21625. h6.emplace("If-None-Match", "W/\"other\"");
  21626. h6.emplace("If-None-Match", etag);
  21627. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21628. ASSERT_TRUE(res6);
  21629. EXPECT_EQ(304, res6->status);
  21630. svr.stop();
  21631. t.join();
  21632. std::remove(fname);
  21633. }
  21634. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21635. using namespace httplib;
  21636. Server svr;
  21637. svr.set_mount_point("/static", ".");
  21638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21639. svr.wait_until_ready();
  21640. Client cli(HOST, PORT);
  21641. // Send If-None-Match: * to a non-existent file
  21642. Headers h = {{"If-None-Match", "*"}};
  21643. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21645. EXPECT_EQ(404, res->status);
  21646. svr.stop();
  21647. t.join();
  21648. }
  21649. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21650. using namespace httplib;
  21651. // Create a test file
  21652. const char *fname = "etag_boundary_testfile.txt";
  21653. const char *content = "boundary-test";
  21654. {
  21655. std::ofstream ofs(fname);
  21656. ofs << content;
  21657. ASSERT_TRUE(ofs.good());
  21658. }
  21659. Server svr;
  21660. svr.set_mount_point("/static", ".");
  21661. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21662. svr.wait_until_ready();
  21663. Client cli(HOST, PORT);
  21664. // Get the actual ETag
  21665. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21666. ASSERT_TRUE(res1);
  21667. ASSERT_EQ(200, res1->status);
  21668. ASSERT_TRUE(res1->has_header("ETag"));
  21669. std::string etag = res1->get_header_value("ETag");
  21670. // Test 1: Very long ETag value (longer than actual ETag)
  21671. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21672. Headers h1 = {{"If-None-Match", "W/"
  21673. "\"very-long-etag-value-that-is-much-longer-"
  21674. "than-the-actual-etag-value\""}};
  21675. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21676. ASSERT_TRUE(res2);
  21677. EXPECT_EQ(200, res2->status); // Should not match
  21678. // Test 2: Long string followed by wildcard
  21679. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21680. // string)
  21681. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21682. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21683. ASSERT_TRUE(res3);
  21684. EXPECT_EQ(304, res3->status); // Should match on "*"
  21685. // Test 3: Wildcard followed by long string
  21686. // Should match on "*" immediately and return 304
  21687. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21688. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21689. ASSERT_TRUE(res4);
  21690. EXPECT_EQ(304, res4->status); // Should match on "*"
  21691. // Test 4: Multiple long non-matching values
  21692. // Should NOT match and return 200 (test that all comparisons are safe)
  21693. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21694. "W/\"second-long-non-matching-value\", "
  21695. "W/\"third-long-non-matching-value\""}};
  21696. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21697. ASSERT_TRUE(res5);
  21698. EXPECT_EQ(200, res5->status); // Should not match
  21699. // Test 5: Single character that is not "*" (edge case)
  21700. Headers h5 = {{"If-None-Match", "X"}};
  21701. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21702. ASSERT_TRUE(res6);
  21703. EXPECT_EQ(200, res6->status); // Should not match
  21704. svr.stop();
  21705. t.join();
  21706. std::remove(fname);
  21707. }
  21708. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21709. using namespace httplib;
  21710. // Create a test file
  21711. const char *fname = "ims_testfile.txt";
  21712. const char *content = "if-modified-since-test";
  21713. {
  21714. std::ofstream ofs(fname);
  21715. ofs << content;
  21716. ASSERT_TRUE(ofs.good());
  21717. }
  21718. Server svr;
  21719. svr.set_mount_point("/static", ".");
  21720. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21721. svr.wait_until_ready();
  21722. Client cli(HOST, PORT);
  21723. // First request: should get 200 with Last-Modified header
  21724. auto res1 = cli.Get("/static/ims_testfile.txt");
  21725. ASSERT_TRUE(res1);
  21726. ASSERT_EQ(200, res1->status);
  21727. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21728. std::string last_modified = res1->get_header_value("Last-Modified");
  21729. EXPECT_FALSE(last_modified.empty());
  21730. // If-Modified-Since with same time: expect 304
  21731. Headers h2 = {{"If-Modified-Since", last_modified}};
  21732. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21733. ASSERT_TRUE(res2);
  21734. EXPECT_EQ(304, res2->status);
  21735. // If-Modified-Since with future time: expect 304
  21736. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21737. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21738. ASSERT_TRUE(res3);
  21739. EXPECT_EQ(304, res3->status);
  21740. // If-Modified-Since with past time: expect 200
  21741. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21742. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21743. ASSERT_TRUE(res4);
  21744. EXPECT_EQ(200, res4->status);
  21745. // If-None-Match takes precedence over If-Modified-Since
  21746. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21747. ASSERT_TRUE(res1->has_header("ETag"));
  21748. std::string etag = res1->get_header_value("ETag");
  21749. Headers h5 = {{"If-None-Match", etag},
  21750. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21751. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21752. ASSERT_TRUE(res5);
  21753. EXPECT_EQ(304, res5->status);
  21754. svr.stop();
  21755. t.join();
  21756. std::remove(fname);
  21757. }
  21758. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21759. using namespace httplib;
  21760. Server svr;
  21761. // Endpoint that returns compressible content
  21762. svr.Get("/compressible", [](const Request &, Response &res) {
  21763. // Return a large enough body to trigger compression
  21764. std::string body(1000, 'a');
  21765. res.set_content(body, "text/plain");
  21766. });
  21767. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21768. svr.wait_until_ready();
  21769. Client cli(HOST, PORT);
  21770. // Request with gzip support: should get Vary header when compressed
  21771. cli.set_compress(true);
  21772. auto res1 = cli.Get("/compressible");
  21773. ASSERT_TRUE(res1);
  21774. EXPECT_EQ(200, res1->status);
  21775. // If Content-Encoding is set, Vary should also be set
  21776. if (res1->has_header("Content-Encoding")) {
  21777. EXPECT_TRUE(res1->has_header("Vary"));
  21778. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21779. }
  21780. // Request without Accept-Encoding header: should not have compression
  21781. Headers h_no_compress;
  21782. auto res2 = cli.Get("/compressible", h_no_compress);
  21783. ASSERT_TRUE(res2);
  21784. EXPECT_EQ(200, res2->status);
  21785. // Verify Vary header is present when compression is applied
  21786. // (the exact behavior depends on server configuration)
  21787. svr.stop();
  21788. t.join();
  21789. }
  21790. TEST(ETagTest, IfRangeWithETag) {
  21791. using namespace httplib;
  21792. // Create a test file with known content
  21793. const char *fname = "if_range_testfile.txt";
  21794. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21795. {
  21796. std::ofstream ofs(fname);
  21797. ofs << content;
  21798. ASSERT_TRUE(ofs.good());
  21799. }
  21800. Server svr;
  21801. svr.set_mount_point("/static", ".");
  21802. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21803. svr.wait_until_ready();
  21804. Client cli(HOST, PORT);
  21805. // First request: get ETag
  21806. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21807. ASSERT_TRUE(res1);
  21808. ASSERT_EQ(200, res1->status);
  21809. ASSERT_TRUE(res1->has_header("ETag"));
  21810. std::string etag = res1->get_header_value("ETag");
  21811. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21812. // Since our server generates weak ETags (W/"..."), If-Range with our
  21813. // ETag should NOT result in partial content - it should return full content.
  21814. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21815. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21816. ASSERT_TRUE(res2);
  21817. // Weak ETag in If-Range -> full content (200), not partial (206)
  21818. EXPECT_EQ(200, res2->status);
  21819. EXPECT_EQ(content, res2->body);
  21820. EXPECT_FALSE(res2->has_header("Content-Range"));
  21821. // Range request with non-matching If-Range (ETag): should get 200 (full
  21822. // content)
  21823. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21824. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21825. ASSERT_TRUE(res3);
  21826. EXPECT_EQ(200, res3->status);
  21827. EXPECT_EQ(content, res3->body);
  21828. EXPECT_FALSE(res3->has_header("Content-Range"));
  21829. // Range request with strong ETag (hypothetical - our server doesn't generate
  21830. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21831. // should return full content)
  21832. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21833. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21834. ASSERT_TRUE(res4);
  21835. EXPECT_EQ(200, res4->status);
  21836. EXPECT_EQ(content, res4->body);
  21837. EXPECT_FALSE(res4->has_header("Content-Range"));
  21838. svr.stop();
  21839. t.join();
  21840. std::remove(fname);
  21841. }
  21842. TEST(ETagTest, IfRangeWithDate) {
  21843. using namespace httplib;
  21844. // Create a test file
  21845. const char *fname = "if_range_date_testfile.txt";
  21846. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21847. {
  21848. std::ofstream ofs(fname);
  21849. ofs << content;
  21850. ASSERT_TRUE(ofs.good());
  21851. }
  21852. Server svr;
  21853. svr.set_mount_point("/static", ".");
  21854. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21855. svr.wait_until_ready();
  21856. Client cli(HOST, PORT);
  21857. // First request: get Last-Modified
  21858. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21859. ASSERT_TRUE(res1);
  21860. ASSERT_EQ(200, res1->status);
  21861. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21862. std::string last_modified = res1->get_header_value("Last-Modified");
  21863. // Range request with matching If-Range (date): should get 206
  21864. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21865. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21866. ASSERT_TRUE(res2);
  21867. EXPECT_EQ(206, res2->status);
  21868. EXPECT_EQ("FGHIJ", res2->body);
  21869. // Range request with old If-Range date: should get 200 (full content)
  21870. Headers h3 = {{"Range", "bytes=5-9"},
  21871. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21872. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21873. ASSERT_TRUE(res3);
  21874. EXPECT_EQ(200, res3->status);
  21875. EXPECT_EQ(content, res3->body);
  21876. // Range request with future If-Range date: should get 206
  21877. Headers h4 = {{"Range", "bytes=0-4"},
  21878. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21879. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21880. ASSERT_TRUE(res4);
  21881. EXPECT_EQ(206, res4->status);
  21882. EXPECT_EQ("ABCDE", res4->body);
  21883. svr.stop();
  21884. t.join();
  21885. std::remove(fname);
  21886. }
  21887. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21888. using namespace httplib;
  21889. const char *fname = "etag_malformed.txt";
  21890. const char *content = "malformed-etag";
  21891. {
  21892. std::ofstream ofs(fname);
  21893. ofs << content;
  21894. ASSERT_TRUE(ofs.good());
  21895. }
  21896. Server svr;
  21897. svr.set_mount_point("/static", ".");
  21898. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21899. svr.wait_until_ready();
  21900. Client cli(HOST, PORT);
  21901. // baseline: should get 200 and an ETag
  21902. auto res1 = cli.Get("/static/etag_malformed.txt");
  21903. ASSERT_TRUE(res1);
  21904. ASSERT_EQ(200, res1->status);
  21905. ASSERT_TRUE(res1->has_header("ETag"));
  21906. // Malformed ETag value (missing quotes) should be treated as non-matching
  21907. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21908. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21909. ASSERT_TRUE(res_bad);
  21910. EXPECT_EQ(200, res_bad->status);
  21911. // Whitespace-only header value should be considered invalid / non-matching
  21912. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21913. "Host: localhost\r\n"
  21914. "If-None-Match: \r\n"
  21915. "Connection: close\r\n"
  21916. "\r\n";
  21917. std::string out;
  21918. ASSERT_TRUE(send_request(5, raw_req, &out));
  21919. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21920. svr.stop();
  21921. t.join();
  21922. std::remove(fname);
  21923. }
  21924. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21925. using namespace httplib;
  21926. const char *fname = "ims_invalid_format.txt";
  21927. const char *content = "ims-bad-format";
  21928. {
  21929. std::ofstream ofs(fname);
  21930. ofs << content;
  21931. ASSERT_TRUE(ofs.good());
  21932. }
  21933. Server svr;
  21934. svr.set_mount_point("/static", ".");
  21935. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21936. svr.wait_until_ready();
  21937. Client cli(HOST, PORT);
  21938. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21939. ASSERT_TRUE(res1);
  21940. ASSERT_EQ(200, res1->status);
  21941. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21942. // If-Modified-Since with invalid format should not result in 304
  21943. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21944. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21945. ASSERT_TRUE(res_bad);
  21946. EXPECT_EQ(200, res_bad->status);
  21947. // If-Range with invalid date format should be treated as mismatch -> full
  21948. // content (200)
  21949. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21950. {"If-Range", "invalid-date"}};
  21951. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21952. ASSERT_TRUE(res_ifrange);
  21953. EXPECT_EQ(200, res_ifrange->status);
  21954. svr.stop();
  21955. t.join();
  21956. std::remove(fname);
  21957. }
  21958. TEST(ETagTest, IfRangeWithMalformedETag) {
  21959. using namespace httplib;
  21960. const char *fname = "ifrange_malformed.txt";
  21961. const std::string content = "0123456789";
  21962. {
  21963. std::ofstream ofs(fname);
  21964. ofs << content;
  21965. ASSERT_TRUE(ofs.good());
  21966. }
  21967. Server svr;
  21968. svr.set_mount_point("/static", ".");
  21969. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21970. svr.wait_until_ready();
  21971. Client cli(HOST, PORT);
  21972. // First request: get ETag
  21973. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21974. ASSERT_TRUE(res1);
  21975. ASSERT_EQ(200, res1->status);
  21976. ASSERT_TRUE(res1->has_header("ETag"));
  21977. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21978. // full content (200)
  21979. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21980. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21981. ASSERT_TRUE(res2);
  21982. EXPECT_EQ(200, res2->status);
  21983. EXPECT_EQ(content, res2->body);
  21984. svr.stop();
  21985. t.join();
  21986. std::remove(fname);
  21987. }
  21988. TEST(ETagTest, ExtremeLargeDateValues) {
  21989. using namespace httplib;
  21990. const char *fname = "ims_extreme_date.txt";
  21991. const char *content = "ims-extreme-date";
  21992. {
  21993. std::ofstream ofs(fname);
  21994. ofs << content;
  21995. ASSERT_TRUE(ofs.good());
  21996. }
  21997. Server svr;
  21998. svr.set_mount_point("/static", ".");
  21999. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22000. svr.wait_until_ready();
  22001. Client cli(HOST, PORT);
  22002. auto res1 = cli.Get(std::string("/static/") + fname);
  22003. ASSERT_TRUE(res1);
  22004. ASSERT_EQ(200, res1->status);
  22005. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22006. // Extremely large year that may overflow date parsing routines.
  22007. Headers h_large_date = {
  22008. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22009. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22010. ASSERT_TRUE(res_bad);
  22011. // Expect server to treat this as invalid/mismatch and return full content
  22012. EXPECT_EQ(200, res_bad->status);
  22013. // If-Range with extremely large date should be treated as mismatch -> full
  22014. // content (200)
  22015. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22016. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22017. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22018. ASSERT_TRUE(res_ifrange);
  22019. EXPECT_EQ(200, res_ifrange->status);
  22020. svr.stop();
  22021. t.join();
  22022. std::remove(fname);
  22023. }
  22024. TEST(ETagTest, NegativeFileModificationTime) {
  22025. using namespace httplib;
  22026. const char *fname = "ims_negative_mtime.txt";
  22027. const std::string content = "negative-mtime";
  22028. {
  22029. std::ofstream ofs(fname);
  22030. ofs << content;
  22031. ASSERT_TRUE(ofs.good());
  22032. }
  22033. // Try to set file mtime to a negative value. This may fail on some
  22034. // platforms/filesystems; if it fails, the test will still verify server
  22035. // behaves safely by performing a regular conditional request.
  22036. #if defined(__APPLE__) || defined(__linux__)
  22037. bool set_negative = false;
  22038. do {
  22039. struct timeval times[2];
  22040. // access time: now
  22041. times[0].tv_sec = time(nullptr);
  22042. times[0].tv_usec = 0;
  22043. // modification time: negative (e.g., -1)
  22044. times[1].tv_sec = -1;
  22045. times[1].tv_usec = 0;
  22046. if (utimes(fname, times) == 0) { set_negative = true; }
  22047. } while (0);
  22048. #else
  22049. bool set_negative = false;
  22050. #endif
  22051. Server svr;
  22052. svr.set_mount_point("/static", ".");
  22053. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22054. svr.wait_until_ready();
  22055. Client cli(HOST, PORT);
  22056. auto res1 = cli.Get(std::string("/static/") + fname);
  22057. ASSERT_TRUE(res1);
  22058. ASSERT_EQ(200, res1->status);
  22059. bool has_last_modified = res1->has_header("Last-Modified");
  22060. std::string last_modified;
  22061. if (has_last_modified) {
  22062. last_modified = res1->get_header_value("Last-Modified");
  22063. }
  22064. if (set_negative) {
  22065. // If we successfully set a negative mtime, ensure server returns a
  22066. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22067. // with an old date and ensure server handles it without crash.
  22068. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22069. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22070. ASSERT_TRUE(res2);
  22071. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22072. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22073. } else {
  22074. // Could not set negative mtime on this platform; fall back to verifying
  22075. // that normal invalid/malformed dates are treated safely (non-304).
  22076. Headers h_bad_date = {
  22077. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22078. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22079. ASSERT_TRUE(res_bad);
  22080. EXPECT_EQ(200, res_bad->status);
  22081. }
  22082. svr.stop();
  22083. t.join();
  22084. std::remove(fname);
  22085. }
  22086. //==============================================================================
  22087. // Integration Tests with Server
  22088. //==============================================================================
  22089. class SSEIntegrationTest : public ::testing::Test {
  22090. protected:
  22091. void SetUp() override {
  22092. stop_server_.store(false);
  22093. events_.clear();
  22094. server_ = httplib::detail::make_unique<Server>();
  22095. setup_server();
  22096. start_server();
  22097. }
  22098. void TearDown() override {
  22099. stop_server_.store(true);
  22100. event_cv_.notify_all();
  22101. server_->stop();
  22102. if (server_thread_.joinable()) { server_thread_.join(); }
  22103. }
  22104. void setup_server() {
  22105. // Simple SSE endpoint
  22106. server_->Get("/events", [this](const Request &req, Response &res) {
  22107. auto last_id = req.get_header_value("Last-Event-ID");
  22108. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22109. res.set_chunked_content_provider(
  22110. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22111. std::unique_lock<std::mutex> lock(event_mutex_);
  22112. if (event_cv_.wait_for(
  22113. lock, std::chrono::milliseconds(200), [this] {
  22114. return !events_.empty() || stop_server_.load();
  22115. })) {
  22116. if (stop_server_.load()) { return false; }
  22117. if (!events_.empty()) {
  22118. std::string event = events_.front();
  22119. events_.erase(events_.begin());
  22120. sink.write(event.data(), event.size());
  22121. return true;
  22122. }
  22123. }
  22124. return !stop_server_.load();
  22125. });
  22126. });
  22127. // Endpoint that returns error
  22128. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22129. res.status = 500;
  22130. res.set_content("Internal Server Error", "text/plain");
  22131. });
  22132. // Endpoint for custom event types
  22133. server_->Get("/custom-events", [](const Request &, Response &res) {
  22134. res.set_chunked_content_provider(
  22135. "text/event-stream", [](size_t offset, DataSink &sink) {
  22136. if (offset == 0) {
  22137. std::string event = "event: update\ndata: updated\n\n"
  22138. "event: delete\ndata: deleted\n\n";
  22139. sink.write(event.data(), event.size());
  22140. }
  22141. return false; // End stream after sending
  22142. });
  22143. });
  22144. }
  22145. void start_server() {
  22146. port_ = server_->bind_to_any_port(HOST);
  22147. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22148. // Wait for server to start
  22149. while (!server_->is_running()) {
  22150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22151. }
  22152. }
  22153. int get_port() const { return port_; }
  22154. void send_event(const std::string &event) {
  22155. std::lock_guard<std::mutex> lock(event_mutex_);
  22156. events_.push_back(event);
  22157. event_cv_.notify_all();
  22158. }
  22159. std::unique_ptr<Server> server_;
  22160. std::thread server_thread_;
  22161. std::mutex event_mutex_;
  22162. std::condition_variable event_cv_;
  22163. std::vector<std::string> events_;
  22164. std::atomic<bool> stop_server_{false};
  22165. std::string last_received_event_id_;
  22166. int port_ = 0;
  22167. };
  22168. //==============================================================================
  22169. // SSE Parsing Tests
  22170. //==============================================================================
  22171. class SSEParsingTest : public SSEIntegrationTest {
  22172. protected:
  22173. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22174. // A trailing sentinel event tells when the whole stream has been parsed.
  22175. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22176. auto body = stream + "event: end\ndata: end\n\n";
  22177. server_->Get("/parse", [body](const Request &, Response &res) {
  22178. res.set_content(body, "text/event-stream");
  22179. });
  22180. return collect("/parse");
  22181. }
  22182. // Runs SSEClient against path until an "end" event arrives and returns the
  22183. // messages dispatched before it
  22184. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22185. Client client(HOST, get_port());
  22186. sse::SSEClient sse(client, path);
  22187. std::mutex mutex;
  22188. std::condition_variable cv;
  22189. std::vector<sse::SSEMessage> messages;
  22190. auto done = false;
  22191. sse.on_message([&](const sse::SSEMessage &msg) {
  22192. std::lock_guard<std::mutex> lock(mutex);
  22193. // Ignore a replay from a reconnect that races with stop()
  22194. if (!done) { messages.push_back(msg); }
  22195. });
  22196. sse.on_event("end", [&](const sse::SSEMessage &) {
  22197. std::lock_guard<std::mutex> lock(mutex);
  22198. done = true;
  22199. cv.notify_all();
  22200. });
  22201. sse.set_reconnect_interval(100);
  22202. sse.start_async();
  22203. {
  22204. std::unique_lock<std::mutex> lock(mutex);
  22205. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22206. }
  22207. sse.stop();
  22208. EXPECT_TRUE(done);
  22209. return messages;
  22210. }
  22211. };
  22212. TEST_F(SSEParsingTest, SingleLineData) {
  22213. auto msgs = parse("data: hello\n\n");
  22214. ASSERT_EQ(msgs.size(), 1u);
  22215. EXPECT_EQ(msgs[0].data, "hello");
  22216. EXPECT_EQ(msgs[0].event, "message");
  22217. }
  22218. TEST_F(SSEParsingTest, MultiLineData) {
  22219. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22220. ASSERT_EQ(msgs.size(), 1u);
  22221. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22222. }
  22223. TEST_F(SSEParsingTest, CustomEventType) {
  22224. auto msgs = parse("event: update\ndata: payload\n\n");
  22225. ASSERT_EQ(msgs.size(), 1u);
  22226. EXPECT_EQ(msgs[0].event, "update");
  22227. EXPECT_EQ(msgs[0].data, "payload");
  22228. }
  22229. TEST_F(SSEParsingTest, EventIdHandling) {
  22230. auto msgs = parse("id: 12345\ndata: test\n\n");
  22231. ASSERT_EQ(msgs.size(), 1u);
  22232. EXPECT_EQ(msgs[0].id, "12345");
  22233. }
  22234. TEST_F(SSEParsingTest, EmptyEventId) {
  22235. auto msgs = parse("id:\ndata: test\n\n");
  22236. ASSERT_EQ(msgs.size(), 1u);
  22237. EXPECT_EQ(msgs[0].id, "");
  22238. }
  22239. TEST_F(SSEParsingTest, CommentsIgnored) {
  22240. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22241. ASSERT_EQ(msgs.size(), 1u);
  22242. EXPECT_EQ(msgs[0].data, "hello");
  22243. EXPECT_EQ(msgs[0].event, "message");
  22244. }
  22245. TEST_F(SSEParsingTest, ColonInValue) {
  22246. auto msgs = parse("data: hello:world:test\n\n");
  22247. ASSERT_EQ(msgs.size(), 1u);
  22248. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22249. }
  22250. TEST_F(SSEParsingTest, FieldNameOnly) {
  22251. // A line without a colon is a field name with an empty value
  22252. auto msgs = parse("data\n\n");
  22253. ASSERT_EQ(msgs.size(), 1u);
  22254. EXPECT_EQ(msgs[0].data, "");
  22255. }
  22256. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22257. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22258. ASSERT_EQ(msgs.size(), 1u);
  22259. EXPECT_EQ(msgs[0].event, "update");
  22260. EXPECT_EQ(msgs[0].data, "hello");
  22261. }
  22262. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22263. auto msgs = parse("data\r\n\r\n");
  22264. ASSERT_EQ(msgs.size(), 1u);
  22265. EXPECT_EQ(msgs[0].data, "");
  22266. }
  22267. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22268. auto msgs = parse("event: update\rdata: hello\r\r");
  22269. ASSERT_EQ(msgs.size(), 1u);
  22270. EXPECT_EQ(msgs[0].event, "update");
  22271. EXPECT_EQ(msgs[0].data, "hello");
  22272. }
  22273. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22274. // Chunk boundaries fall inside every \r\n and right before the first one
  22275. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22276. "\n\r", "\nevent: end\ndata: end\n\n"};
  22277. server_->Get("/split", [chunks](const Request &, Response &res) {
  22278. auto i = std::make_shared<size_t>(0);
  22279. res.set_chunked_content_provider(
  22280. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22281. if (*i == chunks.size()) {
  22282. sink.done();
  22283. } else {
  22284. sink.write(chunks[*i].data(), chunks[*i].size());
  22285. (*i)++;
  22286. }
  22287. return true;
  22288. });
  22289. });
  22290. auto msgs = collect("/split");
  22291. ASSERT_EQ(msgs.size(), 1u);
  22292. EXPECT_EQ(msgs[0].event, "update");
  22293. EXPECT_EQ(msgs[0].data, "hello");
  22294. }
  22295. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22296. // Only a BOM at the start of the stream is ignored
  22297. auto msgs = parse("\xEF\xBB\xBF"
  22298. "data: first\n\n"
  22299. "\xEF\xBB\xBF"
  22300. "data: second\n\n");
  22301. ASSERT_EQ(msgs.size(), 1u);
  22302. EXPECT_EQ(msgs[0].data, "first");
  22303. }
  22304. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22305. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22306. ASSERT_EQ(msgs.size(), 1u);
  22307. EXPECT_EQ(msgs[0].data, "hello");
  22308. EXPECT_EQ(msgs[0].event, "message");
  22309. }
  22310. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22311. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22312. ASSERT_EQ(msgs.size(), 2u);
  22313. EXPECT_EQ(msgs[0].data, "hello");
  22314. EXPECT_EQ(msgs[1].data, "hello");
  22315. }
  22316. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22317. // An event without data is not dispatched, and its type must not leak
  22318. // into the next event
  22319. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22320. ASSERT_EQ(msgs.size(), 1u);
  22321. EXPECT_EQ(msgs[0].event, "message");
  22322. EXPECT_EQ(msgs[0].data, "hello");
  22323. }
  22324. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22325. // Also when the empty field replaces an earlier type
  22326. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22327. ASSERT_EQ(msgs.size(), 2u);
  22328. EXPECT_EQ(msgs[0].event, "message");
  22329. EXPECT_EQ(msgs[1].event, "message");
  22330. }
  22331. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22332. // The first connection sends only an id; the second echoes back the
  22333. // Last-Event-ID it was reconnected with
  22334. std::atomic<int> connection_count{0};
  22335. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22336. if (connection_count++ == 0) {
  22337. res.set_content("id: 42\n\n", "text/event-stream");
  22338. } else {
  22339. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22340. "\n\nevent: end\ndata: end\n\n",
  22341. "text/event-stream");
  22342. }
  22343. });
  22344. auto msgs = collect("/id-only");
  22345. ASSERT_EQ(msgs.size(), 1u);
  22346. EXPECT_EQ(msgs[0].data, "42");
  22347. }
  22348. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22349. // The first connection sets an id and then clears it with an empty one; the
  22350. // second reports whether it was reconnected with a Last-Event-ID
  22351. std::atomic<int> connection_count{0};
  22352. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22353. if (connection_count++ == 0) {
  22354. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22355. "text/event-stream");
  22356. } else {
  22357. res.set_content(
  22358. std::string("data: ") +
  22359. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22360. "\n\nevent: end\ndata: end\n\n",
  22361. "text/event-stream");
  22362. }
  22363. });
  22364. auto msgs = collect("/id-clear");
  22365. ASSERT_EQ(msgs.size(), 3u);
  22366. EXPECT_EQ(msgs[0].id, "1");
  22367. EXPECT_EQ(msgs[1].id, "");
  22368. EXPECT_EQ(msgs[2].data, "not sent");
  22369. }
  22370. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22371. // The first connection sets an id and then sends ids that cannot be carried
  22372. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22373. // with
  22374. std::atomic<int> connection_count{0};
  22375. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22376. if (connection_count++ == 0) {
  22377. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22378. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22379. "text/event-stream");
  22380. } else {
  22381. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22382. "\n\nevent: end\ndata: end\n\n",
  22383. "text/event-stream");
  22384. }
  22385. });
  22386. auto msgs = collect("/id-unsendable");
  22387. ASSERT_EQ(msgs.size(), 1u);
  22388. EXPECT_EQ(msgs[0].data, "42");
  22389. }
  22390. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22391. auto msgs = parse("event: notification\nid: evt-42\n"
  22392. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22393. ASSERT_EQ(msgs.size(), 1u);
  22394. EXPECT_EQ(msgs[0].event, "notification");
  22395. EXPECT_EQ(msgs[0].id, "evt-42");
  22396. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22397. }
  22398. TEST(SSEMessageTest, Clear) {
  22399. sse::SSEMessage msg;
  22400. msg.event = "custom";
  22401. msg.data = "some data";
  22402. msg.id = "123";
  22403. msg.clear();
  22404. EXPECT_EQ(msg.event, "message");
  22405. EXPECT_EQ(msg.data, "");
  22406. EXPECT_EQ(msg.id, "");
  22407. }
  22408. //==============================================================================
  22409. // SSE Integration Tests
  22410. //==============================================================================
  22411. // Test: Successful connection and on_open callback
  22412. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22413. // Add a simple endpoint that sends one event and closes
  22414. server_->Get("/simple-event", [](const Request &, Response &res) {
  22415. res.set_chunked_content_provider(
  22416. "text/event-stream", [](size_t offset, DataSink &sink) {
  22417. if (offset == 0) {
  22418. std::string event = "data: hello\n\n";
  22419. sink.write(event.data(), event.size());
  22420. }
  22421. return false; // Close stream after sending
  22422. });
  22423. });
  22424. Client client("localhost", get_port());
  22425. sse::SSEClient sse(client, "/simple-event");
  22426. std::atomic<bool> open_called{false};
  22427. std::atomic<bool> message_received{false};
  22428. sse.on_open([&open_called]() { open_called.store(true); });
  22429. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22430. if (msg.data == "hello") { message_received.store(true); }
  22431. });
  22432. sse.set_reconnect_interval(100);
  22433. sse.set_max_reconnect_attempts(1);
  22434. // Start async
  22435. sse.start_async();
  22436. // Wait for message to be processed
  22437. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22438. sse.stop();
  22439. EXPECT_TRUE(open_called.load());
  22440. EXPECT_TRUE(message_received.load());
  22441. }
  22442. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22443. // A data line that never ends.
  22444. server_->Get("/endless-line", [](const Request &, Response &res) {
  22445. res.set_chunked_content_provider(
  22446. "text/event-stream", [](size_t offset, DataSink &sink) {
  22447. if (offset == 0) { sink.write("data: ", 6); }
  22448. std::string chunk(64 * 1024, 'A');
  22449. return sink.write(chunk.data(), chunk.size());
  22450. });
  22451. });
  22452. Client client("localhost", get_port());
  22453. sse::SSEClient sse(client, "/endless-line");
  22454. std::atomic<bool> too_long{false};
  22455. sse.on_error([&](Error err) {
  22456. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22457. });
  22458. sse.set_max_reconnect_attempts(1);
  22459. sse.start_async();
  22460. for (int i = 0; i < 500 && !too_long; i++) {
  22461. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22462. }
  22463. sse.stop();
  22464. EXPECT_TRUE(too_long);
  22465. }
  22466. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22467. // Far more in all than the client's payload limit below.
  22468. server_->Get("/many-events", [](const Request &, Response &res) {
  22469. res.set_chunked_content_provider(
  22470. "text/event-stream", [](size_t offset, DataSink &sink) {
  22471. if (offset == 0) {
  22472. std::string events;
  22473. for (int i = 0; i < 1000; i++) {
  22474. events += "data: message\n\n";
  22475. }
  22476. sink.write(events.data(), events.size());
  22477. }
  22478. return false;
  22479. });
  22480. });
  22481. Client client("localhost", get_port());
  22482. client.set_payload_max_length(1024);
  22483. sse::SSEClient sse(client, "/many-events");
  22484. std::atomic<int> messages{0};
  22485. std::atomic<bool> too_large{false};
  22486. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22487. sse.on_error([&](Error err) {
  22488. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22489. });
  22490. sse.set_max_reconnect_attempts(1);
  22491. sse.start_async();
  22492. for (int i = 0; i < 500 && messages < 1000; i++) {
  22493. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22494. }
  22495. sse.stop();
  22496. EXPECT_GE(messages.load(), 1000);
  22497. EXPECT_FALSE(too_large);
  22498. }
  22499. // Test: on_message callback
  22500. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22501. // Endpoint that sends multiple events then closes
  22502. server_->Get("/multi-event", [](const Request &, Response &res) {
  22503. res.set_chunked_content_provider(
  22504. "text/event-stream", [](size_t offset, DataSink &sink) {
  22505. if (offset == 0) {
  22506. std::string events = "data: message1\n\ndata: message2\n\n";
  22507. sink.write(events.data(), events.size());
  22508. }
  22509. return false;
  22510. });
  22511. });
  22512. Client client("localhost", get_port());
  22513. sse::SSEClient sse(client, "/multi-event");
  22514. std::vector<std::string> received_messages;
  22515. std::mutex messages_mutex;
  22516. sse.on_message([&](const sse::SSEMessage &msg) {
  22517. std::lock_guard<std::mutex> lock(messages_mutex);
  22518. received_messages.push_back(msg.data);
  22519. });
  22520. sse.set_reconnect_interval(100);
  22521. sse.set_max_reconnect_attempts(1);
  22522. sse.start_async();
  22523. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22524. sse.stop();
  22525. std::lock_guard<std::mutex> lock(messages_mutex);
  22526. EXPECT_GE(received_messages.size(), 2u);
  22527. if (received_messages.size() >= 2) {
  22528. EXPECT_EQ(received_messages[0], "message1");
  22529. EXPECT_EQ(received_messages[1], "message2");
  22530. }
  22531. }
  22532. // Test: on_event for specific types
  22533. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22534. Client client("localhost", get_port());
  22535. sse::SSEClient sse(client, "/custom-events");
  22536. std::atomic<bool> update_received{false};
  22537. std::atomic<bool> delete_received{false};
  22538. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22539. if (msg.data == "updated") { update_received.store(true); }
  22540. });
  22541. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22542. if (msg.data == "deleted") { delete_received.store(true); }
  22543. });
  22544. sse.set_max_reconnect_attempts(1);
  22545. sse.start_async();
  22546. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22547. sse.stop();
  22548. EXPECT_TRUE(update_received.load());
  22549. EXPECT_TRUE(delete_received.load());
  22550. }
  22551. // Test: on_error callback on connection failure
  22552. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22553. // Connect to a non-existent port
  22554. Client client("localhost", 59999);
  22555. sse::SSEClient sse(client, "/events");
  22556. std::atomic<bool> error_called{false};
  22557. Error received_error = Error::Success;
  22558. sse.on_error([&](Error err) {
  22559. error_called.store(true);
  22560. received_error = err;
  22561. });
  22562. sse.set_reconnect_interval(50);
  22563. sse.set_max_reconnect_attempts(1);
  22564. sse.start_async();
  22565. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22566. sse.stop();
  22567. EXPECT_TRUE(error_called.load());
  22568. EXPECT_NE(received_error, Error::Success);
  22569. }
  22570. // Test: Last-Event-ID header sent on reconnect
  22571. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22572. // Endpoint that sends event with ID
  22573. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22574. res.set_chunked_content_provider(
  22575. "text/event-stream", [](size_t offset, DataSink &sink) {
  22576. if (offset == 0) {
  22577. std::string event = "id: evt-123\ndata: test\n\n";
  22578. sink.write(event.data(), event.size());
  22579. }
  22580. return false;
  22581. });
  22582. });
  22583. Client client("localhost", get_port());
  22584. sse::SSEClient sse(client, "/event-with-id");
  22585. std::atomic<bool> id_received{false};
  22586. sse.on_message([&](const sse::SSEMessage &msg) {
  22587. if (!msg.id.empty()) { id_received.store(true); }
  22588. });
  22589. sse.set_reconnect_interval(100);
  22590. sse.set_max_reconnect_attempts(1);
  22591. sse.start_async();
  22592. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22593. sse.stop();
  22594. EXPECT_TRUE(id_received.load());
  22595. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22596. }
  22597. // Test: last_event_id() read from another thread while start_async() runs
  22598. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22599. // Ids of every length up to 200, so the stored id keeps changing size
  22600. server_->Get("/many-ids", [](const Request &, Response &res) {
  22601. res.set_chunked_content_provider(
  22602. "text/event-stream", [](size_t offset, DataSink &sink) {
  22603. if (offset == 0) {
  22604. std::string events;
  22605. for (size_t i = 0; i < 2000; i++) {
  22606. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22607. events += "data: x\n\n";
  22608. }
  22609. events += "id: end\ndata: x\n\n";
  22610. sink.write(events.data(), events.size());
  22611. }
  22612. return false;
  22613. });
  22614. });
  22615. Client client("localhost", get_port());
  22616. sse::SSEClient sse(client, "/many-ids");
  22617. // Wait out the rest of the test rather than replay the stream
  22618. sse.set_reconnect_interval(10000);
  22619. sse.set_max_reconnect_attempts(1);
  22620. sse.start_async();
  22621. auto well_formed = true;
  22622. std::string id;
  22623. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22624. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22625. id = sse.last_event_id();
  22626. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22627. well_formed = false;
  22628. }
  22629. }
  22630. sse.stop();
  22631. EXPECT_TRUE(well_formed);
  22632. EXPECT_EQ(sse.last_event_id(), "end");
  22633. }
  22634. // Test: Manual stop
  22635. TEST_F(SSEIntegrationTest, ManualStop) {
  22636. // Endpoint that sends one event and stays open briefly. The server outlives
  22637. // this test body, so the provider uses the fixture's flag, not a local.
  22638. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22639. res.set_chunked_content_provider(
  22640. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22641. if (offset == 0) {
  22642. std::string event = "data: connected\n\n";
  22643. sink.write(event.data(), event.size());
  22644. }
  22645. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22646. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22647. }
  22648. return false;
  22649. });
  22650. });
  22651. Client client("localhost", get_port());
  22652. sse::SSEClient sse(client, "/stay-open");
  22653. std::atomic<bool> connected{false};
  22654. sse.on_open([&connected]() { connected.store(true); });
  22655. sse.set_reconnect_interval(100);
  22656. sse.set_max_reconnect_attempts(1);
  22657. sse.start_async();
  22658. // Wait for connection to establish
  22659. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22660. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22661. }
  22662. EXPECT_TRUE(connected.load());
  22663. EXPECT_TRUE(sse.is_connected());
  22664. // Signal handler to stop
  22665. stop_server_.store(true);
  22666. // Stop SSE client
  22667. sse.stop();
  22668. EXPECT_FALSE(sse.is_connected());
  22669. }
  22670. // Sends one event, then nothing until stop is set
  22671. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22672. return [&stop](const Request &, Response &res) {
  22673. res.set_chunked_content_provider(
  22674. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22675. if (offset == 0) {
  22676. std::string event = "data: hello\n\n";
  22677. sink.write(event.data(), event.size());
  22678. }
  22679. while (!stop.load()) {
  22680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22681. }
  22682. return false;
  22683. });
  22684. };
  22685. }
  22686. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22687. static void check_stop_interrupts_blocked_read(Client &client) {
  22688. client.set_read_timeout(30, 0);
  22689. for (auto by_destructor : {false, true}) {
  22690. std::atomic<bool> received{false};
  22691. std::chrono::steady_clock::time_point start;
  22692. {
  22693. sse::SSEClient sse(client, "/idle-stream");
  22694. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22695. sse.start_async();
  22696. for (int i = 0; i < 500 && !received.load(); ++i) {
  22697. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22698. }
  22699. ASSERT_TRUE(received.load());
  22700. // Let the client block in the next read
  22701. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22702. start = std::chrono::steady_clock::now();
  22703. if (!by_destructor) { sse.stop(); }
  22704. }
  22705. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22706. std::chrono::seconds(2));
  22707. }
  22708. }
  22709. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22710. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22711. Client client("localhost", get_port());
  22712. check_stop_interrupts_blocked_read(client);
  22713. }
  22714. #ifdef CPPHTTPLIB_SSL_ENABLED
  22715. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22717. std::atomic<bool> done{false};
  22718. svr.Get("/idle-stream", idle_event_stream(done));
  22719. auto port = svr.bind_to_any_port(HOST);
  22720. std::thread t([&] { svr.listen_after_bind(); });
  22721. auto se = detail::scope_exit([&] {
  22722. done.store(true);
  22723. svr.stop();
  22724. t.join();
  22725. });
  22726. svr.wait_until_ready();
  22727. Client client("https://localhost:" + std::to_string(port));
  22728. client.enable_server_certificate_verification(false);
  22729. check_stop_interrupts_blocked_read(client);
  22730. }
  22731. #endif
  22732. // Test: SSEClient with custom headers
  22733. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22734. // Setup a server endpoint that checks for custom header
  22735. std::atomic<bool> header_received{false};
  22736. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22737. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22738. header_received.store(true);
  22739. }
  22740. res.set_chunked_content_provider("text/event-stream",
  22741. [](size_t, DataSink &) { return false; });
  22742. });
  22743. Client client("localhost", get_port());
  22744. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22745. sse::SSEClient sse(client, "/header-check", headers);
  22746. sse.set_max_reconnect_attempts(1);
  22747. sse.start_async();
  22748. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22749. sse.stop();
  22750. EXPECT_TRUE(header_received.load());
  22751. }
  22752. // Test: Reconnect interval configuration
  22753. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22754. Client client("localhost", get_port());
  22755. sse::SSEClient sse(client, "/events");
  22756. auto &result = sse.set_reconnect_interval(500);
  22757. // Builder pattern should return reference to self
  22758. EXPECT_EQ(&result, &sse);
  22759. }
  22760. // Test: Max reconnect attempts
  22761. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22762. // Connect to non-existent port to force reconnects
  22763. Client client("localhost", 59998);
  22764. sse::SSEClient sse(client, "/events");
  22765. std::atomic<int> error_count{0};
  22766. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22767. sse.set_reconnect_interval(50);
  22768. sse.set_max_reconnect_attempts(2);
  22769. auto start = std::chrono::steady_clock::now();
  22770. sse.start(); // Blocking call
  22771. auto end = std::chrono::steady_clock::now();
  22772. // Should have stopped after 2 failed attempts
  22773. EXPECT_GE(error_count.load(), 2);
  22774. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22775. auto duration =
  22776. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22777. #ifdef _WIN32
  22778. // Windows is much slower for socket connection failures
  22779. EXPECT_LT(duration.count(), 7000);
  22780. #else
  22781. EXPECT_LT(duration.count(), 1000);
  22782. #endif
  22783. }
  22784. // Test: Multi-line data in integration
  22785. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22786. // Endpoint with multi-line data
  22787. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22788. res.set_chunked_content_provider(
  22789. "text/event-stream", [](size_t offset, DataSink &sink) {
  22790. if (offset == 0) {
  22791. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22792. sink.write(event.data(), event.size());
  22793. }
  22794. return false;
  22795. });
  22796. });
  22797. Client client("localhost", get_port());
  22798. sse::SSEClient sse(client, "/multiline-data");
  22799. std::string received_data;
  22800. std::mutex data_mutex;
  22801. sse.on_message([&](const sse::SSEMessage &msg) {
  22802. std::lock_guard<std::mutex> lock(data_mutex);
  22803. received_data = msg.data;
  22804. });
  22805. sse.set_reconnect_interval(100);
  22806. sse.set_max_reconnect_attempts(1);
  22807. sse.start_async();
  22808. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22809. sse.stop();
  22810. std::lock_guard<std::mutex> lock(data_mutex);
  22811. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22812. }
  22813. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22814. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22815. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22816. DataSink &sink) {
  22817. if (offset == 0) {
  22818. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22819. sink.write(events.data(), events.size());
  22820. }
  22821. return false;
  22822. });
  22823. });
  22824. Client client("localhost", get_port());
  22825. sse::SSEClient sse(client, "/empty-data-lines");
  22826. std::mutex mutex;
  22827. std::condition_variable cv;
  22828. std::vector<std::string> received;
  22829. sse.on_message([&](const sse::SSEMessage &msg) {
  22830. std::lock_guard<std::mutex> lock(mutex);
  22831. received.push_back(msg.data);
  22832. cv.notify_all();
  22833. });
  22834. sse.set_max_reconnect_attempts(1);
  22835. sse.start_async();
  22836. {
  22837. std::unique_lock<std::mutex> lock(mutex);
  22838. cv.wait_for(lock, std::chrono::seconds(2),
  22839. [&] { return received.size() >= 3; });
  22840. }
  22841. sse.stop();
  22842. ASSERT_GE(received.size(), 3u);
  22843. EXPECT_EQ(received[0], "");
  22844. EXPECT_EQ(received[1], "\nhello");
  22845. EXPECT_EQ(received[2], "");
  22846. }
  22847. // Test: Auto-reconnect after server disconnection
  22848. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22849. std::atomic<int> connection_count{0};
  22850. std::atomic<int> message_count{0};
  22851. // Endpoint that sends one event and closes, forcing reconnect
  22852. server_->Get("/reconnect-test",
  22853. [&connection_count](const Request &, Response &res) {
  22854. connection_count.fetch_add(1);
  22855. res.set_chunked_content_provider(
  22856. "text/event-stream", [](size_t offset, DataSink &sink) {
  22857. if (offset == 0) {
  22858. std::string event = "data: hello\n\n";
  22859. sink.write(event.data(), event.size());
  22860. }
  22861. return false; // Close connection after sending
  22862. });
  22863. });
  22864. Client client("localhost", get_port());
  22865. sse::SSEClient sse(client, "/reconnect-test");
  22866. sse.on_message([&message_count](const sse::SSEMessage &) {
  22867. message_count.fetch_add(1);
  22868. });
  22869. sse.set_reconnect_interval(100);
  22870. sse.set_max_reconnect_attempts(3);
  22871. sse.start_async();
  22872. // Wait long enough for multiple reconnects
  22873. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22874. sse.stop();
  22875. // Should have connected multiple times (initial + reconnects)
  22876. EXPECT_GE(connection_count.load(), 2);
  22877. // Should have received messages from multiple connections
  22878. EXPECT_GE(message_count.load(), 2);
  22879. }
  22880. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22881. std::atomic<int> connection_count{0};
  22882. // Neither Content-Length nor chunked: the close ends the stream
  22883. server_->Get("/close-delimited",
  22884. [&connection_count](const Request &, Response &res) {
  22885. connection_count.fetch_add(1);
  22886. res.set_content_provider(
  22887. "text/event-stream", [](size_t offset, DataSink &sink) {
  22888. if (offset == 0) {
  22889. std::string event = "data: hello\n\n";
  22890. sink.write(event.data(), event.size());
  22891. } else {
  22892. sink.done();
  22893. }
  22894. return true;
  22895. });
  22896. });
  22897. Client client("localhost", get_port());
  22898. sse::SSEClient sse(client, "/close-delimited");
  22899. std::atomic<int> error_count{0};
  22900. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22901. sse.set_reconnect_interval(100);
  22902. sse.start_async();
  22903. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22904. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22905. }
  22906. sse.stop();
  22907. // Reconnects as after any end of the stream, but reports no error
  22908. EXPECT_GE(connection_count.load(), 2);
  22909. EXPECT_EQ(0, error_count.load());
  22910. }
  22911. // Test: A retry field that is not all ASCII digits is ignored
  22912. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22913. std::atomic<int> connection_count{0};
  22914. server_->Get("/bad-retry",
  22915. [&connection_count](const Request &, Response &res) {
  22916. connection_count.fetch_add(1);
  22917. res.set_chunked_content_provider(
  22918. "text/event-stream", [](size_t offset, DataSink &sink) {
  22919. if (offset == 0) {
  22920. std::string event = "retry: -1\ndata: hello\n\n";
  22921. sink.write(event.data(), event.size());
  22922. }
  22923. return false;
  22924. });
  22925. });
  22926. Client client("localhost", get_port());
  22927. sse::SSEClient sse(client, "/bad-retry");
  22928. sse.set_reconnect_interval(10000);
  22929. sse.start_async();
  22930. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22931. sse.stop();
  22932. EXPECT_EQ(connection_count.load(), 1);
  22933. }
  22934. // Test: A retry field of all ASCII digits sets the reconnection time
  22935. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22936. std::mutex mutex;
  22937. std::condition_variable cv;
  22938. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22939. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22940. {
  22941. std::lock_guard<std::mutex> lock(mutex);
  22942. connected_at.push_back(std::chrono::steady_clock::now());
  22943. cv.notify_all();
  22944. }
  22945. res.set_chunked_content_provider(
  22946. "text/event-stream", [](size_t offset, DataSink &sink) {
  22947. if (offset == 0) {
  22948. std::string event = "retry: 0\ndata: hello\n\n";
  22949. sink.write(event.data(), event.size());
  22950. }
  22951. return false;
  22952. });
  22953. });
  22954. Client client("localhost", get_port());
  22955. sse::SSEClient sse(client, "/zero-retry");
  22956. sse.set_reconnect_interval(10000);
  22957. sse.start_async();
  22958. {
  22959. std::unique_lock<std::mutex> lock(mutex);
  22960. cv.wait_for(lock, std::chrono::seconds(5),
  22961. [&] { return connected_at.size() >= 2; });
  22962. }
  22963. sse.stop();
  22964. // The server-supplied interval is applied, but never below 100ms, so
  22965. // "retry: 0" does not cause a busy reconnect loop
  22966. std::lock_guard<std::mutex> lock(mutex);
  22967. ASSERT_GE(connected_at.size(), 2u);
  22968. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22969. connected_at[1] - connected_at[0])
  22970. .count();
  22971. EXPECT_GE(interval_ms, 100);
  22972. }
  22973. // Test: Last-Event-ID sent on reconnect
  22974. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22975. std::atomic<int> connection_count{0};
  22976. std::vector<std::string> received_last_event_ids;
  22977. std::mutex id_mutex;
  22978. // Endpoint that checks Last-Event-ID header and sends event with ID
  22979. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22980. int conn = connection_count.fetch_add(1);
  22981. // Capture the Last-Event-ID header from each connection
  22982. {
  22983. std::lock_guard<std::mutex> lock(id_mutex);
  22984. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22985. }
  22986. res.set_chunked_content_provider(
  22987. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22988. if (offset == 0) {
  22989. std::string event =
  22990. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22991. sink.write(event.data(), event.size());
  22992. }
  22993. return false;
  22994. });
  22995. });
  22996. Client client("localhost", get_port());
  22997. sse::SSEClient sse(client, "/reconnect-with-id");
  22998. sse.set_reconnect_interval(100);
  22999. sse.set_max_reconnect_attempts(3);
  23000. sse.start_async();
  23001. // Wait for at least 2 connections
  23002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23003. sse.stop();
  23004. // Verify behavior
  23005. std::lock_guard<std::mutex> lock(id_mutex);
  23006. EXPECT_GE(received_last_event_ids.size(), 2u);
  23007. // First connection should have no Last-Event-ID
  23008. if (!received_last_event_ids.empty()) {
  23009. EXPECT_EQ(received_last_event_ids[0], "");
  23010. }
  23011. // Second connection should have Last-Event-ID from first connection
  23012. if (received_last_event_ids.size() >= 2) {
  23013. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23014. }
  23015. }
  23016. // Test: set_headers updates headers used on reconnect
  23017. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23018. std::vector<std::string> received_tokens;
  23019. std::mutex token_mutex;
  23020. // Endpoint that captures Authorization header
  23021. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23022. {
  23023. std::lock_guard<std::mutex> lock(token_mutex);
  23024. received_tokens.push_back(req.get_header_value("Authorization"));
  23025. }
  23026. res.set_chunked_content_provider(
  23027. "text/event-stream", [](size_t offset, DataSink &sink) {
  23028. if (offset == 0) {
  23029. std::string event = "data: hello\n\n";
  23030. sink.write(event.data(), event.size());
  23031. }
  23032. return false; // Close connection to trigger reconnect
  23033. });
  23034. });
  23035. Client client("localhost", get_port());
  23036. Headers headers = {{"Authorization", "Bearer old-token"}};
  23037. sse::SSEClient sse(client, "/auth-check", headers);
  23038. // Update headers on each successful connection
  23039. sse.on_open(
  23040. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23041. sse.set_reconnect_interval(100);
  23042. sse.set_max_reconnect_attempts(3);
  23043. sse.start_async();
  23044. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23045. sse.stop();
  23046. std::lock_guard<std::mutex> lock(token_mutex);
  23047. ASSERT_GE(received_tokens.size(), 2u);
  23048. // First connection uses original header
  23049. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23050. // Second connection uses updated header from set_headers
  23051. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23052. }
  23053. // Test: 401 allows reconnection (so on_error can refresh headers)
  23054. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23055. std::atomic<int> connection_count{0};
  23056. // Endpoint: returns 401 on first attempt, 200 on second
  23057. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23058. int conn = connection_count.fetch_add(1);
  23059. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23060. res.status = StatusCode::Unauthorized_401;
  23061. res.set_content("Unauthorized", "text/plain");
  23062. return;
  23063. }
  23064. res.set_chunked_content_provider(
  23065. "text/event-stream", [](size_t offset, DataSink &sink) {
  23066. if (offset == 0) {
  23067. std::string event = "data: authenticated\n\n";
  23068. sink.write(event.data(), event.size());
  23069. }
  23070. return false;
  23071. });
  23072. });
  23073. Client client("localhost", get_port());
  23074. Headers headers = {{"Authorization", "Bearer expired"}};
  23075. sse::SSEClient sse(client, "/auth-retry", headers);
  23076. std::atomic<bool> message_received{false};
  23077. // Refresh token on error
  23078. sse.on_error(
  23079. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23080. sse.on_message([&](const sse::SSEMessage &msg) {
  23081. if (msg.data == "authenticated") { message_received.store(true); }
  23082. });
  23083. sse.set_reconnect_interval(100);
  23084. sse.set_max_reconnect_attempts(3);
  23085. sse.start_async();
  23086. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23087. sse.stop();
  23088. // Should have reconnected after 401 and succeeded with new token
  23089. EXPECT_GE(connection_count.load(), 2);
  23090. EXPECT_TRUE(message_received.load());
  23091. }
  23092. TEST(Issue2318Test, EmptyHostString) {
  23093. {
  23094. httplib::Client cli_empty("", PORT);
  23095. auto res = cli_empty.Get("/");
  23096. ASSERT_FALSE(res);
  23097. EXPECT_EQ(httplib::Error::Connection, res.error());
  23098. }
  23099. {
  23100. httplib::Client cli(" ", PORT);
  23101. auto res = cli.Get("/");
  23102. ASSERT_FALSE(res);
  23103. EXPECT_EQ(httplib::Error::Connection, res.error());
  23104. }
  23105. }
  23106. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23107. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23108. Server svr;
  23109. // Set a small payload limit (1KB)
  23110. svr.set_payload_max_length(1024);
  23111. svr.Post("/test", [&](const Request &req, Response &res) {
  23112. res.set_content("Body size: " + std::to_string(req.body.size()),
  23113. "text/plain");
  23114. });
  23115. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23116. auto se = detail::scope_exit([&] {
  23117. svr.stop();
  23118. listen_thread.join();
  23119. });
  23120. svr.wait_until_ready();
  23121. // Create data that compresses well but exceeds limit when decompressed
  23122. // 8KB of repeated null bytes compresses to a very small size
  23123. std::string original_data(8 * 1024, '\0');
  23124. // Compress the data using gzip
  23125. std::string compressed_data;
  23126. detail::gzip_compressor compressor;
  23127. compressor.compress(original_data.data(), original_data.size(), true,
  23128. [&](const char *data, size_t size) {
  23129. compressed_data.append(data, size);
  23130. return true;
  23131. });
  23132. // Verify compression worked (compressed should be much smaller)
  23133. ASSERT_LT(compressed_data.size(), original_data.size());
  23134. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23135. // Send compressed data with Content-Encoding: gzip
  23136. Client cli(HOST, PORT);
  23137. Headers headers = {{"Content-Encoding", "gzip"}};
  23138. auto res =
  23139. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23140. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23142. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23143. }
  23144. #endif
  23145. // ============================================================================
  23146. // OpenSSL-Specific Tests
  23147. // ============================================================================
  23148. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23149. X509 *readCertificate(const std::string &strFileName) {
  23150. std::ifstream inStream(strFileName);
  23151. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23152. std::istreambuf_iterator<char>());
  23153. if (strCertPEM.empty()) return (nullptr);
  23154. BIO *pbCert = BIO_new(BIO_s_mem());
  23155. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23156. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23157. BIO_free(pbCert);
  23158. return (pCert);
  23159. }
  23160. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23161. std::ifstream inStream(strFileName);
  23162. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23163. std::istreambuf_iterator<char>());
  23164. if (strPrivateKeyPEM.empty()) return (nullptr);
  23165. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23166. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23167. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23168. BIO_free(pbPrivKey);
  23169. return (pPrivateKey);
  23170. }
  23171. TEST(BindServerTest, UpdateCerts) {
  23172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23173. int port = svr.bind_to_any_port("0.0.0.0");
  23174. ASSERT_TRUE(svr.is_valid());
  23175. ASSERT_TRUE(port > 0);
  23176. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23177. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23178. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23179. ASSERT_TRUE(cert != nullptr);
  23180. ASSERT_TRUE(ca_cert != nullptr);
  23181. ASSERT_TRUE(key != nullptr);
  23182. X509_STORE *cert_store = X509_STORE_new();
  23183. X509_STORE_add_cert(cert_store, ca_cert);
  23184. // svr.update_certs(cert, key, cert_store); // deprecated
  23185. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23186. CLIENT_CA_CERT_FILE);
  23187. ASSERT_TRUE(svr.is_valid());
  23188. svr.stop();
  23189. X509_STORE_free(cert_store);
  23190. X509_free(cert);
  23191. X509_free(ca_cert);
  23192. EVP_PKEY_free(key);
  23193. }
  23194. // Test that update_certs() updates client CA list correctly
  23195. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23196. // Start with file-based constructor
  23197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23198. ASSERT_TRUE(svr.is_valid());
  23199. // Initially no client CA list should be set
  23200. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23201. ASSERT_TRUE(ssl_ctx != nullptr);
  23202. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23203. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23204. // Now update with client CA (PEM string)
  23205. std::string cert_pem, key_pem, ca_pem;
  23206. read_file(SERVER_CERT_FILE, cert_pem);
  23207. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23208. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23209. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23210. ASSERT_TRUE(svr.is_valid());
  23211. // Now client CA list should be set
  23212. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23213. ASSERT_TRUE(ca_list_after != nullptr);
  23214. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23215. }
  23216. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23217. // Test that the file-path SSLServer constructor properly sets the client CA
  23218. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23220. ASSERT_TRUE(svr.is_valid());
  23221. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23222. ASSERT_TRUE(ssl_ctx != nullptr);
  23223. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23224. ASSERT_TRUE(ca_list != nullptr);
  23225. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23226. }
  23227. #endif
  23228. // ============================================================================
  23229. // MbedTLS-Specific Tests
  23230. // ============================================================================
  23231. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23232. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23233. using namespace httplib::tls;
  23234. // Track if callback was invoked
  23235. bool callback_invoked = false;
  23236. // The callback receives void* ctx which is actually MbedTlsContext*
  23237. // We can access the mbedtls_ssl_config via the context
  23238. auto setup_callback = [&callback_invoked](void *ctx) {
  23239. callback_invoked = true;
  23240. // Cast to MbedTlsContext* to access the ssl config
  23241. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23242. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23243. // Use static variables to hold certificate data (simplified for test)
  23244. static mbedtls_x509_crt own_cert;
  23245. static mbedtls_pk_context own_key;
  23246. static mbedtls_x509_crt ca_chain;
  23247. static bool initialized = false;
  23248. if (!initialized) {
  23249. mbedtls_x509_crt_init(&own_cert);
  23250. mbedtls_pk_init(&own_key);
  23251. mbedtls_x509_crt_init(&ca_chain);
  23252. // Load server certificate
  23253. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23254. return false;
  23255. }
  23256. // Load server private key.
  23257. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23258. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23259. #if MBEDTLS_VERSION_MAJOR == 3
  23260. ,
  23261. mbedtls_ctr_drbg_random, nullptr
  23262. #endif
  23263. ) != 0) {
  23264. return false;
  23265. }
  23266. // Load CA chain for client verification
  23267. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23268. return false;
  23269. }
  23270. initialized = true;
  23271. }
  23272. // Configure the SSL config
  23273. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23274. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23275. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23276. // Set minimum TLS version using mbedTLS native API
  23277. #if MBEDTLS_VERSION_MAJOR >= 3
  23278. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23279. #else
  23280. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23281. MBEDTLS_SSL_MINOR_VERSION_3);
  23282. #endif
  23283. return true;
  23284. };
  23285. SSLServer svr(setup_callback);
  23286. ASSERT_TRUE(svr.is_valid());
  23287. ASSERT_TRUE(callback_invoked);
  23288. svr.Get("/test", [&](const Request &req, Response &res) {
  23289. res.set_content("test", "text/plain");
  23290. auto cert = req.peer_cert();
  23291. ASSERT_TRUE(static_cast<bool>(cert));
  23292. auto common_name = cert.subject_cn();
  23293. EXPECT_EQ("Common Name", common_name);
  23294. });
  23295. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23296. auto se = detail::scope_exit([&] {
  23297. svr.stop();
  23298. t.join();
  23299. ASSERT_FALSE(svr.is_running());
  23300. });
  23301. svr.wait_until_ready();
  23302. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23303. cli.enable_server_certificate_verification(false);
  23304. cli.set_connection_timeout(30);
  23305. auto res = cli.Get("/test");
  23306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23307. ASSERT_EQ(StatusCode::OK_200, res->status);
  23308. }
  23309. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23310. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23311. // keep-alive SSL session, which reads through that config in
  23312. // mbedtls_ssl_close_notify.
  23313. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23314. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23315. ASSERT_TRUE(svr.is_valid());
  23316. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23317. res.set_content("test", "text/plain");
  23318. });
  23319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23320. auto se = detail::scope_exit([&] {
  23321. svr.stop();
  23322. t.join();
  23323. ASSERT_FALSE(svr.is_running());
  23324. });
  23325. svr.wait_until_ready();
  23326. {
  23327. SSLClient cli(HOST, PORT);
  23328. cli.enable_server_certificate_verification(false);
  23329. cli.set_keep_alive(true);
  23330. auto res = cli.Get("/test");
  23331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23332. ASSERT_EQ(StatusCode::OK_200, res->status);
  23333. // cli is destructed here with the keep-alive SSL session still open.
  23334. }
  23335. }
  23336. #endif
  23337. // WebSocket Tests
  23338. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23339. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23340. // defining the meaning of these bits has been negotiated.
  23341. auto make_frame = [](uint8_t first_byte) {
  23342. std::string frame;
  23343. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23344. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23345. frame += "Hello";
  23346. return frame;
  23347. };
  23348. // RSV1 set (0x40)
  23349. {
  23350. detail::BufferStream strm;
  23351. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23352. ws::Opcode opcode;
  23353. std::string payload;
  23354. bool fin;
  23355. EXPECT_EQ(
  23356. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23357. ws::impl::FrameRead::Fail);
  23358. }
  23359. // RSV2 set (0x20)
  23360. {
  23361. detail::BufferStream strm;
  23362. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23363. ws::Opcode opcode;
  23364. std::string payload;
  23365. bool fin;
  23366. EXPECT_EQ(
  23367. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23368. ws::impl::FrameRead::Fail);
  23369. }
  23370. // RSV3 set (0x10)
  23371. {
  23372. detail::BufferStream strm;
  23373. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23374. ws::Opcode opcode;
  23375. std::string payload;
  23376. bool fin;
  23377. EXPECT_EQ(
  23378. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23379. ws::impl::FrameRead::Fail);
  23380. }
  23381. // No RSV bits set - should succeed
  23382. {
  23383. detail::BufferStream strm;
  23384. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23385. ws::Opcode opcode;
  23386. std::string payload;
  23387. bool fin;
  23388. EXPECT_EQ(
  23389. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23390. ws::impl::FrameRead::Ok);
  23391. EXPECT_EQ(ws::Opcode::Text, opcode);
  23392. EXPECT_EQ("Hello", payload);
  23393. EXPECT_TRUE(fin);
  23394. }
  23395. }
  23396. TEST(WebSocketTest, ControlFrameValidation) {
  23397. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23398. // payload length <= 125.
  23399. // Ping with FIN=0 - must be rejected
  23400. {
  23401. detail::BufferStream strm;
  23402. std::string frame;
  23403. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23404. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23405. strm.write(frame.data(), frame.size());
  23406. ws::Opcode opcode;
  23407. std::string payload;
  23408. bool fin;
  23409. EXPECT_EQ(
  23410. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23411. ws::impl::FrameRead::Fail);
  23412. }
  23413. // Close with FIN=0 - must be rejected
  23414. {
  23415. detail::BufferStream strm;
  23416. std::string frame;
  23417. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23418. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23419. strm.write(frame.data(), frame.size());
  23420. ws::Opcode opcode;
  23421. std::string payload;
  23422. bool fin;
  23423. EXPECT_EQ(
  23424. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23425. ws::impl::FrameRead::Fail);
  23426. }
  23427. // Ping with payload_len=126 (extended length) - must be rejected
  23428. {
  23429. detail::BufferStream strm;
  23430. std::string frame;
  23431. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23432. frame += static_cast<char>(126); // payload_len=126 (>125)
  23433. frame += static_cast<char>(0x00); // extended length high byte
  23434. frame += static_cast<char>(126); // extended length low byte
  23435. frame += std::string(126, 'x');
  23436. strm.write(frame.data(), frame.size());
  23437. ws::Opcode opcode;
  23438. std::string payload;
  23439. bool fin;
  23440. EXPECT_EQ(
  23441. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23442. ws::impl::FrameRead::Fail);
  23443. }
  23444. // Ping with FIN=1 and payload_len=125 - should succeed
  23445. {
  23446. detail::BufferStream strm;
  23447. std::string frame;
  23448. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23449. frame += static_cast<char>(125); // payload_len=125
  23450. frame += std::string(125, 'x');
  23451. strm.write(frame.data(), frame.size());
  23452. ws::Opcode opcode;
  23453. std::string payload;
  23454. bool fin;
  23455. EXPECT_EQ(
  23456. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23457. ws::impl::FrameRead::Ok);
  23458. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23459. EXPECT_EQ(125u, payload.size());
  23460. EXPECT_TRUE(fin);
  23461. }
  23462. }
  23463. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23464. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23465. // length MUST be 0.
  23466. // MSB set - must be rejected
  23467. {
  23468. detail::BufferStream strm;
  23469. std::string frame;
  23470. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23471. frame += static_cast<char>(127); // 64-bit extended length
  23472. frame += static_cast<char>(0x80); // MSB set (invalid)
  23473. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23474. strm.write(frame.data(), frame.size());
  23475. ws::Opcode opcode;
  23476. std::string payload;
  23477. bool fin;
  23478. EXPECT_EQ(
  23479. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23480. ws::impl::FrameRead::Fail);
  23481. }
  23482. // MSB clear - should pass length parsing (will be rejected by max_len,
  23483. // but that's a different check; use a small length to verify)
  23484. {
  23485. detail::BufferStream strm;
  23486. std::string frame;
  23487. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23488. frame += static_cast<char>(127); // 64-bit extended length
  23489. frame += std::string(7, '\0'); // high bytes = 0
  23490. frame += static_cast<char>(0x03); // length = 3
  23491. frame += "abc";
  23492. strm.write(frame.data(), frame.size());
  23493. ws::Opcode opcode;
  23494. std::string payload;
  23495. bool fin;
  23496. EXPECT_EQ(
  23497. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23498. ws::impl::FrameRead::Ok);
  23499. EXPECT_EQ(ws::Opcode::Text, opcode);
  23500. EXPECT_EQ("abc", payload);
  23501. }
  23502. }
  23503. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23504. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23505. // Valid UTF-8
  23506. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23507. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23508. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23509. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23510. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23511. // Invalid UTF-8
  23512. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23513. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23514. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23515. EXPECT_FALSE(
  23516. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23517. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23518. }
  23519. TEST(WebSocketTest, ConnectAndDisconnect) {
  23520. Server svr;
  23521. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23522. std::string msg;
  23523. while (ws.read(msg)) {}
  23524. });
  23525. auto port = svr.bind_to_any_port(HOST);
  23526. std::thread t([&]() { svr.listen_after_bind(); });
  23527. svr.wait_until_ready();
  23528. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23529. auto res = client.connect();
  23530. ASSERT_TRUE(res);
  23531. EXPECT_EQ(Error::Success, res.error());
  23532. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23533. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23534. EXPECT_TRUE(client.is_open());
  23535. client.close();
  23536. EXPECT_FALSE(client.is_open());
  23537. svr.stop();
  23538. t.join();
  23539. }
  23540. TEST(WebSocketTest, ValidURL) {
  23541. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23542. EXPECT_TRUE(ws1.is_valid());
  23543. ws::WebSocketClient ws2("ws://example.com/path");
  23544. EXPECT_TRUE(ws2.is_valid());
  23545. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23546. EXPECT_TRUE(ws3.is_valid());
  23547. #ifdef CPPHTTPLIB_SSL_ENABLED
  23548. ws::WebSocketClient wss1("wss://example.com/path");
  23549. EXPECT_TRUE(wss1.is_valid());
  23550. ws::WebSocketClient wss2("wss://example.com:443/path");
  23551. EXPECT_TRUE(wss2.is_valid());
  23552. #endif
  23553. }
  23554. TEST(WebSocketTest, InvalidURL) {
  23555. // No scheme
  23556. ws::WebSocketClient ws1("localhost:8080/path");
  23557. EXPECT_FALSE(ws1.is_valid());
  23558. // No path
  23559. ws::WebSocketClient ws2("ws://localhost:8080");
  23560. EXPECT_FALSE(ws2.is_valid());
  23561. // Empty string
  23562. ws::WebSocketClient ws3("");
  23563. EXPECT_FALSE(ws3.is_valid());
  23564. // Missing host
  23565. ws::WebSocketClient ws4("ws://:8080/path");
  23566. EXPECT_FALSE(ws4.is_valid());
  23567. // Port number overflow — should not crash
  23568. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23569. EXPECT_FALSE(ws5.is_valid());
  23570. // Port out of range
  23571. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23572. EXPECT_FALSE(ws6.is_valid());
  23573. }
  23574. TEST(WebSocketTest, UnsupportedScheme) {
  23575. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23576. ws::WebSocketClient ws1("http://localhost:8080/path");
  23577. EXPECT_FALSE(ws1.is_valid());
  23578. ws::WebSocketClient ws2("https://localhost:8080/path");
  23579. EXPECT_FALSE(ws2.is_valid());
  23580. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23581. EXPECT_FALSE(ws3.is_valid());
  23582. #else
  23583. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23584. std::invalid_argument);
  23585. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23586. std::invalid_argument);
  23587. #endif
  23588. }
  23589. TEST(WebSocketTest, ConnectWhenInvalid) {
  23590. ws::WebSocketClient ws("not a valid url");
  23591. EXPECT_FALSE(ws.is_valid());
  23592. auto res = ws.connect();
  23593. EXPECT_FALSE(res);
  23594. EXPECT_EQ(Error::Connection, res.error());
  23595. EXPECT_EQ(-1, res.status());
  23596. }
  23597. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23598. // Grab a port that is free, then close it again so nothing listens there
  23599. Server svr;
  23600. auto port = svr.bind_to_any_port(HOST);
  23601. svr.stop();
  23602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23603. auto res = client.connect();
  23604. ASSERT_FALSE(res);
  23605. EXPECT_EQ(Error::Connection, res.error());
  23606. EXPECT_EQ(-1, res.status());
  23607. }
  23608. TEST(WebSocketTest, DefaultPort) {
  23609. ws::WebSocketClient ws1("ws://example.com/path");
  23610. EXPECT_TRUE(ws1.is_valid());
  23611. // ws:// defaults to port 80 (verified by successful parse)
  23612. #ifdef CPPHTTPLIB_SSL_ENABLED
  23613. ws::WebSocketClient ws2("wss://example.com/path");
  23614. EXPECT_TRUE(ws2.is_valid());
  23615. // wss:// defaults to port 443 (verified by successful parse)
  23616. #endif
  23617. }
  23618. TEST(WebSocketTest, IPv6LiteralAddress) {
  23619. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23620. EXPECT_TRUE(ws1.is_valid());
  23621. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23622. EXPECT_TRUE(ws2.is_valid());
  23623. }
  23624. TEST(WebSocketTest, ComplexPath) {
  23625. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23626. EXPECT_TRUE(ws1.is_valid());
  23627. ws::WebSocketClient ws2("ws://localhost:8080/");
  23628. EXPECT_TRUE(ws2.is_valid());
  23629. }
  23630. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23631. Server svr;
  23632. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23633. std::string msg;
  23634. while (ws.read(msg)) {}
  23635. });
  23636. auto port = svr.bind_to_any_port(HOST);
  23637. std::thread t([&]() { svr.listen_after_bind(); });
  23638. svr.wait_until_ready();
  23639. auto another_host = "example.com";
  23640. auto wrong_ip = "192.0.2.1";
  23641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23642. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23643. ASSERT_TRUE(client.connect());
  23644. EXPECT_TRUE(client.is_open());
  23645. client.close();
  23646. svr.stop();
  23647. t.join();
  23648. }
  23649. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23650. Server svr;
  23651. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23652. std::string msg;
  23653. while (ws.read(msg)) {}
  23654. });
  23655. auto port = svr.bind_to_any_port(HOST);
  23656. std::thread t([&]() { svr.listen_after_bind(); });
  23657. svr.wait_until_ready();
  23658. auto wrong_ip = "192.0.2.1";
  23659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23660. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23661. client.set_connection_timeout(1);
  23662. client.set_read_timeout(1);
  23663. client.set_write_timeout(1);
  23664. EXPECT_FALSE(client.connect());
  23665. EXPECT_FALSE(client.is_open());
  23666. svr.stop();
  23667. t.join();
  23668. }
  23669. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23670. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23671. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23672. // (RFC 6761) is only a map key and the Host header value.
  23673. auto host = "target.invalid";
  23674. Server svr;
  23675. std::string received_host;
  23676. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23677. received_host = req.get_header_value("Host");
  23678. std::string msg;
  23679. while (ws.read(msg)) {}
  23680. });
  23681. auto port = svr.bind_to_any_port(HOST);
  23682. std::thread t([&]() { svr.listen_after_bind(); });
  23683. // ASSERT_* below returns from the test body, which would leave t joinable
  23684. // and make ~thread call std::terminate.
  23685. auto se = detail::scope_exit([&] {
  23686. svr.stop();
  23687. if (t.joinable()) { t.join(); }
  23688. });
  23689. svr.wait_until_ready();
  23690. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23691. std::to_string(port) + "/ws");
  23692. client.set_direct_hostname_addr_map({{host, HOST}});
  23693. ASSERT_TRUE(client.connect());
  23694. EXPECT_TRUE(client.is_open());
  23695. client.close();
  23696. svr.stop();
  23697. t.join();
  23698. // The mapping only redirects the connection; the identity stays host_.
  23699. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23700. }
  23701. class WebSocketIntegrationTest : public ::testing::Test {
  23702. protected:
  23703. void SetUp() override {
  23704. server_ = httplib::detail::make_unique<Server>();
  23705. setup_server();
  23706. start_server();
  23707. }
  23708. void TearDown() override {
  23709. server_->stop();
  23710. if (server_thread_.joinable()) { server_thread_.join(); }
  23711. }
  23712. void setup_server() {
  23713. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23714. std::string msg;
  23715. ws::ReadResult ret;
  23716. while ((ret = ws.read(msg))) {
  23717. if (ret == ws::Binary) {
  23718. ws.send(msg.data(), msg.size());
  23719. } else {
  23720. ws.send(msg);
  23721. }
  23722. }
  23723. });
  23724. server_->WebSocket("/ws-echo-string",
  23725. [](const Request &, ws::WebSocket &ws) {
  23726. std::string msg;
  23727. while (ws.read(msg)) {
  23728. ws.send("echo: " + msg);
  23729. }
  23730. });
  23731. server_->WebSocket(
  23732. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23733. // Echo back request metadata
  23734. ws.send("path:" + req.path);
  23735. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23736. std::string msg;
  23737. while (ws.read(msg)) {}
  23738. });
  23739. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23740. std::string msg;
  23741. ws.read(msg); // wait for a message
  23742. ws.close();
  23743. });
  23744. server_->WebSocket("/ws-close-status",
  23745. [](const Request &, ws::WebSocket &ws) {
  23746. std::string msg;
  23747. ws.read(msg); // wait for a message
  23748. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23749. });
  23750. server_->WebSocket(
  23751. "/ws-subprotocol",
  23752. [](const Request &, ws::WebSocket &ws) {
  23753. std::string msg;
  23754. while (ws.read(msg)) {
  23755. ws.send(msg);
  23756. }
  23757. },
  23758. [](const std::vector<std::string> &protocols) -> std::string {
  23759. for (const auto &p : protocols) {
  23760. if (p == "graphql-ws") { return p; }
  23761. }
  23762. return "";
  23763. });
  23764. server_->WebSocket(
  23765. "/ws-subprotocol-unoffered",
  23766. [](const Request &, ws::WebSocket &ws) {
  23767. std::string msg;
  23768. while (ws.read(msg)) {
  23769. ws.send(msg);
  23770. }
  23771. },
  23772. [](const std::vector<std::string> &) -> std::string {
  23773. return "admin";
  23774. });
  23775. }
  23776. void start_server() {
  23777. port_ = server_->bind_to_any_port(HOST);
  23778. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23779. server_->wait_until_ready();
  23780. }
  23781. std::unique_ptr<Server> server_;
  23782. std::thread server_thread_;
  23783. int port_ = 0;
  23784. };
  23785. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23787. "/ws-echo");
  23788. ASSERT_TRUE(client.connect());
  23789. ASSERT_TRUE(client.is_open());
  23790. ASSERT_TRUE(client.send("Hello WebSocket"));
  23791. std::string msg;
  23792. EXPECT_EQ(ws::Text, client.read(msg));
  23793. EXPECT_EQ("Hello WebSocket", msg);
  23794. client.close();
  23795. }
  23796. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23797. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23798. "/ws-echo");
  23799. ASSERT_TRUE(client.connect());
  23800. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23801. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23802. std::string msg;
  23803. EXPECT_EQ(ws::Binary, client.read(msg));
  23804. EXPECT_EQ(binary_data, msg);
  23805. client.close();
  23806. }
  23807. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23808. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23809. "/ws-echo");
  23810. ASSERT_TRUE(client.connect());
  23811. for (int i = 0; i < 10; i++) {
  23812. auto text = "message " + std::to_string(i);
  23813. ASSERT_TRUE(client.send(text));
  23814. std::string msg;
  23815. ASSERT_TRUE(client.read(msg));
  23816. EXPECT_EQ(text, msg);
  23817. }
  23818. client.close();
  23819. }
  23820. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23821. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23822. "/ws-close");
  23823. ASSERT_TRUE(client.connect());
  23824. // Send a message to trigger the server to close
  23825. ASSERT_TRUE(client.send("trigger close"));
  23826. // The server will close, so read should return false
  23827. std::string msg;
  23828. EXPECT_FALSE(client.read(msg));
  23829. EXPECT_FALSE(client.is_open());
  23830. }
  23831. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23833. "/ws-echo");
  23834. ASSERT_TRUE(client.connect());
  23835. // 128KB message
  23836. std::string large_data(128 * 1024, 'X');
  23837. ASSERT_TRUE(client.send(large_data));
  23838. std::string msg;
  23839. ASSERT_TRUE(client.read(msg));
  23840. EXPECT_EQ(large_data, msg);
  23841. client.close();
  23842. }
  23843. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23844. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23845. "/ws-echo");
  23846. ASSERT_TRUE(client.connect());
  23847. const int num_threads = 4;
  23848. std::vector<std::thread> threads;
  23849. std::atomic<int> send_count{0};
  23850. for (int t = 0; t < num_threads; t++) {
  23851. threads.emplace_back([&client, &send_count, t]() {
  23852. for (int i = 0; i < 5; i++) {
  23853. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23854. if (client.send(text)) { send_count++; }
  23855. }
  23856. });
  23857. }
  23858. for (auto &th : threads) {
  23859. th.join();
  23860. }
  23861. int received = 0;
  23862. std::string msg;
  23863. while (received < send_count.load()) {
  23864. if (!client.read(msg)) { break; }
  23865. received++;
  23866. }
  23867. EXPECT_EQ(send_count.load(), received);
  23868. client.close();
  23869. }
  23870. TEST_F(WebSocketIntegrationTest, ReadString) {
  23871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23872. "/ws-echo-string");
  23873. ASSERT_TRUE(client.connect());
  23874. ASSERT_TRUE(client.send("hello"));
  23875. std::string msg;
  23876. ASSERT_TRUE(client.read(msg));
  23877. EXPECT_EQ("echo: hello", msg);
  23878. ASSERT_TRUE(client.send("world"));
  23879. ASSERT_TRUE(client.read(msg));
  23880. EXPECT_EQ("echo: world", msg);
  23881. client.close();
  23882. }
  23883. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23884. Headers headers = {{"X-Test-Header", "test-value"}};
  23885. ws::WebSocketClient client(
  23886. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23887. ASSERT_TRUE(client.connect());
  23888. std::string msg;
  23889. ASSERT_TRUE(client.read(msg));
  23890. EXPECT_EQ("path:/ws-request-info", msg);
  23891. ASSERT_TRUE(client.read(msg));
  23892. EXPECT_EQ("header:test-value", msg);
  23893. client.close();
  23894. }
  23895. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23897. "/ws-echo");
  23898. client.set_read_timeout(1, 0); // 1 second
  23899. ASSERT_TRUE(client.connect());
  23900. // Don't send anything — server echo handler waits for a message, so read()
  23901. // should time out. The connection survives it: nothing was consumed.
  23902. std::string msg;
  23903. EXPECT_EQ(client.read(msg), ws::Timeout);
  23904. EXPECT_TRUE(client.is_open());
  23905. // And it is still usable afterwards.
  23906. EXPECT_TRUE(client.send("after timeout"));
  23907. EXPECT_EQ(client.read(msg), ws::Text);
  23908. EXPECT_EQ(msg, "after timeout");
  23909. }
  23910. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23911. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23912. "/ws-echo");
  23913. client.set_read_timeout(1, 0);
  23914. ASSERT_TRUE(client.connect());
  23915. ASSERT_TRUE(client.send("first"));
  23916. std::string msg;
  23917. ASSERT_EQ(client.read(msg), ws::Text);
  23918. ASSERT_EQ(msg, "first");
  23919. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23920. // not be used with a read timeout: it would reprocess the previous message.
  23921. EXPECT_EQ(client.read(msg), ws::Timeout);
  23922. EXPECT_EQ(msg, "first");
  23923. }
  23924. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23926. "/ws-echo");
  23927. ASSERT_TRUE(client.connect());
  23928. // Setting it once the connection is open reaches the live stream, not just
  23929. // the seed for the next connect().
  23930. client.set_read_timeout(1, 0);
  23931. std::string msg;
  23932. EXPECT_EQ(client.read(msg), ws::Timeout);
  23933. EXPECT_TRUE(client.is_open());
  23934. }
  23935. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23936. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23937. "/ws-echo");
  23938. client.set_read_timeout(5, 0);
  23939. ASSERT_TRUE(client.connect());
  23940. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23941. // The server should reject it and close the connection.
  23942. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23943. client.send(oversized);
  23944. // The server's read() should have failed due to payload limit,
  23945. // so our read() should return false (connection closed).
  23946. std::string msg;
  23947. EXPECT_FALSE(client.read(msg));
  23948. }
  23949. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23951. "/ws-echo");
  23952. client.set_read_timeout(10, 0);
  23953. ASSERT_TRUE(client.connect());
  23954. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23955. // This should succeed.
  23956. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23957. ASSERT_TRUE(client.send(at_limit));
  23958. std::string msg;
  23959. ASSERT_TRUE(client.read(msg));
  23960. EXPECT_EQ(at_limit.size(), msg.size());
  23961. client.close();
  23962. }
  23963. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23965. "/nonexistent");
  23966. auto res = client.connect();
  23967. EXPECT_FALSE(res);
  23968. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23969. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23970. EXPECT_FALSE(client.is_open());
  23971. }
  23972. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23974. "/ws-echo");
  23975. ASSERT_TRUE(client.connect());
  23976. ASSERT_TRUE(client.send(""));
  23977. std::string msg;
  23978. EXPECT_EQ(ws::Text, client.read(msg));
  23979. EXPECT_EQ("", msg);
  23980. client.close();
  23981. }
  23982. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23983. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23984. "/ws-echo");
  23985. // First connection
  23986. ASSERT_TRUE(client.connect());
  23987. ASSERT_TRUE(client.send("first"));
  23988. std::string msg;
  23989. ASSERT_TRUE(client.read(msg));
  23990. EXPECT_EQ("first", msg);
  23991. client.close();
  23992. EXPECT_FALSE(client.is_open());
  23993. // Reconnect using the same client object
  23994. ASSERT_TRUE(client.connect());
  23995. ASSERT_TRUE(client.is_open());
  23996. ASSERT_TRUE(client.send("second"));
  23997. ASSERT_TRUE(client.read(msg));
  23998. EXPECT_EQ("second", msg);
  23999. client.close();
  24000. }
  24001. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24003. "/ws-close-status");
  24004. ASSERT_TRUE(client.connect());
  24005. // Trigger the server to close with GoingAway status
  24006. ASSERT_TRUE(client.send("trigger"));
  24007. // read() should return false after receiving the close frame
  24008. std::string msg;
  24009. EXPECT_FALSE(client.read(msg));
  24010. EXPECT_FALSE(client.is_open());
  24011. }
  24012. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24014. "/ws-echo");
  24015. ASSERT_TRUE(client.connect());
  24016. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24017. EXPECT_FALSE(client.is_open());
  24018. }
  24019. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24020. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24021. ws::WebSocketClient client(
  24022. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24023. ASSERT_TRUE(client.connect());
  24024. // Server should have selected graphql-ws
  24025. EXPECT_EQ("graphql-ws", client.subprotocol());
  24026. client.close();
  24027. }
  24028. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24029. Headers headers;
  24030. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24031. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24032. ws::WebSocketClient client(
  24033. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24034. ASSERT_TRUE(client.connect());
  24035. // The offer on the second field line counts too, so graphql-ws is selected
  24036. EXPECT_EQ("graphql-ws", client.subprotocol());
  24037. client.close();
  24038. }
  24039. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24040. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24041. ws::WebSocketClient client(
  24042. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24043. ASSERT_TRUE(client.connect());
  24044. // Server should not have selected any subprotocol
  24045. EXPECT_TRUE(client.subprotocol().empty());
  24046. client.close();
  24047. }
  24048. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24049. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24051. "/ws-subprotocol-unoffered",
  24052. headers);
  24053. ASSERT_TRUE(client.connect());
  24054. EXPECT_TRUE(client.subprotocol().empty());
  24055. client.close();
  24056. }
  24057. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24058. // Connect without requesting any subprotocol
  24059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24060. "/ws-subprotocol");
  24061. ASSERT_TRUE(client.connect());
  24062. EXPECT_TRUE(client.subprotocol().empty());
  24063. client.close();
  24064. }
  24065. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24067. "/ws-echo");
  24068. client.set_tcp_nodelay(true);
  24069. client.set_connection_timeout(3, 0);
  24070. bool socket_options_called = false;
  24071. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24072. ASSERT_TRUE(client.connect());
  24073. ASSERT_TRUE(client.is_open());
  24074. EXPECT_TRUE(socket_options_called);
  24075. ASSERT_TRUE(client.send("hello"));
  24076. std::string msg;
  24077. auto result = client.read(msg);
  24078. EXPECT_EQ(result, ws::ReadResult::Text);
  24079. EXPECT_EQ(msg, "hello");
  24080. client.close();
  24081. }
  24082. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24084. "/ws-echo");
  24085. client.set_connection_timeout(std::chrono::seconds(3));
  24086. client.set_write_timeout(std::chrono::seconds(3));
  24087. // A sub-second remainder exercises the seconds/microseconds split.
  24088. client.set_read_timeout(std::chrono::milliseconds(1500));
  24089. ASSERT_TRUE(client.connect());
  24090. auto start = std::chrono::steady_clock::now();
  24091. std::string msg;
  24092. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24093. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24094. std::chrono::steady_clock::now() - start)
  24095. .count();
  24096. // Above 1s so that dropping the microseconds half of the split fails here.
  24097. // Ignoring the setter altogether would not reach this line at all: a client
  24098. // waits forever by default.
  24099. EXPECT_GE(elapsed, 1400);
  24100. EXPECT_LT(elapsed, 30000);
  24101. }
  24102. #ifndef _WIN32
  24103. // A send() that times out after part of the data went out returns the count
  24104. // written so far. Every byte of the frame must still be sent, or the peer reads
  24105. // the next frame's header and payload as the rest of this one.
  24106. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24107. signal(SIGPIPE, SIG_IGN);
  24108. const std::string large(4 * 1024 * 1024, 'A');
  24109. std::atomic<bool> large_sent{false};
  24110. std::atomic<bool> small_sent{false};
  24111. Server svr;
  24112. svr.set_write_timeout(0, 500000);
  24113. svr.set_socket_options([](socket_t sock) {
  24114. int size = 8192;
  24115. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24116. reinterpret_cast<const char *>(&size), sizeof(size));
  24117. });
  24118. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24119. large_sent = ws.send(large.data(), large.size());
  24120. small_sent = ws.send("after");
  24121. std::string msg;
  24122. while (ws.read(msg)) {}
  24123. });
  24124. auto port = svr.bind_to_any_port(HOST);
  24125. std::thread t([&]() { svr.listen_after_bind(); });
  24126. auto se = detail::scope_exit([&] {
  24127. svr.stop();
  24128. t.join();
  24129. });
  24130. svr.wait_until_ready();
  24131. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24132. std::to_string(port) + "/ws");
  24133. client.set_read_timeout(5);
  24134. client.set_socket_options([](socket_t sock) {
  24135. int size = 8192;
  24136. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24137. reinterpret_cast<const char *>(&size), sizeof(size));
  24138. });
  24139. ASSERT_TRUE(client.connect());
  24140. // Outlast the server's write timeout, then drain.
  24141. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24142. std::string msg;
  24143. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24144. EXPECT_TRUE(msg == large);
  24145. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24146. EXPECT_EQ("after", msg);
  24147. EXPECT_TRUE(large_sent);
  24148. EXPECT_TRUE(small_sent);
  24149. client.close();
  24150. }
  24151. #endif
  24152. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24153. Server svr;
  24154. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24155. if (!req.has_header("Authorization")) {
  24156. res.status = StatusCode::Unauthorized_401;
  24157. res.set_content("Unauthorized", "text/plain");
  24158. return Server::HandlerResponse::Handled;
  24159. }
  24160. return Server::HandlerResponse::Unhandled;
  24161. });
  24162. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24163. std::string msg;
  24164. while (ws.read(msg)) {
  24165. ws.send(msg);
  24166. }
  24167. });
  24168. auto port = svr.bind_to_any_port("localhost");
  24169. std::thread t([&]() { svr.listen_after_bind(); });
  24170. svr.wait_until_ready();
  24171. // Without Authorization header - should be rejected before upgrade
  24172. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24173. EXPECT_FALSE(client1.connect());
  24174. // The rejection is framed like any other HTTP response
  24175. {
  24176. Client cli("localhost", port);
  24177. Headers headers = {{"Upgrade", "websocket"},
  24178. {"Connection", "Upgrade"},
  24179. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24180. {"Sec-WebSocket-Version", "13"}};
  24181. auto res = cli.Get("/ws", headers);
  24182. ASSERT_TRUE(res);
  24183. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24184. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24185. EXPECT_EQ("Unauthorized", res->body);
  24186. }
  24187. // With Authorization header - should succeed
  24188. Headers headers = {{"Authorization", "Bearer token123"}};
  24189. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24190. headers);
  24191. ASSERT_TRUE(client2.connect());
  24192. ASSERT_TRUE(client2.send("hello"));
  24193. std::string msg;
  24194. ASSERT_TRUE(client2.read(msg));
  24195. EXPECT_EQ("hello", msg);
  24196. client2.close();
  24197. svr.stop();
  24198. t.join();
  24199. }
  24200. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24201. Server svr;
  24202. std::atomic<int> pre_routing_calls{0};
  24203. std::atomic<int> pre_request_calls{0};
  24204. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24205. pre_routing_calls++;
  24206. if (req.path == "/handled") {
  24207. res.set_content("handled", "text/plain");
  24208. return Server::HandlerResponse::Handled;
  24209. }
  24210. return Server::HandlerResponse::Unhandled;
  24211. });
  24212. svr.set_pre_request_handler([&](const Request &, Response &) {
  24213. pre_request_calls++;
  24214. return Server::HandlerResponse::Unhandled;
  24215. });
  24216. svr.Get("/http", [](const Request &, Response &res) {
  24217. res.set_content("http", "text/plain");
  24218. });
  24219. svr.WebSocket("/ws",
  24220. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24221. auto port = svr.bind_to_any_port("localhost");
  24222. std::thread t([&]() { svr.listen_after_bind(); });
  24223. auto se = detail::scope_exit([&] {
  24224. svr.stop();
  24225. t.join();
  24226. });
  24227. svr.wait_until_ready();
  24228. Headers upgrade = {{"Upgrade", "websocket"},
  24229. {"Connection", "Upgrade"},
  24230. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24231. {"Sec-WebSocket-Version", "13"}};
  24232. auto get = [&](const char *path) {
  24233. pre_routing_calls = 0;
  24234. return Client("localhost", port).Get(path, upgrade);
  24235. };
  24236. // No WebSocket route, but an HTTP one
  24237. auto res = get("/http");
  24238. ASSERT_TRUE(res);
  24239. EXPECT_EQ(StatusCode::OK_200, res->status);
  24240. EXPECT_EQ("http", res->body);
  24241. EXPECT_EQ(1, pre_routing_calls);
  24242. EXPECT_EQ(1, pre_request_calls);
  24243. // No route at all
  24244. res = get("/none");
  24245. ASSERT_TRUE(res);
  24246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24247. EXPECT_EQ(1, pre_routing_calls);
  24248. // Answered by the pre-routing handler
  24249. res = get("/handled");
  24250. ASSERT_TRUE(res);
  24251. EXPECT_EQ(StatusCode::OK_200, res->status);
  24252. EXPECT_EQ("handled", res->body);
  24253. EXPECT_EQ(1, pre_routing_calls);
  24254. // A WebSocket route
  24255. pre_routing_calls = 0;
  24256. pre_request_calls = 0;
  24257. {
  24258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24259. "/ws");
  24260. ASSERT_TRUE(client.connect());
  24261. std::string msg;
  24262. ASSERT_TRUE(client.read(msg));
  24263. EXPECT_EQ("ws", msg);
  24264. client.close();
  24265. }
  24266. EXPECT_EQ(1, pre_routing_calls);
  24267. EXPECT_EQ(1, pre_request_calls);
  24268. }
  24269. // An upgrade request answered by a hook leaves its body unread, so that body
  24270. // must not be served as the next request on the connection.
  24271. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24272. Server svr;
  24273. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24274. if (req.path == "/pre-routing") {
  24275. res.set_content("pre-routing", "text/plain");
  24276. return Server::HandlerResponse::Handled;
  24277. }
  24278. return Server::HandlerResponse::Unhandled;
  24279. });
  24280. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24281. if (req.matched_route == "/pre-request") {
  24282. res.set_content("pre-request", "text/plain");
  24283. return Server::HandlerResponse::Handled;
  24284. }
  24285. return Server::HandlerResponse::Unhandled;
  24286. });
  24287. svr.Get("/smuggled", [](const Request &, Response &res) {
  24288. res.set_content("smuggled", "text/plain");
  24289. });
  24290. svr.WebSocket("/pre-request",
  24291. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24292. auto port = svr.bind_to_any_port(HOST);
  24293. std::thread t([&]() { svr.listen_after_bind(); });
  24294. auto se = detail::scope_exit([&] {
  24295. svr.stop();
  24296. t.join();
  24297. });
  24298. svr.wait_until_ready();
  24299. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24300. for (auto path : {"/pre-routing", "/pre-request"}) {
  24301. std::string req = std::string("GET ") + path +
  24302. " HTTP/1.1\r\n"
  24303. "Host: localhost\r\n"
  24304. "Upgrade: websocket\r\n"
  24305. "Connection: Upgrade\r\n"
  24306. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24307. "Sec-WebSocket-Version: 13\r\n"
  24308. "Content-Length: " +
  24309. std::to_string(body.size()) + "\r\n\r\n" + body;
  24310. std::string res;
  24311. ASSERT_TRUE(send_request(5, req, &res, port));
  24312. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24313. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24314. // Only one response, and the body was not served as a request
  24315. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24316. }
  24317. }
  24318. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24319. Server svr;
  24320. std::atomic<int> pre_request_calls{0};
  24321. std::atomic<bool> route_matched{false};
  24322. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24323. pre_request_calls++;
  24324. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24325. if (req.get_header_value("Authorization") != "Bearer token123") {
  24326. res.status = StatusCode::Unauthorized_401;
  24327. res.set_content("Unauthorized", "text/plain");
  24328. return Server::HandlerResponse::Handled;
  24329. }
  24330. return Server::HandlerResponse::Unhandled;
  24331. });
  24332. std::atomic<bool> handler_called{false};
  24333. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24334. handler_called = true;
  24335. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24336. });
  24337. auto port = svr.bind_to_any_port("localhost");
  24338. std::thread t([&]() { svr.listen_after_bind(); });
  24339. svr.wait_until_ready();
  24340. // Without Authorization header - should be rejected before upgrade
  24341. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24342. "/ws/1");
  24343. EXPECT_FALSE(client1.connect());
  24344. EXPECT_FALSE(handler_called);
  24345. EXPECT_EQ(1, pre_request_calls);
  24346. EXPECT_TRUE(route_matched);
  24347. // The rejection is an ordinary HTTP response, not a protocol switch
  24348. {
  24349. Client cli("localhost", port);
  24350. Headers headers = {{"Upgrade", "websocket"},
  24351. {"Connection", "Upgrade"},
  24352. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24353. {"Sec-WebSocket-Version", "13"}};
  24354. auto res = cli.Get("/ws/1", headers);
  24355. ASSERT_TRUE(res);
  24356. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24357. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24358. EXPECT_EQ("Unauthorized", res->body);
  24359. }
  24360. EXPECT_FALSE(handler_called);
  24361. // With Authorization header - should succeed
  24362. Headers headers = {{"Authorization", "Bearer token123"}};
  24363. ws::WebSocketClient client2(
  24364. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24365. ASSERT_TRUE(client2.connect());
  24366. std::string msg;
  24367. ASSERT_TRUE(client2.read(msg));
  24368. EXPECT_EQ("/ws/:id 2", msg);
  24369. EXPECT_TRUE(handler_called);
  24370. client2.close();
  24371. svr.stop();
  24372. t.join();
  24373. }
  24374. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24375. static Headers websocket_upgrade_headers() {
  24376. return {{"Upgrade", "websocket"},
  24377. {"Connection", "Upgrade"},
  24378. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24379. {"Sec-WebSocket-Version", "13"},
  24380. {"Sec-WebSocket-Protocol", "chat"}};
  24381. }
  24382. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24383. Server svr;
  24384. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24385. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24386. return Server::HandlerResponse::Unhandled;
  24387. });
  24388. svr.set_pre_request_handler([](const Request &req, Response &) {
  24389. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24390. return Server::HandlerResponse::Unhandled;
  24391. });
  24392. svr.set_exception_handler(
  24393. [](const Request &, Response &res, std::exception_ptr ep) {
  24394. try {
  24395. std::rethrow_exception(ep);
  24396. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24397. });
  24398. auto handler = [](const Request &, ws::WebSocket &) {};
  24399. svr.WebSocket("/pre-routing", handler);
  24400. svr.WebSocket("/pre-request", handler);
  24401. svr.WebSocket("/sub-protocol", handler,
  24402. [](const std::vector<std::string> &) -> std::string {
  24403. throw std::runtime_error("/sub-protocol");
  24404. });
  24405. auto port = svr.bind_to_any_port(HOST);
  24406. ASSERT_GT(port, 0);
  24407. thread t = thread([&] { svr.listen_after_bind(); });
  24408. auto se = detail::scope_exit([&] {
  24409. svr.stop();
  24410. t.join();
  24411. ASSERT_FALSE(svr.is_running());
  24412. });
  24413. svr.wait_until_ready();
  24414. Client cli(HOST, port);
  24415. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24416. auto res = cli.Get(path, websocket_upgrade_headers());
  24417. if (!res) {
  24418. ADD_FAILURE() << path << ": " << to_string(res.error());
  24419. continue;
  24420. }
  24421. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24422. EXPECT_EQ(path, res->body);
  24423. }
  24424. }
  24425. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24426. Server svr;
  24427. svr.set_pre_routing_handler(
  24428. [](const Request &, Response &) -> Server::HandlerResponse {
  24429. throw std::runtime_error("pre-routing");
  24430. });
  24431. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24432. auto port = svr.bind_to_any_port(HOST);
  24433. ASSERT_GT(port, 0);
  24434. thread t = thread([&] { svr.listen_after_bind(); });
  24435. auto se = detail::scope_exit([&] {
  24436. svr.stop();
  24437. t.join();
  24438. ASSERT_FALSE(svr.is_running());
  24439. });
  24440. svr.wait_until_ready();
  24441. Client cli(HOST, port);
  24442. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24443. ASSERT_TRUE(res) << to_string(res.error());
  24444. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24445. }
  24446. #endif
  24447. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24448. Server svr;
  24449. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24450. // A read timeout is how a handler gets control back. Without it, a handler
  24451. // parked in read() can never write on the connection it is reading.
  24452. ws.set_read_timeout(std::chrono::milliseconds(100));
  24453. std::string msg;
  24454. while (ws.is_open()) {
  24455. auto r = ws.read(msg);
  24456. if (r == httplib::ws::Timeout) {
  24457. ws.send("tick");
  24458. continue;
  24459. }
  24460. if (r == httplib::ws::Fail) { break; }
  24461. ws.send(msg);
  24462. }
  24463. });
  24464. auto port = svr.bind_to_any_port("localhost");
  24465. std::thread t([&]() { svr.listen_after_bind(); });
  24466. svr.wait_until_ready();
  24467. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24468. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24469. ASSERT_TRUE(client.connect());
  24470. // The client sends nothing, so anything it receives came out of the
  24471. // handler's timeout path.
  24472. std::string msg;
  24473. ASSERT_EQ(client.read(msg), ws::Text);
  24474. EXPECT_EQ("tick", msg);
  24475. client.close();
  24476. svr.stop();
  24477. t.join();
  24478. }
  24479. // Stream::read may return fewer bytes than asked for. This is that contract at
  24480. // its worst -- one byte per call -- which is what a frame header straddling a
  24481. // read buffer's boundary looks like to the frame parser.
  24482. class WsByteAtATimeStream : public Stream {
  24483. public:
  24484. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24485. bool is_readable() const override { return true; }
  24486. bool wait_readable() const override { return true; }
  24487. bool wait_writable() const override { return true; }
  24488. ssize_t read(char *ptr, size_t size) override {
  24489. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24490. *ptr = data_[pos_++];
  24491. return 1;
  24492. }
  24493. ssize_t write(const char *, size_t size) override {
  24494. return static_cast<ssize_t>(size);
  24495. }
  24496. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24497. ip = "127.0.0.1";
  24498. port = 0;
  24499. }
  24500. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24501. ip = "127.0.0.1";
  24502. port = 0;
  24503. }
  24504. socket_t socket() const override { return INVALID_SOCKET; }
  24505. time_t duration() const override { return 0; }
  24506. private:
  24507. std::string data_;
  24508. size_t pos_ = 0;
  24509. };
  24510. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24511. // The payload uses the 16-bit extended length, so the header, the length
  24512. // and the mask key are all multi-byte fields here. Each used to be read
  24513. // with a single read() call, which fails as soon as one is split. The
  24514. // payload is also a little over one read chunk, so it is read in two.
  24515. std::string body;
  24516. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24517. body += static_cast<char>(i % 251);
  24518. }
  24519. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24520. std::string frame;
  24521. frame += static_cast<char>(0x81); // FIN + Text
  24522. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24523. frame += static_cast<char>(body.size() >> 8);
  24524. frame += static_cast<char>(body.size() & 0xff);
  24525. for (size_t i = 0; i < 4; i++) {
  24526. frame += static_cast<char>(mask[i]);
  24527. }
  24528. for (size_t i = 0; i < body.size(); i++) {
  24529. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24530. }
  24531. WsByteAtATimeStream strm(frame);
  24532. ws::Opcode opcode;
  24533. std::string payload;
  24534. bool fin = false;
  24535. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24536. /*expect_masked=*/true, body.size()),
  24537. ws::impl::FrameRead::Ok);
  24538. EXPECT_TRUE(fin);
  24539. EXPECT_EQ(opcode, ws::Opcode::Text);
  24540. EXPECT_EQ(payload, body);
  24541. }
  24542. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24543. std::string body(2000, 'x');
  24544. std::string frame;
  24545. frame += static_cast<char>(0x82); // FIN + Binary
  24546. frame += static_cast<char>(126); // 16-bit length follows
  24547. frame += static_cast<char>(body.size() >> 8);
  24548. frame += static_cast<char>(body.size() & 0xff);
  24549. frame += body;
  24550. detail::BufferStream strm;
  24551. strm.write(frame.data(), frame.size());
  24552. ws::Opcode opcode;
  24553. std::string payload;
  24554. bool fin;
  24555. EXPECT_EQ(
  24556. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24557. ws::impl::FrameRead::Ok);
  24558. EXPECT_EQ(body, payload);
  24559. }
  24560. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24561. // The header announces the largest payload allowed, and only 3 bytes of it
  24562. // ever arrive.
  24563. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24564. std::string frame;
  24565. frame += static_cast<char>(0x82); // FIN + Binary
  24566. frame += static_cast<char>(127); // 64-bit length follows
  24567. for (int shift = 56; shift >= 0; shift -= 8) {
  24568. frame += static_cast<char>((len >> shift) & 0xff);
  24569. }
  24570. frame += "abc";
  24571. detail::BufferStream strm;
  24572. strm.write(frame.data(), frame.size());
  24573. ws::Opcode opcode;
  24574. std::string payload;
  24575. bool fin;
  24576. EXPECT_EQ(
  24577. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24578. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24579. ws::impl::FrameRead::Fail);
  24580. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24581. }
  24582. TEST(WebSocketTest, QueryStringInHandshake) {
  24583. Server svr;
  24584. std::mutex mtx;
  24585. std::string received_target;
  24586. std::string received_token;
  24587. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24588. {
  24589. std::lock_guard<std::mutex> lock(mtx);
  24590. received_target = req.target;
  24591. if (req.has_param("token")) {
  24592. received_token = req.get_param_value("token");
  24593. }
  24594. }
  24595. std::string msg;
  24596. while (ws.read(msg)) {
  24597. ws.send(msg);
  24598. }
  24599. });
  24600. auto port = svr.bind_to_any_port("localhost");
  24601. std::thread t([&]() { svr.listen_after_bind(); });
  24602. svr.wait_until_ready();
  24603. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24604. "/ws?token=ABC&session=123");
  24605. ASSERT_TRUE(client.connect());
  24606. // Round-trip ensures the handler has run and captured the request.
  24607. ASSERT_TRUE(client.send("hello"));
  24608. std::string msg;
  24609. ASSERT_TRUE(client.read(msg));
  24610. EXPECT_EQ("hello", msg);
  24611. client.close();
  24612. {
  24613. std::lock_guard<std::mutex> lock(mtx);
  24614. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24615. EXPECT_EQ("ABC", received_token);
  24616. }
  24617. svr.stop();
  24618. t.join();
  24619. }
  24620. // Run a handshake against a throwaway server and hand the request the server
  24621. // received back to the caller, so tests can assert on the headers the client
  24622. // actually put on the wire.
  24623. static void capture_websocket_handshake_request(
  24624. const Headers &client_headers,
  24625. std::function<void(const Request &, int port)> verify) {
  24626. Server svr;
  24627. std::mutex mtx;
  24628. Request received;
  24629. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24630. {
  24631. std::lock_guard<std::mutex> lock(mtx);
  24632. received = req;
  24633. }
  24634. std::string msg;
  24635. while (ws.read(msg)) {
  24636. ws.send(msg);
  24637. }
  24638. });
  24639. auto port = svr.bind_to_any_port("localhost");
  24640. std::thread t([&]() { svr.listen_after_bind(); });
  24641. auto se = detail::scope_exit([&] {
  24642. svr.stop();
  24643. t.join();
  24644. });
  24645. svr.wait_until_ready();
  24646. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24647. client_headers);
  24648. ASSERT_TRUE(client.connect());
  24649. ASSERT_TRUE(client.send("hello"));
  24650. std::string msg;
  24651. ASSERT_TRUE(client.read(msg));
  24652. client.close();
  24653. {
  24654. std::lock_guard<std::mutex> lock(mtx);
  24655. verify(received, port);
  24656. }
  24657. }
  24658. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24659. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24660. // Non-default port must be present in the Host header. Default ports
  24661. // (80/443) are omitted; that logic is covered by
  24662. // MakeHostAndPortStringTest.
  24663. EXPECT_EQ("localhost:" + std::to_string(port),
  24664. req.get_header_value("Host"));
  24665. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24666. req.get_header_value("User-Agent"));
  24667. EXPECT_FALSE(req.has_header("Accept"));
  24668. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24669. EXPECT_FALSE(req.has_header("Content-Length"));
  24670. });
  24671. }
  24672. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24673. capture_websocket_handshake_request(
  24674. {{"Host", "example.com"},
  24675. {"User-Agent", "custom-agent"},
  24676. {"X-Custom", "value"}},
  24677. [](const Request &req, int) {
  24678. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24679. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24680. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24681. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24682. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24683. });
  24684. }
  24685. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24686. capture_websocket_handshake_request(
  24687. {{"Upgrade", "bogus"},
  24688. {"Connection", "close"},
  24689. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24690. {"Sec-WebSocket-Version", "8"}},
  24691. [](const Request &req, int) {
  24692. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24693. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24694. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24695. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24696. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24697. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24698. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24699. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24700. req.get_header_value("Sec-WebSocket-Key"));
  24701. });
  24702. }
  24703. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24704. // A header the client refuses to send must abort the handshake before any
  24705. // part of it reaches the wire; a lone request line would otherwise sit in
  24706. // the peer's buffer as a truncated request.
  24707. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24708. ASSERT_NE(INVALID_SOCKET, srv);
  24709. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24710. sockaddr_in addr{};
  24711. addr.sin_family = AF_INET;
  24712. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24713. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24714. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24715. ASSERT_EQ(0, ::listen(srv, 1));
  24716. sockaddr_in bound{};
  24717. socklen_t bound_len = sizeof(bound);
  24718. ASSERT_EQ(
  24719. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24720. auto port = ntohs(bound.sin_port);
  24721. ssize_t received = -1;
  24722. std::thread t([&] {
  24723. // Bound every blocking call so a regression fails the test with a bad
  24724. // value instead of hanging the suite.
  24725. fd_set rfds;
  24726. FD_ZERO(&rfds);
  24727. FD_SET(srv, &rfds);
  24728. timeval tv{5, 0};
  24729. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24730. 0) {
  24731. return;
  24732. }
  24733. sockaddr_in cli_addr{};
  24734. socklen_t cli_len = sizeof(cli_addr);
  24735. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24736. if (cli == INVALID_SOCKET) { return; }
  24737. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24738. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24739. char buf[4096];
  24740. received = ::recv(cli, buf, sizeof(buf), 0);
  24741. });
  24742. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24743. // connect() has already shut the socket down by the time it returns false,
  24744. // so the peer sees EOF without waiting for the client to be destroyed.
  24745. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24746. {{"X-Bad", "a\r\nInjected: 1"}});
  24747. EXPECT_FALSE(client.connect());
  24748. t.join();
  24749. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24750. EXPECT_EQ(0, received);
  24751. }
  24752. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24753. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24754. // contains "upgrade" as a substring is a different token and must not
  24755. // start a WebSocket handshake.
  24756. auto make_request = [](const std::vector<std::string> &connection_values) {
  24757. Request req;
  24758. req.method = "GET";
  24759. req.headers.emplace("Upgrade", "websocket");
  24760. for (const auto &value : connection_values) {
  24761. req.headers.emplace("Connection", value);
  24762. }
  24763. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24764. req.headers.emplace("Sec-WebSocket-Version", "13");
  24765. return req;
  24766. };
  24767. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24768. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24769. EXPECT_TRUE(
  24770. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24771. EXPECT_TRUE(
  24772. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24773. EXPECT_TRUE(
  24774. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24775. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24776. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24777. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24778. EXPECT_FALSE(
  24779. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24780. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24781. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24782. }
  24783. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24784. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24785. // asks recipients to match each protocol-name case-insensitively, and RFC
  24786. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24787. // client naming websocket alongside another protocol, or on a second field
  24788. // line, is offering websocket; a value that merely contains "websocket" as a
  24789. // substring is a different protocol name and is not.
  24790. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24791. Request req;
  24792. req.method = "GET";
  24793. for (const auto &value : upgrade_values) {
  24794. req.headers.emplace("Upgrade", value);
  24795. }
  24796. req.headers.emplace("Connection", "Upgrade");
  24797. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24798. req.headers.emplace("Sec-WebSocket-Version", "13");
  24799. return req;
  24800. };
  24801. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24802. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24803. EXPECT_TRUE(
  24804. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24805. EXPECT_TRUE(
  24806. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24807. EXPECT_TRUE(
  24808. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24809. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24810. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24811. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24812. EXPECT_FALSE(
  24813. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24814. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24815. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24816. }
  24817. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24818. Server svr;
  24819. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24820. auto port = svr.bind_to_any_port("localhost");
  24821. std::thread t([&]() { svr.listen_after_bind(); });
  24822. auto se = detail::scope_exit([&] {
  24823. svr.stop();
  24824. t.join();
  24825. });
  24826. svr.wait_until_ready();
  24827. Headers headers = {{"Upgrade", "websocket"},
  24828. {"Connection", "notupgrade"},
  24829. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24830. {"Sec-WebSocket-Version", "13"}};
  24831. Client cli("localhost", port);
  24832. auto res = cli.Get("/ws", headers);
  24833. // The route exists only as a WebSocket route, so a request that fails the
  24834. // handshake check falls through to ordinary routing.
  24835. ASSERT_TRUE(res);
  24836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24837. }
  24838. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24839. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24840. // Connection value is the only thing left for the client to reject.
  24841. Server svr;
  24842. svr.Get("/ws", [](const Request &req, Response &res) {
  24843. res.status = StatusCode::SwitchingProtocol_101;
  24844. res.set_header("Upgrade", "websocket");
  24845. res.set_header("Connection", "notupgrade");
  24846. res.set_header("Sec-WebSocket-Accept",
  24847. detail::websocket_accept_key(
  24848. req.get_header_value("Sec-WebSocket-Key")));
  24849. });
  24850. auto port = svr.bind_to_any_port("localhost");
  24851. std::thread t([&]() { svr.listen_after_bind(); });
  24852. auto se = detail::scope_exit([&] {
  24853. svr.stop();
  24854. t.join();
  24855. });
  24856. svr.wait_until_ready();
  24857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24858. auto res = client.connect();
  24859. EXPECT_FALSE(res);
  24860. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24861. EXPECT_FALSE(client.is_open());
  24862. }
  24863. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24864. Server svr;
  24865. svr.Get("/ws", [](const Request &req, Response &res) {
  24866. res.status = StatusCode::SwitchingProtocol_101;
  24867. res.set_header("Upgrade", "websocket");
  24868. res.set_header("Connection", "Upgrade");
  24869. res.set_header("Sec-WebSocket-Accept",
  24870. detail::websocket_accept_key(
  24871. req.get_header_value("Sec-WebSocket-Key")));
  24872. res.set_header("Sec-WebSocket-Protocol", "admin");
  24873. });
  24874. auto port = svr.bind_to_any_port("localhost");
  24875. std::thread t([&]() { svr.listen_after_bind(); });
  24876. auto se = detail::scope_exit([&] {
  24877. svr.stop();
  24878. t.join();
  24879. });
  24880. svr.wait_until_ready();
  24881. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24882. // Server selects a subprotocol the client never offered
  24883. {
  24884. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24885. ws::WebSocketClient client(url, headers);
  24886. auto res = client.connect();
  24887. EXPECT_FALSE(res);
  24888. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24889. EXPECT_FALSE(client.is_open());
  24890. EXPECT_TRUE(client.subprotocol().empty());
  24891. }
  24892. // Client offered none but the server named one anyway
  24893. {
  24894. ws::WebSocketClient client(url);
  24895. auto res = client.connect();
  24896. EXPECT_FALSE(res);
  24897. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24898. EXPECT_FALSE(client.is_open());
  24899. EXPECT_TRUE(client.subprotocol().empty());
  24900. }
  24901. }
  24902. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24903. // The socket path doubles as the URL host, so it must not contain '/'.
  24904. const char *shard = getenv("GTEST_SHARD_INDEX");
  24905. const std::string sock_path =
  24906. shard ? std::string("httplib-ws-") + shard + ".sock"
  24907. : std::string("httplib-ws.sock");
  24908. std::remove(sock_path.c_str());
  24909. Server svr;
  24910. std::mutex mtx;
  24911. std::string received_host;
  24912. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24913. {
  24914. std::lock_guard<std::mutex> lock(mtx);
  24915. received_host = req.get_header_value("Host");
  24916. }
  24917. std::string msg;
  24918. while (ws.read(msg)) {
  24919. ws.send(msg);
  24920. }
  24921. });
  24922. svr.set_address_family(AF_UNIX);
  24923. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24924. auto se = detail::scope_exit([&] {
  24925. svr.stop();
  24926. t.join();
  24927. std::remove(sock_path.c_str());
  24928. });
  24929. svr.wait_until_ready();
  24930. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24931. client.set_address_family(AF_UNIX);
  24932. ASSERT_TRUE(client.connect());
  24933. ASSERT_TRUE(client.send("hello"));
  24934. std::string msg;
  24935. ASSERT_TRUE(client.read(msg));
  24936. client.close();
  24937. {
  24938. std::lock_guard<std::mutex> lock(mtx);
  24939. // There is no host:port for a Unix socket, so the same "localhost"
  24940. // placeholder the HTTP client uses is expected.
  24941. EXPECT_EQ("localhost", received_host);
  24942. }
  24943. }
  24944. // Two threads must never parse WebSocket frames from the same stream.
  24945. // close() used to read the peer's Close reply with its own frame read, so it
  24946. // raced a reader thread that was in the middle of a payload: the payload loop
  24947. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24948. // so bytes taken by close() were replaced with bytes from further along the
  24949. // stream. The message kept its length and silently changed content.
  24950. //
  24951. // The raw peer below sends a frame header plus part of the payload, waits for
  24952. // the handler to call close(), and only then sends the rest. Whichever thread
  24953. // would win the race for those bytes, the message must arrive intact, because
  24954. // close() must not touch the stream while read() owns it.
  24955. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24956. #ifndef _WIN32
  24957. signal(SIGPIPE, SIG_IGN);
  24958. #endif
  24959. const size_t payload_len = 120; // fits the 7-bit length field
  24960. const size_t prefix_len = 8;
  24961. const int attempts = 8;
  24962. std::string expected(payload_len, '\0');
  24963. for (size_t i = 0; i < payload_len; i++) {
  24964. expected[i] = static_cast<char>('a' + i % 26);
  24965. }
  24966. std::atomic<bool> peer_stalled{false};
  24967. std::atomic<bool> handler_done{false};
  24968. std::mutex received_mutex;
  24969. std::vector<std::string> received;
  24970. // Bound every wait, so a regression fails the test instead of hanging the
  24971. // suite.
  24972. auto wait_for = [](const std::atomic<bool> &flag) {
  24973. for (int i = 0; i < 500 && !flag; i++) {
  24974. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24975. }
  24976. };
  24977. Server svr;
  24978. svr.set_websocket_ping_interval(0);
  24979. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24980. std::thread reader([&]() {
  24981. std::string msg;
  24982. while (ws.read(msg)) {
  24983. std::lock_guard<std::mutex> guard(received_mutex);
  24984. received.push_back(msg);
  24985. }
  24986. });
  24987. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24988. // inside read_websocket_frame() when close() runs.
  24989. wait_for(peer_stalled);
  24990. ws.close();
  24991. reader.join();
  24992. handler_done = true;
  24993. });
  24994. auto port = svr.bind_to_any_port("127.0.0.1");
  24995. std::thread t([&]() { svr.listen_after_bind(); });
  24996. auto se = detail::scope_exit([&] {
  24997. svr.stop();
  24998. t.join();
  24999. });
  25000. svr.wait_until_ready();
  25001. auto send_bytes = [](socket_t s, const std::string &data) {
  25002. #ifdef _WIN32
  25003. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25004. #else
  25005. auto n = ::send(s, data.data(), data.size(), 0);
  25006. #endif
  25007. return n == static_cast<decltype(n)>(data.size());
  25008. };
  25009. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25010. // Every length used here fits the 7-bit length field.
  25011. auto masked_header = [](uint8_t first_byte, size_t len) {
  25012. std::string h;
  25013. h += static_cast<char>(first_byte);
  25014. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25015. h.append(4, '\0'); // mask key
  25016. return h;
  25017. };
  25018. for (int attempt = 0; attempt < attempts; attempt++) {
  25019. peer_stalled = false;
  25020. handler_done = false;
  25021. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25022. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25023. auto se_sock = detail::scope_exit([&] {
  25024. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25025. });
  25026. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25027. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25028. sockaddr_in addr{};
  25029. addr.sin_family = AF_INET;
  25030. addr.sin_port = htons(static_cast<uint16_t>(port));
  25031. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25032. ASSERT_EQ(
  25033. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25034. << "attempt " << attempt;
  25035. ASSERT_TRUE(send_bytes(sock,
  25036. "GET /ws HTTP/1.1\r\n"
  25037. "Host: 127.0.0.1\r\n"
  25038. "Upgrade: websocket\r\n"
  25039. "Connection: Upgrade\r\n"
  25040. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25041. "Sec-WebSocket-Version: 13\r\n"
  25042. "\r\n"))
  25043. << "attempt " << attempt;
  25044. std::string response;
  25045. while (response.find("\r\n\r\n") == std::string::npos) {
  25046. char buf[512];
  25047. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25048. if (n <= 0) { break; }
  25049. response.append(buf, static_cast<size_t>(n));
  25050. }
  25051. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25052. << "attempt " << attempt;
  25053. // Send the header of a Binary message but only the first prefix_len bytes
  25054. // of its payload, leaving the reader thread stalled inside the payload.
  25055. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25056. expected.substr(0, prefix_len)))
  25057. << "attempt " << attempt;
  25058. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25059. peer_stalled = true;
  25060. // Let close() send its Close frame and park in its own read before the
  25061. // rest of the payload arrives, so both threads are waiting for it.
  25062. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25063. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25064. close_frame += static_cast<char>(0x03); // status 1000
  25065. close_frame += static_cast<char>(0xE8);
  25066. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25067. << "attempt " << attempt;
  25068. // Closing the peer releases the reader thread even on the buggy path,
  25069. // where it waits for bytes another thread already consumed.
  25070. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25071. detail::close_socket(sock);
  25072. sock = INVALID_SOCKET;
  25073. wait_for(handler_done);
  25074. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25075. }
  25076. std::lock_guard<std::mutex> guard(received_mutex);
  25077. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25078. << "a message in flight when close() ran was dropped";
  25079. for (size_t i = 0; i < received.size(); i++) {
  25080. EXPECT_EQ(expected, received[i]) << "message " << i;
  25081. }
  25082. }
  25083. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25084. // returning the socket, or INVALID_SOCKET.
  25085. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25086. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25087. if (sock == INVALID_SOCKET) { return sock; }
  25088. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25089. sockaddr_in addr{};
  25090. addr.sin_family = AF_INET;
  25091. addr.sin_port = htons(static_cast<uint16_t>(port));
  25092. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25093. std::string req = "GET " + path +
  25094. " HTTP/1.1\r\n"
  25095. "Host: 127.0.0.1\r\n"
  25096. "Upgrade: websocket\r\n"
  25097. "Connection: Upgrade\r\n"
  25098. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25099. "Sec-WebSocket-Version: 13\r\n"
  25100. "\r\n";
  25101. std::string res;
  25102. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25103. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25104. static_cast<ssize_t>(req.size())) {
  25105. char c;
  25106. while (res.find("\r\n\r\n") == std::string::npos &&
  25107. ::recv(sock, &c, 1, 0) == 1) {
  25108. res += c;
  25109. }
  25110. }
  25111. if (res.find(" 101 ") == std::string::npos) {
  25112. detail::close_socket(sock);
  25113. return INVALID_SOCKET;
  25114. }
  25115. return sock;
  25116. }
  25117. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25118. // The payload must fit the 7-bit length field.
  25119. static std::string masked_frame(uint8_t first_byte,
  25120. const std::string &payload) {
  25121. std::string f;
  25122. f += static_cast<char>(first_byte);
  25123. f += static_cast<char>(0x80 | payload.size());
  25124. f.append(4, '\0');
  25125. return f + payload;
  25126. }
  25127. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25128. std::atomic<bool> done{false};
  25129. std::string received;
  25130. Server svr;
  25131. svr.set_websocket_ping_interval(0);
  25132. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25133. std::string msg;
  25134. if (ws.read(msg) == ws::Binary) { received = msg; }
  25135. done = true;
  25136. });
  25137. auto port = svr.bind_to_any_port("127.0.0.1");
  25138. std::thread t([&]() { svr.listen_after_bind(); });
  25139. auto se = detail::scope_exit([&] {
  25140. svr.stop();
  25141. t.join();
  25142. });
  25143. svr.wait_until_ready();
  25144. auto sock = connect_raw_websocket(port, "/ws");
  25145. ASSERT_NE(INVALID_SOCKET, sock);
  25146. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25147. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25148. masked_frame(0x89, "p") + // FIN + Ping
  25149. masked_frame(0x80, "lo"); // FIN + Continuation
  25150. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25151. for (int i = 0; i < 500 && !done; i++) {
  25152. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25153. }
  25154. ASSERT_TRUE(done);
  25155. EXPECT_EQ("Hello", received);
  25156. // The Ping between the fragments is answered with a Pong.
  25157. char pong[3];
  25158. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25159. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25160. }
  25161. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25162. Server svr;
  25163. svr.set_websocket_ping_interval(-1);
  25164. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25165. std::string msg;
  25166. while (ws.read(msg)) {}
  25167. });
  25168. auto port = svr.bind_to_any_port("127.0.0.1");
  25169. std::thread t([&]() { svr.listen_after_bind(); });
  25170. auto se = detail::scope_exit([&] {
  25171. svr.stop();
  25172. t.join();
  25173. });
  25174. svr.wait_until_ready();
  25175. auto sock = connect_raw_websocket(port, "/ws");
  25176. ASSERT_NE(INVALID_SOCKET, sock);
  25177. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25178. // Nothing comes while the client stays quiet.
  25179. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25180. char c;
  25181. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25182. }
  25183. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25184. // and that has to end a read() already waiting on the peer, on every platform.
  25185. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25186. // The peer sends no pings, and its handler never calls read(), which is
  25187. // where pongs are written.
  25188. std::mutex mutex;
  25189. std::condition_variable cv;
  25190. auto release = false;
  25191. svr.set_websocket_ping_interval(0);
  25192. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25193. std::unique_lock<std::mutex> lock(mutex);
  25194. cv.wait(lock, [&] { return release; });
  25195. });
  25196. auto port = svr.bind_to_any_port(HOST);
  25197. std::thread t([&]() { svr.listen_after_bind(); });
  25198. auto se = detail::scope_exit([&] {
  25199. {
  25200. std::lock_guard<std::mutex> lock(mutex);
  25201. release = true;
  25202. }
  25203. cv.notify_all();
  25204. svr.stop();
  25205. t.join();
  25206. });
  25207. svr.wait_until_ready();
  25208. ws::WebSocketClient client(std::string(scheme) +
  25209. "://localhost:" + std::to_string(port) + "/ws");
  25210. #ifdef CPPHTTPLIB_SSL_ENABLED
  25211. client.enable_server_certificate_verification(false);
  25212. #endif
  25213. // A ping a second, given up on after two go unanswered: about 3s
  25214. client.set_websocket_ping_interval(1);
  25215. client.set_websocket_max_missed_pongs(2);
  25216. // Well past that, so that a read the timeout ends instead stands out
  25217. client.set_read_timeout(10);
  25218. ASSERT_TRUE(client.connect());
  25219. auto start = std::chrono::steady_clock::now();
  25220. std::string msg;
  25221. EXPECT_EQ(ws::Fail, client.read(msg));
  25222. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25223. std::chrono::steady_clock::now() - start)
  25224. .count(),
  25225. 6000);
  25226. EXPECT_FALSE(client.is_open());
  25227. }
  25228. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25229. Server svr;
  25230. check_pong_timeout_ends_read(svr, "ws");
  25231. }
  25232. #ifdef CPPHTTPLIB_SSL_ENABLED
  25233. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25235. ASSERT_TRUE(svr.is_valid());
  25236. check_pong_timeout_ends_read(svr, "wss");
  25237. }
  25238. #endif
  25239. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25240. Server svr;
  25241. svr.set_websocket_ping_interval(0);
  25242. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25243. std::string msg;
  25244. while (ws.read(msg)) {}
  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. // Each Close payload and the reply it should get: an echo when valid, 1002
  25254. // otherwise.
  25255. std::vector<std::pair<std::string, std::string>> cases = {
  25256. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25257. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25258. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25259. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25260. };
  25261. // Also between the fragments of a message.
  25262. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25263. for (const auto &c : cases) {
  25264. auto sock = connect_raw_websocket(port, "/ws");
  25265. ASSERT_NE(INVALID_SOCKET, sock);
  25266. auto frames = prefix + masked_frame(0x88, c.first);
  25267. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25268. std::string reply;
  25269. char buf[256];
  25270. while (reply.size() < 2 + c.second.size()) {
  25271. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25272. if (n <= 0) { break; }
  25273. reply.append(buf, static_cast<size_t>(n));
  25274. }
  25275. detail::close_socket(sock);
  25276. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25277. c.second,
  25278. reply);
  25279. }
  25280. }
  25281. }
  25282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25283. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25284. protected:
  25285. void SetUp() override {
  25286. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25287. SERVER_PRIVATE_KEY_FILE);
  25288. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25289. std::string msg;
  25290. ws::ReadResult ret;
  25291. while ((ret = ws.read(msg))) {
  25292. if (ret == ws::Binary) {
  25293. ws.send(msg.data(), msg.size());
  25294. } else {
  25295. ws.send(msg);
  25296. }
  25297. }
  25298. });
  25299. port_ = server_->bind_to_any_port(HOST);
  25300. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25301. server_->wait_until_ready();
  25302. }
  25303. void TearDown() override {
  25304. server_->stop();
  25305. if (server_thread_.joinable()) { server_thread_.join(); }
  25306. }
  25307. std::unique_ptr<SSLServer> server_;
  25308. std::thread server_thread_;
  25309. int port_ = 0;
  25310. };
  25311. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25312. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25313. {
  25314. ws::WebSocketClient client(url);
  25315. client.enable_server_certificate_verification(false);
  25316. auto calls = 0;
  25317. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25318. calls++;
  25319. return false;
  25320. });
  25321. EXPECT_FALSE(client.connect());
  25322. EXPECT_GT(calls, 0);
  25323. }
  25324. {
  25325. ws::WebSocketClient client(url);
  25326. client.enable_server_certificate_verification(false);
  25327. client.set_session_verifier([](tls::session_t) {
  25328. return SSLVerifierResponse::CertificateRejected;
  25329. });
  25330. EXPECT_FALSE(client.connect());
  25331. }
  25332. {
  25333. ws::WebSocketClient client(url);
  25334. client.enable_server_certificate_verification(false);
  25335. client.set_session_verifier([](tls::session_t) {
  25336. return SSLVerifierResponse::CertificateAccepted;
  25337. });
  25338. EXPECT_TRUE(client.connect());
  25339. }
  25340. }
  25341. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25342. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25343. "/ws-echo");
  25344. client.enable_server_certificate_verification(false);
  25345. ASSERT_TRUE(client.connect());
  25346. ASSERT_TRUE(client.is_open());
  25347. ASSERT_TRUE(client.send("Hello WSS"));
  25348. std::string msg;
  25349. EXPECT_EQ(ws::Text, client.read(msg));
  25350. EXPECT_EQ("Hello WSS", msg);
  25351. client.close();
  25352. }
  25353. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25354. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25355. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25356. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25357. // client (without calling close() first) is the only path that runs
  25358. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25359. // bug exactly.
  25360. //
  25361. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25362. // when linked against an instrumented libssl; run under Valgrind to catch it
  25363. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25364. // suite (the freed session otherwise stalls on the close handshake) — this test
  25365. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25366. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25367. {
  25368. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25369. "/ws-echo");
  25370. client.enable_server_certificate_verification(false);
  25371. client.set_read_timeout(2, 0);
  25372. client.set_write_timeout(2, 0);
  25373. ASSERT_TRUE(client.connect());
  25374. ASSERT_TRUE(client.is_open());
  25375. ASSERT_TRUE(client.send("still open"));
  25376. // Intentionally do NOT call client.close(): leaving scope runs
  25377. // shutdown_and_close() with the WebSocket still open, which must send the
  25378. // close frame while the TLS session is still alive.
  25379. }
  25380. }
  25381. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25382. // shutdown_and_close() at the start of connect(), reproducing the same
  25383. // use-after-free within the test body rather than at scope exit. The second
  25384. // connect must succeed and echo, proving the close handshake ran over a live
  25385. // session. See the note above about memory-tool requirements.
  25386. TEST_F(WebSocketSSLIntegrationTest,
  25387. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25388. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25389. "/ws-echo");
  25390. client.enable_server_certificate_verification(false);
  25391. client.set_read_timeout(2, 0);
  25392. client.set_write_timeout(2, 0);
  25393. ASSERT_TRUE(client.connect());
  25394. ASSERT_TRUE(client.is_open());
  25395. ASSERT_TRUE(client.send("still open"));
  25396. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25397. // the still-open connection, which must not touch a freed TLS session.
  25398. ASSERT_TRUE(client.connect());
  25399. ASSERT_TRUE(client.is_open());
  25400. ASSERT_TRUE(client.send("after reconnect"));
  25401. std::string msg;
  25402. EXPECT_EQ(ws::Text, client.read(msg));
  25403. EXPECT_EQ("after reconnect", msg);
  25404. client.close();
  25405. }
  25406. #endif
  25407. #ifdef CPPHTTPLIB_SSL_ENABLED
  25408. class WebSocketSSLCATest : public ::testing::Test {
  25409. protected:
  25410. void SetUp() override {
  25411. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25412. SERVER_PRIVATE_KEY_FILE);
  25413. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25414. std::string msg;
  25415. while (ws.read(msg)) {
  25416. ws.send(msg);
  25417. }
  25418. });
  25419. port_ = server_->bind_to_any_port("127.0.0.1");
  25420. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25421. server_->wait_until_ready();
  25422. }
  25423. void TearDown() override {
  25424. server_->stop();
  25425. if (server_thread_.joinable()) { server_thread_.join(); }
  25426. }
  25427. std::string url() const {
  25428. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25429. }
  25430. std::unique_ptr<SSLServer> server_;
  25431. std::thread server_thread_;
  25432. int port_ = 0;
  25433. };
  25434. // A custom CA loaded as PEM verifies the server with full certificate
  25435. // verification enabled
  25436. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25437. ws::WebSocketClient client(url());
  25438. std::string cert;
  25439. read_file(SERVER_CERT2_FILE, cert);
  25440. client.load_ca_cert_store(cert.c_str(), cert.size());
  25441. ASSERT_TRUE(client.connect());
  25442. ASSERT_TRUE(client.send("hello"));
  25443. std::string msg;
  25444. EXPECT_EQ(ws::Text, client.read(msg));
  25445. EXPECT_EQ("hello", msg);
  25446. client.close();
  25447. }
  25448. // A custom CA that does not cover the server must fail verification (the
  25449. // custom CA is exclusive; system certs are not loaded alongside it)
  25450. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25451. ws::WebSocketClient client(url());
  25452. std::string cert;
  25453. read_file(CLIENT_CA_CERT_FILE, cert);
  25454. client.load_ca_cert_store(cert.c_str(), cert.size());
  25455. auto res = client.connect();
  25456. ASSERT_FALSE(res);
  25457. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25458. EXPECT_EQ(-1, res.status());
  25459. EXPECT_NE(0u, res.ssl_backend_error());
  25460. }
  25461. // The same CA as a file path rather than PEM in memory
  25462. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25463. ws::WebSocketClient client(url());
  25464. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25465. ASSERT_TRUE(client.connect());
  25466. ASSERT_TRUE(client.send("hello"));
  25467. std::string msg;
  25468. EXPECT_EQ(ws::Text, client.read(msg));
  25469. EXPECT_EQ("hello", msg);
  25470. client.close();
  25471. }
  25472. // ...and a CA file that does not cover the server still fails, so it is the
  25473. // path above that decides the outcome
  25474. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25475. ws::WebSocketClient client(url());
  25476. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25477. ASSERT_FALSE(client.connect());
  25478. }
  25479. // Regression test: reconnecting with a native custom CA store used to reuse
  25480. // a store handle the previous TLS context had already freed (use-after-free
  25481. // under the OpenSSL backend). The context now lives as long as the client.
  25482. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25483. ws::WebSocketClient client(url());
  25484. std::string cert;
  25485. read_file(SERVER_CERT2_FILE, cert);
  25486. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25487. ASSERT_TRUE(client.connect());
  25488. client.close();
  25489. ASSERT_TRUE(client.connect());
  25490. ASSERT_TRUE(client.send("again"));
  25491. std::string msg;
  25492. EXPECT_EQ(ws::Text, client.read(msg));
  25493. EXPECT_EQ("again", msg);
  25494. client.close();
  25495. }
  25496. // Regression test: a certificate with a trusted chain but no identity match
  25497. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25498. // verification entirely for IP hosts, so this connection succeeded there.
  25499. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25500. // chain verification while the identity check must still fail.
  25501. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25503. ASSERT_TRUE(svr.is_valid());
  25504. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25505. std::string msg;
  25506. while (ws.read(msg)) {
  25507. ws.send(msg);
  25508. }
  25509. });
  25510. auto port = svr.bind_to_any_port("127.0.0.1");
  25511. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25512. auto se = detail::scope_exit([&] {
  25513. svr.stop();
  25514. t.join();
  25515. });
  25516. svr.wait_until_ready();
  25517. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25518. "/echo");
  25519. std::string cert;
  25520. read_file(SERVER_CERT_FILE, cert);
  25521. client.load_ca_cert_store(cert.c_str(), cert.size());
  25522. ASSERT_FALSE(client.connect());
  25523. }
  25524. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25525. // SNI, so nothing binds the host name to the TLS session. These bind the
  25526. // server to "localhost" instead, the only shape that exercises the SNI and
  25527. // hostname-verification path with certificate verification left enabled.
  25528. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25529. protected:
  25530. void Start(const char *cert_file) {
  25531. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25532. SERVER_PRIVATE_KEY_FILE);
  25533. ASSERT_TRUE(server_->is_valid());
  25534. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25535. std::string msg;
  25536. while (ws.read(msg)) {
  25537. ws.send(msg);
  25538. }
  25539. });
  25540. port_ = server_->bind_to_any_port("localhost");
  25541. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25542. server_->wait_until_ready();
  25543. }
  25544. void TearDown() override {
  25545. if (server_) { server_->stop(); }
  25546. if (server_thread_.joinable()) { server_thread_.join(); }
  25547. }
  25548. std::string url() const {
  25549. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25550. }
  25551. std::unique_ptr<SSLServer> server_;
  25552. std::thread server_thread_;
  25553. int port_ = 0;
  25554. };
  25555. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25556. // out and the connection is usable
  25557. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25558. Start(SERVER_CERT2_FILE);
  25559. ws::WebSocketClient client(url());
  25560. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25561. ASSERT_TRUE(client.connect());
  25562. ASSERT_TRUE(client.send("hello"));
  25563. std::string msg;
  25564. EXPECT_EQ(ws::Text, client.read(msg));
  25565. EXPECT_EQ("hello", msg);
  25566. client.close();
  25567. }
  25568. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25569. // while the identity check must still reject "localhost"
  25570. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25571. Start(SERVER_CERT_FILE);
  25572. ws::WebSocketClient client(url());
  25573. client.set_ca_cert_path(SERVER_CERT_FILE);
  25574. auto res = client.connect();
  25575. ASSERT_FALSE(res);
  25576. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25577. EXPECT_EQ(-1, res.status());
  25578. }
  25579. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25580. // disabled: the chain is still checked, only the identity check is skipped
  25581. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25582. Start(SERVER_CERT_FILE);
  25583. ws::WebSocketClient client(url());
  25584. client.set_ca_cert_path(SERVER_CERT_FILE);
  25585. client.enable_server_hostname_verification(false);
  25586. ASSERT_TRUE(client.connect());
  25587. ASSERT_TRUE(client.send("hello"));
  25588. std::string msg;
  25589. EXPECT_EQ(ws::Text, client.read(msg));
  25590. EXPECT_EQ("hello", msg);
  25591. client.close();
  25592. }
  25593. // A CA that did not sign the server certificate fails the chain, even though
  25594. // the name would match
  25595. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25596. Start(SERVER_CERT2_FILE);
  25597. ws::WebSocketClient client(url());
  25598. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25599. ASSERT_FALSE(client.connect());
  25600. }
  25601. // With verification disabled, neither the chain nor the name is checked
  25602. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25603. Start(SERVER_CERT_FILE);
  25604. ws::WebSocketClient client(url());
  25605. client.enable_server_certificate_verification(false);
  25606. ASSERT_TRUE(client.connect());
  25607. ASSERT_TRUE(client.send("hello"));
  25608. std::string msg;
  25609. EXPECT_EQ(ws::Text, client.read(msg));
  25610. EXPECT_EQ("hello", msg);
  25611. client.close();
  25612. }
  25613. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25614. protected:
  25615. void SetUp() override {
  25616. server_ = httplib::detail::make_unique<SSLServer>(
  25617. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25618. ASSERT_TRUE(server_->is_valid());
  25619. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25620. std::string msg;
  25621. while (ws.read(msg)) {
  25622. ws.send(msg);
  25623. }
  25624. });
  25625. port_ = server_->bind_to_any_port("localhost");
  25626. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25627. server_->wait_until_ready();
  25628. }
  25629. void TearDown() override {
  25630. server_->stop();
  25631. if (server_thread_.joinable()) { server_thread_.join(); }
  25632. }
  25633. std::string url() const {
  25634. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25635. }
  25636. void ConnectWithClientCert(const std::string &client_cert_file,
  25637. const std::string &client_private_key_file,
  25638. const char *private_key_password) {
  25639. std::string cert_pem, key_pem;
  25640. read_file(client_cert_file, cert_pem);
  25641. read_file(client_private_key_file, key_pem);
  25642. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25643. key_pem.c_str(), key_pem.size(),
  25644. private_key_password};
  25645. ConnectWithPem(pem);
  25646. }
  25647. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25648. ws::WebSocketClient client(url(), pem);
  25649. ASSERT_TRUE(client.is_valid());
  25650. client.enable_server_certificate_verification(false);
  25651. ASSERT_TRUE(client.connect());
  25652. ASSERT_TRUE(client.send("hello"));
  25653. std::string msg;
  25654. EXPECT_EQ(ws::Text, client.read(msg));
  25655. EXPECT_EQ("hello", msg);
  25656. client.close();
  25657. }
  25658. std::unique_ptr<SSLServer> server_;
  25659. std::thread server_thread_;
  25660. int port_ = 0;
  25661. };
  25662. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25663. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25664. }
  25665. // Control for the tests above: the fixture's server really does require a
  25666. // client certificate, so it is the PEM the constructor installed that decides
  25667. // the outcome.
  25668. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25669. ws::WebSocketClient client(url());
  25670. ASSERT_TRUE(client.is_valid());
  25671. client.enable_server_certificate_verification(false);
  25672. EXPECT_FALSE(client.connect());
  25673. }
  25674. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25675. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25676. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25677. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25678. }
  25679. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25680. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25681. std::string cert_pem, key_pem;
  25682. read_file(CLIENT_CERT_FILE, cert_pem);
  25683. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25684. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25685. std::vector<char> key(key_pem.begin(), key_pem.end());
  25686. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25687. key.size(), nullptr};
  25688. ConnectWithPem(pem);
  25689. }
  25690. #endif
  25691. #if !defined(_WIN32)
  25692. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25693. auto secret_dir = std::string("./symlink_test_secret");
  25694. auto served_dir = std::string("./symlink_test_served");
  25695. auto secret_file = secret_dir + "/secret.txt";
  25696. auto symlink_path = served_dir + "/escape";
  25697. // Setup: create directories and files
  25698. mkdir(secret_dir.c_str(), 0755);
  25699. mkdir(served_dir.c_str(), 0755);
  25700. {
  25701. std::ofstream ofs(secret_file);
  25702. ofs << "SECRET_DATA";
  25703. }
  25704. // Create symlink using absolute path so it resolves correctly
  25705. #ifdef PATH_MAX
  25706. char abs_secret[PATH_MAX];
  25707. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25708. #else
  25709. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25710. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25711. ASSERT_NE(nullptr, abs_secret);
  25712. #endif
  25713. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25714. auto se = detail::scope_exit([&] {
  25715. unlink(symlink_path.c_str());
  25716. unlink(secret_file.c_str());
  25717. rmdir(served_dir.c_str());
  25718. rmdir(secret_dir.c_str());
  25719. });
  25720. Server svr;
  25721. svr.set_mount_point("/", served_dir);
  25722. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25723. auto se2 = detail::scope_exit([&] {
  25724. svr.stop();
  25725. listen_thread.join();
  25726. });
  25727. svr.wait_until_ready();
  25728. Client cli("localhost", PORT);
  25729. // Symlink pointing outside base dir should be blocked
  25730. auto res = cli.Get("/escape/secret.txt");
  25731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25732. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25733. }
  25734. #endif
  25735. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25736. // "GET /smuggled" request), reads the first response, and only then sends the
  25737. // embedded request as the body. Returns how many times /smuggled ran.
  25738. //
  25739. // The body is sent AFTER receiving the first response (as in the original
  25740. // PoC) so that the stream_line_reader cannot buffer it together with the
  25741. // headers of the first request.
  25742. static int count_smuggled_requests(const std::string &outer_head,
  25743. std::string &first_response) {
  25744. Server svr;
  25745. svr.set_mount_point("/", "./www");
  25746. std::atomic<int> smuggled_count(0);
  25747. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25748. smuggled_count++;
  25749. res.set_content("oops", "text/plain");
  25750. });
  25751. svr.Post("/post", [&](const Request &req, Response &res) {
  25752. res.set_content(req.body, "text/plain");
  25753. });
  25754. auto port = svr.bind_to_any_port("localhost");
  25755. thread t = thread([&] { svr.listen_after_bind(); });
  25756. auto se = detail::scope_exit([&] {
  25757. svr.stop();
  25758. t.join();
  25759. });
  25760. svr.wait_until_ready();
  25761. auto error = Error::Success;
  25762. auto sock = detail::create_client_socket(
  25763. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25764. /*connection_timeout_sec=*/2, 0,
  25765. /*read_timeout_sec=*/2, 0,
  25766. /*write_timeout_sec=*/2, 0, std::string(), error);
  25767. EXPECT_NE(INVALID_SOCKET, sock);
  25768. if (sock == INVALID_SOCKET) { return -1; }
  25769. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25770. // The "smuggled" request will be sent as the body of the outer request
  25771. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25772. "Host: localhost\r\n"
  25773. "Connection: close\r\n"
  25774. "\r\n";
  25775. auto head = outer_head;
  25776. auto len = std::to_string(smuggled.size());
  25777. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25778. pos = head.find("{len}", pos + len.size())) {
  25779. head.replace(pos, 5, len);
  25780. }
  25781. // Step 1: Send only the outer request headers (no body yet)
  25782. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25783. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25784. // Step 2: Read the first response
  25785. char buf[4096];
  25786. for (;;) {
  25787. auto n = recv(sock, buf, sizeof(buf), 0);
  25788. if (n <= 0) break;
  25789. first_response.append(buf, static_cast<size_t>(n));
  25790. // Stop once we have a complete response (headers + body)
  25791. auto hdr_end = first_response.find("\r\n\r\n");
  25792. if (hdr_end != std::string::npos) {
  25793. // Check for Content-Length to know when the body is complete
  25794. auto cl_pos = first_response.find("Content-Length:");
  25795. if (cl_pos != std::string::npos) {
  25796. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25797. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25798. auto cl = std::stoul(
  25799. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25800. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25801. } else {
  25802. break; // No Content-Length, assume headers-only response
  25803. }
  25804. }
  25805. }
  25806. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25807. // vulnerable server the keep-alive loop reads this as a second request. The
  25808. // server may already have closed the connection, so the result is ignored.
  25809. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25810. // Half-close so that a server which drained the body sees EOF and closes,
  25811. // instead of the read below waiting for the read timeout.
  25812. #ifdef _WIN32
  25813. ::shutdown(sock, SD_SEND);
  25814. #else
  25815. ::shutdown(sock, SHUT_WR);
  25816. #endif
  25817. // Step 4: Read until the server closes the connection
  25818. for (;;) {
  25819. auto n = recv(sock, buf, sizeof(buf), 0);
  25820. if (n <= 0) break;
  25821. }
  25822. return smuggled_count.load();
  25823. }
  25824. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25825. // A GET request with Content-Length to a static file handler must have its
  25826. // body drained before the keep-alive connection is reused. Otherwise the
  25827. // unread body bytes are interpreted as the next HTTP request.
  25828. std::string first_response;
  25829. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25830. "Host: localhost\r\n"
  25831. "Content-Length: {len}\r\n"
  25832. "\r\n",
  25833. first_response));
  25834. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25835. }
  25836. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25837. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25838. // be answered with 400 and the connection closed. Treating it as "no body"
  25839. // leaves the body to be parsed as the next request.
  25840. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25841. const char *targets[] = {
  25842. "GET /file", // handler that never reads the body
  25843. "GET /not-found", // no handler matches (404)
  25844. "POST /post", // handler that reads the body
  25845. };
  25846. for (auto target : targets) {
  25847. for (auto value : values) {
  25848. std::string first_response;
  25849. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25850. " HTTP/1.1\r\n"
  25851. "Host: localhost\r\n"
  25852. "Content-Length: " +
  25853. value + "\r\n\r\n",
  25854. first_response))
  25855. << target << " with Content-Length: " << value;
  25856. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25857. << target << " with Content-Length: " << value;
  25858. }
  25859. }
  25860. }
  25861. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25862. // A 400 for an unparseable request line leaves the rest of the message
  25863. // unread, so the connection must be closed rather than reused.
  25864. std::string first_response;
  25865. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25866. "Host: localhost\r\n"
  25867. "Content-Length: {len}\r\n"
  25868. "\r\n",
  25869. first_response));
  25870. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25871. }
  25872. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25873. // Same as above for a header block that fails to parse.
  25874. std::string first_response;
  25875. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25876. "Host: localhost\r\n"
  25877. "Bad Header\r\n"
  25878. "Content-Length: {len}\r\n"
  25879. "\r\n",
  25880. first_response));
  25881. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25882. }
  25883. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25884. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25885. // server must not read another request on that connection, even when the
  25886. // request had no body to drain.
  25887. std::string first_response;
  25888. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25889. "Host: localhost\r\n"
  25890. "\r\n",
  25891. first_response));
  25892. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25893. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25894. }
  25895. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25896. // A content reader that stops early leaves the stream inside the body.
  25897. // Draining the whole Content-Length from there, or reading the body again,
  25898. // reads into the next request, and whatever follows is parsed as a request
  25899. // of its own.
  25900. Server svr;
  25901. std::atomic<int> smuggled_count(0);
  25902. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25903. svr.Post("/upload", [](const Request &req, Response &res,
  25904. const ContentReader &content_reader) {
  25905. // Stop at the last chunk, so the whole body has been read however it
  25906. // arrives.
  25907. auto length = req.get_header_value_u64("Content-Length");
  25908. size_t total = 0;
  25909. auto consumed = content_reader([&](const char *, size_t n) {
  25910. total += n;
  25911. return total < length;
  25912. });
  25913. EXPECT_FALSE(consumed);
  25914. if (req.has_param("retry")) {
  25915. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25916. }
  25917. // Replace the 400 the aborted read set, which would close the connection.
  25918. res.set_redirect("/done");
  25919. });
  25920. auto port = svr.bind_to_any_port(HOST);
  25921. thread t = thread([&] { svr.listen_after_bind(); });
  25922. auto se = detail::scope_exit([&] {
  25923. svr.stop();
  25924. t.join();
  25925. });
  25926. svr.wait_until_ready();
  25927. // A front end sees the second request as a POST whose body is the GET. The
  25928. // first body is as long as the POST's headers, so draining it again reads
  25929. // exactly those and leaves the GET to be parsed next.
  25930. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25931. "Host: localhost\r\n"
  25932. "\r\n";
  25933. std::string second_head = "POST /post HTTP/1.1\r\n"
  25934. "Host: localhost\r\n"
  25935. "Content-Length: " +
  25936. std::to_string(inner.size()) +
  25937. "\r\n"
  25938. "\r\n";
  25939. for (auto target : {"/upload", "/upload?retry"}) {
  25940. smuggled_count = 0;
  25941. std::string request = "POST " + std::string(target) +
  25942. " HTTP/1.1\r\n"
  25943. "Host: localhost\r\n"
  25944. "Content-Length: " +
  25945. std::to_string(second_head.size()) +
  25946. "\r\n"
  25947. "\r\n" +
  25948. std::string(second_head.size(), 'A') + second_head +
  25949. inner;
  25950. std::string response;
  25951. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25952. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25953. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25954. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25955. EXPECT_EQ(0, smuggled_count.load()) << target;
  25956. }
  25957. }
  25958. // An error response closes the connection anyway, so the body is left unread
  25959. // with a redirect, such as one to a login page.
  25960. static void serve_redirects(Server &svr,
  25961. const std::function<void(int)> &client) {
  25962. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25963. res.set_redirect("/login");
  25964. return Server::HandlerResponse::Handled;
  25965. });
  25966. auto port = svr.bind_to_any_port(HOST);
  25967. ASSERT_GT(port, 0);
  25968. thread t = thread([&] { svr.listen_after_bind(); });
  25969. auto se = detail::scope_exit([&] {
  25970. svr.stop();
  25971. t.join();
  25972. ASSERT_FALSE(svr.is_running());
  25973. });
  25974. svr.wait_until_ready();
  25975. client(port);
  25976. }
  25977. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25978. Server svr;
  25979. serve_redirects(svr, [](int port) {
  25980. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25981. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25982. std::to_string(body.size()) + "\r\n\r\n" + body +
  25983. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25984. std::string resp;
  25985. ASSERT_TRUE(send_request(1, req, &resp, port));
  25986. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25987. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25988. });
  25989. }
  25990. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25991. Server svr;
  25992. svr.set_read_timeout(0, 200000);
  25993. serve_redirects(svr, [](int port) {
  25994. // A byte every 100 ms keeps each read within the read timeout, but not the
  25995. // body as a whole, so the server closes and the bytes sent after that fail.
  25996. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25997. "Content-Length: 10\r\n\r\n"};
  25998. parts.resize(11, "x");
  25999. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26000. });
  26001. }
  26002. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26003. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26004. // must be rejected with 400 Bad Request.
  26005. Server svr;
  26006. svr.Post("/test", [&](const Request &, Response &res) {
  26007. res.set_content("ok", "text/plain");
  26008. });
  26009. thread t = thread([&] { svr.listen(HOST, PORT); });
  26010. auto se = detail::scope_exit([&] {
  26011. svr.stop();
  26012. t.join();
  26013. ASSERT_FALSE(svr.is_running());
  26014. });
  26015. svr.wait_until_ready();
  26016. // Exact "chunked"
  26017. {
  26018. auto req = "POST /test HTTP/1.1\r\n"
  26019. "Host: localhost\r\n"
  26020. "Content-Length: 5\r\n"
  26021. "Transfer-Encoding: chunked\r\n"
  26022. "Connection: close\r\n"
  26023. "\r\n"
  26024. "hello";
  26025. std::string response;
  26026. ASSERT_TRUE(send_request(1, req, &response));
  26027. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26028. response.substr(0, response.find("\r\n")));
  26029. }
  26030. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26031. {
  26032. auto req = "POST /test HTTP/1.1\r\n"
  26033. "Host: localhost\r\n"
  26034. "Content-Length: 5\r\n"
  26035. "Transfer-Encoding: gzip, chunked\r\n"
  26036. "Connection: close\r\n"
  26037. "\r\n"
  26038. "hello";
  26039. std::string response;
  26040. ASSERT_TRUE(send_request(1, req, &response));
  26041. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26042. response.substr(0, response.find("\r\n")));
  26043. }
  26044. }
  26045. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26046. Server svr;
  26047. svr.Post("/test", [&](const Request &, Response &res) {
  26048. res.set_content("ok", "text/plain");
  26049. });
  26050. thread t = thread([&] { svr.listen(HOST, PORT); });
  26051. auto se = detail::scope_exit([&] {
  26052. svr.stop();
  26053. t.join();
  26054. ASSERT_FALSE(svr.is_running());
  26055. });
  26056. svr.wait_until_ready();
  26057. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26058. // length cannot be determined, so the server must answer 400 and close
  26059. // rather than treat the request as bodyless and leave the body in the
  26060. // socket for the next request to pick up.
  26061. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26062. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26063. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26064. std::string response;
  26065. ASSERT_TRUE(send_request(1, req, &response));
  26066. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26067. response.substr(0, response.find("\r\n")))
  26068. << transfer_encoding;
  26069. }
  26070. // RFC 9110 5.3: the codings may also be split across several
  26071. // Transfer-Encoding lines, which combine in the order they were received.
  26072. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26073. // just like the single-line "chunked, gzip" above.
  26074. {
  26075. auto req = "POST /test HTTP/1.1\r\n"
  26076. "Host: localhost\r\n"
  26077. "Transfer-Encoding: chunked\r\n"
  26078. "Transfer-Encoding: gzip\r\n"
  26079. "\r\n"
  26080. "0\r\n\r\n";
  26081. std::string response;
  26082. ASSERT_TRUE(send_request(1, req, &response));
  26083. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26084. response.substr(0, response.find("\r\n")));
  26085. }
  26086. }
  26087. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26088. Server svr;
  26089. svr.Post("/test", [&](const Request &, Response &res) {
  26090. res.set_content("ok", "text/plain");
  26091. });
  26092. auto port = svr.bind_to_any_port(HOST);
  26093. ASSERT_GT(port, 0);
  26094. thread t = thread([&] { svr.listen_after_bind(); });
  26095. auto se = detail::scope_exit([&] {
  26096. svr.stop();
  26097. t.join();
  26098. ASSERT_FALSE(svr.is_running());
  26099. });
  26100. svr.wait_until_ready();
  26101. for (auto transfer_encoding :
  26102. {"Transfer-Encoding: gzip, chunked\r\n",
  26103. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26104. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26105. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26106. transfer_encoding + "\r\n0\r\n\r\n";
  26107. std::string response;
  26108. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26109. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26110. response.substr(0, response.find("\r\n")))
  26111. << transfer_encoding;
  26112. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26113. << transfer_encoding;
  26114. }
  26115. }
  26116. // Regression for issue #2450: a DELETE without Content-Length on a
  26117. // keep-alive connection must not let the post-response drain consume the
  26118. // next request's bytes.
  26119. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26120. Server svr;
  26121. std::atomic<int> delete_count(0);
  26122. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26123. delete_count++;
  26124. res.status = StatusCode::NoContent_204;
  26125. });
  26126. auto port = svr.bind_to_any_port(HOST);
  26127. thread t = thread([&] { svr.listen_after_bind(); });
  26128. auto se = detail::scope_exit([&] {
  26129. svr.stop();
  26130. t.join();
  26131. });
  26132. svr.wait_until_ready();
  26133. auto error = Error::Success;
  26134. auto sock = detail::create_client_socket(
  26135. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26136. /*connection_timeout_sec=*/2, 0,
  26137. /*read_timeout_sec=*/2, 0,
  26138. /*write_timeout_sec=*/2, 0, std::string(), error);
  26139. ASSERT_NE(INVALID_SOCKET, sock);
  26140. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26141. auto send_request_and_read_response = [&](const std::string &req,
  26142. std::string &out) -> bool {
  26143. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26144. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26145. char buf[4096];
  26146. for (;;) {
  26147. auto n = recv(sock, buf, sizeof(buf), 0);
  26148. if (n <= 0) { return !out.empty(); }
  26149. out.append(buf, static_cast<size_t>(n));
  26150. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26151. }
  26152. };
  26153. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26154. "Host: localhost\r\n"
  26155. "\r\n";
  26156. std::string resp1;
  26157. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26158. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26159. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26160. "Host: localhost\r\n"
  26161. "Connection: close\r\n"
  26162. "\r\n";
  26163. std::string resp2;
  26164. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26165. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26166. EXPECT_EQ(2, delete_count.load());
  26167. }
  26168. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26169. Server svr;
  26170. svr.Post("/ingest", [&](const Request &, Response &res,
  26171. const ContentReader &content_reader) {
  26172. auto consumed = content_reader([](const char *, size_t) { return false; });
  26173. EXPECT_FALSE(consumed);
  26174. res.status = StatusCode::Conflict_409;
  26175. res.set_header("Connection", "close");
  26176. });
  26177. auto port = svr.bind_to_any_port(HOST);
  26178. thread t = thread([&] { svr.listen_after_bind(); });
  26179. auto se = detail::scope_exit([&] {
  26180. svr.stop();
  26181. t.join();
  26182. });
  26183. svr.wait_until_ready();
  26184. auto error = Error::Success;
  26185. auto sock = detail::create_client_socket(
  26186. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26187. /*connection_timeout_sec=*/2, 0,
  26188. /*read_timeout_sec=*/1, 0,
  26189. /*write_timeout_sec=*/2, 0, std::string(), error);
  26190. ASSERT_NE(INVALID_SOCKET, sock);
  26191. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26192. std::string request = "POST /ingest HTTP/1.1\r\n"
  26193. "Host: localhost\r\n"
  26194. "Transfer-Encoding: chunked\r\n"
  26195. "\r\n"
  26196. "4\r\n"
  26197. "data\r\n";
  26198. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26199. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26200. std::string response;
  26201. ssize_t received = 0;
  26202. do {
  26203. char buf[4096];
  26204. received = recv(sock, buf, sizeof(buf), 0);
  26205. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26206. } while (received > 0);
  26207. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26208. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26209. EXPECT_EQ(0, received);
  26210. }
  26211. namespace no_proxy_test {
  26212. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26213. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26214. // calling listen().
  26215. class ScopedServer {
  26216. public:
  26217. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26218. ~ScopedServer() {
  26219. svr_.stop();
  26220. if (th_.joinable()) { th_.join(); }
  26221. }
  26222. Server &svr() { return svr_; }
  26223. int port() const { return port_; }
  26224. void listen() {
  26225. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26226. svr_.wait_until_ready();
  26227. }
  26228. private:
  26229. Server svr_;
  26230. std::thread th_;
  26231. int port_ = 0;
  26232. };
  26233. class ProxyAndTargetServers {
  26234. public:
  26235. ProxyAndTargetServers() {
  26236. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26237. proxy_hits_++;
  26238. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26239. res.set_content("via-proxy", "text/plain");
  26240. });
  26241. target_.Get(".*", [this](const Request &req, Response &res) {
  26242. target_hits_++;
  26243. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26244. res.set_content("direct", "text/plain");
  26245. });
  26246. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26247. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26248. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26249. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26250. proxy_mock_.wait_until_ready();
  26251. target_.wait_until_ready();
  26252. }
  26253. ~ProxyAndTargetServers() {
  26254. proxy_mock_.stop();
  26255. target_.stop();
  26256. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26257. if (target_thread_.joinable()) { target_thread_.join(); }
  26258. }
  26259. Server &proxy_mock() { return proxy_mock_; }
  26260. Server &target() { return target_; }
  26261. int proxy_port() const { return proxy_port_; }
  26262. int target_port() const { return target_port_; }
  26263. int proxy_hits() const { return proxy_hits_.load(); }
  26264. int target_hits() const { return target_hits_.load(); }
  26265. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26266. void reset_counters() {
  26267. proxy_hits_ = 0;
  26268. target_hits_ = 0;
  26269. last_had_proxy_authz_ = false;
  26270. }
  26271. private:
  26272. Server proxy_mock_;
  26273. Server target_;
  26274. std::thread proxy_thread_;
  26275. std::thread target_thread_;
  26276. int proxy_port_ = 0;
  26277. int target_port_ = 0;
  26278. std::atomic<int> proxy_hits_{0};
  26279. std::atomic<int> target_hits_{0};
  26280. std::atomic<bool> last_had_proxy_authz_{false};
  26281. };
  26282. inline std::unique_ptr<Client> make_client(const std::string &host,
  26283. ProxyAndTargetServers &s) {
  26284. auto cli = detail::make_unique<Client>(host, s.target_port());
  26285. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26286. cli->set_proxy("127.0.0.1", s.proxy_port());
  26287. return cli;
  26288. }
  26289. } // namespace no_proxy_test
  26290. using no_proxy_test::make_client;
  26291. using no_proxy_test::ProxyAndTargetServers;
  26292. // A stream request carries the credentials a buffered request does
  26293. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26294. no_proxy_test::ScopedServer origin;
  26295. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26296. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26297. });
  26298. origin.listen();
  26299. Client cli("127.0.0.1", origin.port());
  26300. cli.set_basic_auth("user", "pass");
  26301. auto handle = cli.open_stream("GET", "/x");
  26302. ASSERT_TRUE(handle.is_valid());
  26303. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26304. Client bearer("127.0.0.1", origin.port());
  26305. bearer.set_bearer_token_auth("tok");
  26306. auto handle2 = bearer.open_stream("GET", "/x");
  26307. ASSERT_TRUE(handle2.is_valid());
  26308. EXPECT_EQ("Bearer tok", read_all(handle2));
  26309. }
  26310. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26311. // takes its own credentials, as for a buffered request
  26312. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26313. std::string target, authz, proxy_authz;
  26314. no_proxy_test::ScopedServer proxy;
  26315. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26316. target = req.target;
  26317. authz = req.get_header_value("Authorization");
  26318. proxy_authz = req.get_header_value("Proxy-Authorization");
  26319. res.set_content("ok", "text/plain");
  26320. });
  26321. proxy.listen();
  26322. Client cli("origin.example", 8080);
  26323. cli.set_proxy("127.0.0.1", proxy.port());
  26324. cli.set_proxy_basic_auth("puser", "ppass");
  26325. cli.set_basic_auth("user", "pass");
  26326. auto handle = cli.open_stream("GET", "/x");
  26327. ASSERT_TRUE(handle.is_valid());
  26328. EXPECT_EQ("ok", read_all(handle));
  26329. EXPECT_EQ("http://origin.example:8080/x", target);
  26330. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26331. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26332. }
  26333. // In absolute-form the path follows the authority, so a path that does not
  26334. // begin with '/' would make the proxy connect to another host
  26335. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26336. std::vector<std::string> targets;
  26337. no_proxy_test::ScopedServer proxy;
  26338. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26339. targets.push_back(req.target);
  26340. res.set_content("ok", "text/plain");
  26341. });
  26342. proxy.listen();
  26343. Client cli("origin.example", 8080);
  26344. cli.set_proxy("127.0.0.1", proxy.port());
  26345. cli.set_basic_auth("user", "pass");
  26346. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26347. auto res = cli.Get(path);
  26348. EXPECT_FALSE(res) << path;
  26349. auto handle = cli.open_stream("GET", path);
  26350. EXPECT_FALSE(handle.is_valid()) << path;
  26351. }
  26352. EXPECT_TRUE(targets.empty());
  26353. auto res = cli.Get("/x");
  26354. ASSERT_TRUE(res);
  26355. ASSERT_EQ(1u, targets.size());
  26356. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26357. }
  26358. TEST(NoProxyTest, ExactHostnameBypasses) {
  26359. ProxyAndTargetServers s;
  26360. auto cli = make_client("example.com", s);
  26361. cli->set_no_proxy({"example.com"});
  26362. auto res = cli->Get("/");
  26363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26364. EXPECT_EQ(0, s.proxy_hits());
  26365. EXPECT_EQ(1, s.target_hits());
  26366. }
  26367. TEST(NoProxyTest, SubdomainBypasses) {
  26368. ProxyAndTargetServers s;
  26369. auto cli = make_client("foo.example.com", s);
  26370. cli->set_no_proxy({"example.com"});
  26371. auto res = cli->Get("/");
  26372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26373. EXPECT_EQ(0, s.proxy_hits());
  26374. EXPECT_EQ(1, s.target_hits());
  26375. }
  26376. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26377. // Regression guard: "evilexample.com" must not be considered a subdomain
  26378. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26379. // check would let traffic bypass the proxy and leak credentials direct
  26380. // to the attacker host.
  26381. ProxyAndTargetServers s;
  26382. auto cli = make_client("evilexample.com", s);
  26383. cli->set_no_proxy({"example.com"});
  26384. auto res = cli->Get("/");
  26385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26386. EXPECT_GE(s.proxy_hits(), 1);
  26387. EXPECT_EQ(0, s.target_hits());
  26388. }
  26389. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26390. ProxyAndTargetServers s;
  26391. auto cli = make_client("example.com.evil.com", s);
  26392. cli->set_no_proxy({"example.com"});
  26393. auto res = cli->Get("/");
  26394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26395. EXPECT_GE(s.proxy_hits(), 1);
  26396. EXPECT_EQ(0, s.target_hits());
  26397. }
  26398. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26399. ProxyAndTargetServers s;
  26400. auto cli = make_client("example.com", s);
  26401. cli->set_no_proxy({".example.com"});
  26402. auto res = cli->Get("/");
  26403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26404. EXPECT_EQ(0, s.proxy_hits());
  26405. EXPECT_EQ(1, s.target_hits());
  26406. }
  26407. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26408. ProxyAndTargetServers s;
  26409. auto cli = make_client("Example.COM", s);
  26410. cli->set_no_proxy({"EXAMPLE.com"});
  26411. auto res = cli->Get("/");
  26412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26413. EXPECT_EQ(0, s.proxy_hits());
  26414. EXPECT_EQ(1, s.target_hits());
  26415. }
  26416. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26417. ProxyAndTargetServers s;
  26418. auto cli = make_client("example.com.", s);
  26419. cli->set_no_proxy({"example.com"});
  26420. auto res = cli->Get("/");
  26421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26422. EXPECT_EQ(0, s.proxy_hits());
  26423. EXPECT_EQ(1, s.target_hits());
  26424. }
  26425. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26426. // Trailing dots must be normalized on BOTH sides — host and entry.
  26427. // An implementation that only strips the host-side trailing dot would
  26428. // fail to match host "example.com" against entry "example.com." because
  26429. // a literal substring search would compare 11 chars against 12.
  26430. ProxyAndTargetServers s;
  26431. auto cli = make_client("example.com", s);
  26432. cli->set_no_proxy({"example.com."});
  26433. auto res = cli->Get("/");
  26434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26435. EXPECT_EQ(0, s.proxy_hits());
  26436. EXPECT_EQ(1, s.target_hits());
  26437. }
  26438. TEST(NoProxyTest, WildcardBypassesEverything) {
  26439. ProxyAndTargetServers s;
  26440. auto cli = make_client("anything.invalid.test", s);
  26441. cli->set_no_proxy({"*"});
  26442. auto res = cli->Get("/");
  26443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26444. EXPECT_EQ(0, s.proxy_hits());
  26445. EXPECT_EQ(1, s.target_hits());
  26446. }
  26447. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26448. ProxyAndTargetServers s;
  26449. Client cli("127.0.0.1", s.target_port());
  26450. cli.set_proxy("127.0.0.1", s.proxy_port());
  26451. cli.set_no_proxy({"127.0.0.1"});
  26452. auto res = cli.Get("/");
  26453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26454. EXPECT_EQ(0, s.proxy_hits());
  26455. EXPECT_EQ(1, s.target_hits());
  26456. }
  26457. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26458. ProxyAndTargetServers s;
  26459. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26460. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26461. cli.set_proxy("127.0.0.1", s.proxy_port());
  26462. cli.set_no_proxy({"::1"});
  26463. auto res = cli.Get("/");
  26464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26465. EXPECT_EQ(0, s.proxy_hits());
  26466. EXPECT_EQ(1, s.target_hits());
  26467. }
  26468. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26469. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26470. // must still be recognized as IPv6 for CIDR matching. Implementations
  26471. // that detect IPv6 only when the host begins with '[' would parse the
  26472. // host as a hostname and miss the match.
  26473. ProxyAndTargetServers s;
  26474. Client cli("fe80::1", s.target_port());
  26475. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26476. cli.set_proxy("127.0.0.1", s.proxy_port());
  26477. cli.set_no_proxy({"fe80::/10"});
  26478. auto res = cli.Get("/");
  26479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26480. EXPECT_EQ(0, s.proxy_hits());
  26481. EXPECT_EQ(1, s.target_hits());
  26482. }
  26483. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26484. ProxyAndTargetServers s;
  26485. Client cli("::1", s.target_port());
  26486. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26487. cli.set_proxy("127.0.0.1", s.proxy_port());
  26488. cli.set_no_proxy({"[::1]"});
  26489. auto res = cli.Get("/");
  26490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26491. EXPECT_EQ(0, s.proxy_hits());
  26492. EXPECT_EQ(1, s.target_hits());
  26493. }
  26494. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26495. ProxyAndTargetServers s;
  26496. Client cli("fe80::1", s.target_port());
  26497. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26498. cli.set_proxy("127.0.0.1", s.proxy_port());
  26499. cli.set_no_proxy({"[fe80::]/10"});
  26500. auto res = cli.Get("/");
  26501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26502. EXPECT_EQ(0, s.proxy_hits());
  26503. EXPECT_EQ(1, s.target_hits());
  26504. }
  26505. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26506. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26507. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26508. // tricks via address-family conversion.
  26509. ProxyAndTargetServers s;
  26510. Client cli("::ffff:127.0.0.1", s.target_port());
  26511. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26512. cli.set_proxy("127.0.0.1", s.proxy_port());
  26513. cli.set_no_proxy({"127.0.0.1"});
  26514. auto res = cli.Get("/");
  26515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26516. EXPECT_GE(s.proxy_hits(), 1);
  26517. EXPECT_EQ(0, s.target_hits());
  26518. }
  26519. TEST(NoProxyTest, IPv4CidrMatch) {
  26520. ProxyAndTargetServers s;
  26521. Client cli("127.0.0.1", s.target_port());
  26522. cli.set_proxy("127.0.0.1", s.proxy_port());
  26523. cli.set_no_proxy({"127.0.0.0/8"});
  26524. auto res = cli.Get("/");
  26525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26526. EXPECT_EQ(0, s.proxy_hits());
  26527. EXPECT_EQ(1, s.target_hits());
  26528. }
  26529. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26530. ProxyAndTargetServers s;
  26531. Client cli("127.0.0.1", s.target_port());
  26532. cli.set_proxy("127.0.0.1", s.proxy_port());
  26533. cli.set_no_proxy({"10.0.0.0/8"});
  26534. auto res = cli.Get("/");
  26535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26536. EXPECT_GE(s.proxy_hits(), 1);
  26537. EXPECT_EQ(0, s.target_hits());
  26538. }
  26539. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26540. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26541. // IPv4 target matches.
  26542. ProxyAndTargetServers s;
  26543. Client cli("127.0.0.1", s.target_port());
  26544. cli.set_proxy("127.0.0.1", s.proxy_port());
  26545. cli.set_no_proxy({"0.0.0.0/0"});
  26546. auto res = cli.Get("/");
  26547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26548. EXPECT_EQ(0, s.proxy_hits());
  26549. EXPECT_EQ(1, s.target_hits());
  26550. }
  26551. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26552. ProxyAndTargetServers s;
  26553. Client cli("127.0.0.1", s.target_port());
  26554. cli.set_proxy("127.0.0.1", s.proxy_port());
  26555. cli.set_no_proxy({"127.0.0.1"});
  26556. auto res = cli.Get("/");
  26557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26558. EXPECT_EQ(0, s.proxy_hits());
  26559. EXPECT_EQ(1, s.target_hits());
  26560. }
  26561. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26562. ProxyAndTargetServers s;
  26563. Client cli("127.0.0.1", s.target_port());
  26564. cli.set_proxy("127.0.0.1", s.proxy_port());
  26565. cli.set_no_proxy({"127.0.0.0/33"});
  26566. auto res = cli.Get("/");
  26567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26568. EXPECT_GE(s.proxy_hits(), 1);
  26569. EXPECT_EQ(0, s.target_hits());
  26570. }
  26571. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26572. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26573. ProxyAndTargetServers s;
  26574. Client cli("127.0.0.1", s.target_port());
  26575. cli.set_proxy("127.0.0.1", s.proxy_port());
  26576. cli.set_no_proxy({"127.0.0.1/"});
  26577. auto res = cli.Get("/");
  26578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26579. EXPECT_GE(s.proxy_hits(), 1);
  26580. EXPECT_EQ(0, s.target_hits());
  26581. }
  26582. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26583. ProxyAndTargetServers s;
  26584. auto cli = make_client("internal.corp", s);
  26585. cli->set_proxy_basic_auth("u", "p");
  26586. cli->set_no_proxy({"internal.corp"});
  26587. auto res = cli->Get("/");
  26588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26589. EXPECT_EQ(1, s.target_hits());
  26590. EXPECT_EQ(0, s.proxy_hits());
  26591. EXPECT_FALSE(s.last_had_proxy_authz())
  26592. << "Proxy-Authorization must not be sent direct to the target";
  26593. }
  26594. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26595. ProxyAndTargetServers s;
  26596. auto cli = make_client("public.example", s);
  26597. cli->set_proxy_basic_auth("u", "p");
  26598. cli->set_no_proxy({"internal.corp"}); // does not match
  26599. auto res = cli->Get("/");
  26600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26601. EXPECT_GE(s.proxy_hits(), 1);
  26602. EXPECT_TRUE(s.last_had_proxy_authz());
  26603. }
  26604. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26605. std::atomic<int> hits{0};
  26606. std::atomic<int> hits_with_authz{0};
  26607. no_proxy_test::ScopedServer proxy_mock;
  26608. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26609. hits++;
  26610. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26611. if (req.target.find("/redir") != std::string::npos) {
  26612. res.set_redirect("http://other.example/landed");
  26613. } else {
  26614. res.set_content("via-proxy", "text/plain");
  26615. }
  26616. });
  26617. proxy_mock.listen();
  26618. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26619. hits = 0;
  26620. hits_with_authz = 0;
  26621. Client cli("public.example", 80);
  26622. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26623. cli.set_proxy_basic_auth(c.first, c.second);
  26624. cli.set_follow_location(true);
  26625. // The redirect to another host goes through the proxy as well
  26626. auto res = cli.Get("/redir");
  26627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26628. EXPECT_EQ(2, hits.load());
  26629. EXPECT_EQ(2, hits_with_authz.load());
  26630. }
  26631. }
  26632. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26633. ProxyAndTargetServers s;
  26634. auto cli = make_client("anything.test", s);
  26635. auto res = cli->Get("/");
  26636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26637. EXPECT_GE(s.proxy_hits(), 1);
  26638. EXPECT_EQ(0, s.target_hits());
  26639. }
  26640. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26641. ProxyAndTargetServers s;
  26642. auto cli = make_client("example.com", s);
  26643. cli->set_no_proxy({"example.com:8080"});
  26644. auto res = cli->Get("/");
  26645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26646. EXPECT_GE(s.proxy_hits(), 1);
  26647. EXPECT_EQ(0, s.target_hits());
  26648. }
  26649. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26650. ProxyAndTargetServers s;
  26651. auto cli = make_client("anything.test", s);
  26652. cli->set_no_proxy({"", " ", "\t"});
  26653. auto res = cli->Get("/");
  26654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26655. EXPECT_GE(s.proxy_hits(), 1);
  26656. EXPECT_EQ(0, s.target_hits());
  26657. }
  26658. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26659. // An entry with leading/trailing whitespace must still match — env-style
  26660. // values are commonly pasted with stray spaces and an implementation
  26661. // that feeds the raw token directly to inet_pton would fail to match
  26662. // valid CIDRs because of the spaces.
  26663. ProxyAndTargetServers s;
  26664. Client cli("127.0.0.1", s.target_port());
  26665. cli.set_proxy("127.0.0.1", s.proxy_port());
  26666. cli.set_no_proxy({" 127.0.0.0/8 "});
  26667. auto res = cli.Get("/");
  26668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26669. EXPECT_EQ(0, s.proxy_hits());
  26670. EXPECT_EQ(1, s.target_hits());
  26671. }
  26672. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26673. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26674. // go direct and must NOT carry Proxy-Authorization.
  26675. std::atomic<int> proxy_hits{0};
  26676. std::atomic<int> target_hits{0};
  26677. std::atomic<bool> target_saw_authz{false};
  26678. no_proxy_test::ScopedServer proxy_mock, target;
  26679. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26680. proxy_hits++;
  26681. res.status = 302;
  26682. res.set_header("Location", "http://127.0.0.1:" +
  26683. std::to_string(target.port()) + "/landed");
  26684. });
  26685. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26686. target_hits++;
  26687. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26688. res.set_content("direct", "text/plain");
  26689. });
  26690. proxy_mock.listen();
  26691. target.listen();
  26692. Client cli("public.example", target.port());
  26693. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26694. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26695. cli.set_proxy_basic_auth("u", "p");
  26696. cli.set_no_proxy({"127.0.0.1"});
  26697. cli.set_follow_location(true);
  26698. auto res = cli.Get("/redir");
  26699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26700. EXPECT_GE(proxy_hits.load(), 1);
  26701. EXPECT_GE(target_hits.load(), 1);
  26702. EXPECT_FALSE(target_saw_authz.load());
  26703. }
  26704. #ifdef CPPHTTPLIB_SSL_ENABLED
  26705. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26706. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26707. // proxy creds would be sent to the (possibly hostile) origin.
  26708. std::atomic<int> target_hits{0};
  26709. std::atomic<bool> target_saw_proxy_authz{false};
  26710. no_proxy_test::ScopedServer target;
  26711. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26712. target_hits++;
  26713. if (req.has_header("Proxy-Authorization")) {
  26714. target_saw_proxy_authz = true;
  26715. }
  26716. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26717. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26718. "nonce=\"abc\", algorithm=MD5");
  26719. });
  26720. target.listen();
  26721. // The proxy address is set to the target's port: the bypass MUST kick in;
  26722. // if it doesn't, the test still routes "via proxy" to the same server and
  26723. // the Proxy-Authorization assertion below catches the leak.
  26724. Client cli("evil.example", target.port());
  26725. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26726. cli.set_proxy("127.0.0.1", target.port());
  26727. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26728. cli.set_no_proxy({"evil.example"});
  26729. auto res = cli.Get("/x");
  26730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26731. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26732. EXPECT_EQ(1, target_hits.load());
  26733. EXPECT_FALSE(target_saw_proxy_authz.load());
  26734. }
  26735. #endif
  26736. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26737. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26738. std::atomic<int> proxy_hits{0};
  26739. std::atomic<int> bypass_hits{0};
  26740. std::atomic<bool> proxy_saw_c_url{false};
  26741. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26742. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26743. proxy_hits++;
  26744. if (req.path.find("/start") != std::string::npos) {
  26745. res.status = 302;
  26746. res.set_header("Location", "http://127.0.0.1:" +
  26747. std::to_string(bypass_server.port()) +
  26748. "/middle");
  26749. return;
  26750. }
  26751. if (req.path.find("/end") != std::string::npos) {
  26752. proxy_saw_c_url = true;
  26753. res.set_content("c-via-proxy", "text/plain");
  26754. return;
  26755. }
  26756. res.set_content("unexpected", "text/plain");
  26757. });
  26758. // public.example's "advertised" port is arbitrary (the request never lands
  26759. // there — it goes through the proxy), but use a dynamic value to stay
  26760. // friendly with sharded parallel runs.
  26761. int public_port = bypass_server.port();
  26762. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26763. bypass_hits++;
  26764. res.status = 302;
  26765. res.set_header("Location", "http://public.example:" +
  26766. std::to_string(public_port) + "/end");
  26767. });
  26768. proxy_mock.listen();
  26769. bypass_server.listen();
  26770. Client cli("public.example", public_port);
  26771. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26772. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26773. cli.set_no_proxy({"127.0.0.1"});
  26774. cli.set_follow_location(true);
  26775. auto res = cli.Get("/start");
  26776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26777. EXPECT_EQ(StatusCode::OK_200, res->status);
  26778. EXPECT_EQ("c-via-proxy", res->body);
  26779. EXPECT_GE(proxy_hits.load(), 2);
  26780. EXPECT_GE(bypass_hits.load(), 1);
  26781. EXPECT_TRUE(proxy_saw_c_url.load());
  26782. }
  26783. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26784. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26785. // request reconnects to the correct endpoint.
  26786. std::atomic<int> proxy_hits{0};
  26787. std::atomic<int> target_hits{0};
  26788. no_proxy_test::ScopedServer proxy_mock, target;
  26789. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26790. proxy_hits++;
  26791. res.set_content("via-proxy", "text/plain");
  26792. });
  26793. target.svr().Get(".*", [&](const Request &, Response &res) {
  26794. target_hits++;
  26795. res.set_content("direct", "text/plain");
  26796. });
  26797. proxy_mock.listen();
  26798. target.listen();
  26799. Client cli("public.example", target.port());
  26800. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26801. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26802. cli.set_keep_alive(true);
  26803. auto res1 = cli.Get("/a");
  26804. ASSERT_TRUE(res1);
  26805. EXPECT_EQ("via-proxy", res1->body);
  26806. EXPECT_EQ(1, proxy_hits.load());
  26807. EXPECT_EQ(0, target_hits.load());
  26808. cli.set_no_proxy({"public.example"});
  26809. auto res2 = cli.Get("/b");
  26810. ASSERT_TRUE(res2);
  26811. EXPECT_EQ("direct", res2->body);
  26812. EXPECT_EQ(1, proxy_hits.load());
  26813. EXPECT_EQ(1, target_hits.load());
  26814. }
  26815. // Forward declarations (see the base64_encode note).
  26816. namespace httplib {
  26817. namespace detail {
  26818. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26819. int shutdown_socket(socket_t sock) noexcept;
  26820. } // namespace detail
  26821. } // namespace httplib
  26822. namespace proxy_tunnel_test {
  26823. const char *const kTunnelEstablished =
  26824. "HTTP/1.1 200 Connection established\r\n\r\n";
  26825. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26826. using ConnectReply = std::function<std::string(const std::string &head)>;
  26827. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26828. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26829. class ScopedConnectProxy {
  26830. public:
  26831. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26832. : forward_port_(forward_port), reply_(std::move(reply)) {
  26833. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26834. if (listen_sock_ == INVALID_SOCKET) { return; }
  26835. auto a = loopback(0);
  26836. auto addr = reinterpret_cast<sockaddr *>(&a);
  26837. socklen_t alen = sizeof(a);
  26838. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26839. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26840. ::listen(listen_sock_, 4) != 0) {
  26841. return;
  26842. }
  26843. port_ = ntohs(a.sin_port);
  26844. th_ = std::thread([this] { run(); });
  26845. }
  26846. ~ScopedConnectProxy() {
  26847. if (th_.joinable()) {
  26848. stop_ = true;
  26849. auto wake = connect_to(port_);
  26850. th_.join();
  26851. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26852. }
  26853. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26854. }
  26855. int port() const { return port_; }
  26856. int connect_hits() const { return connect_hits_.load(); }
  26857. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26858. std::string connect_request() const {
  26859. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26860. return connect_request_;
  26861. }
  26862. private:
  26863. static sockaddr_in loopback(int port) {
  26864. sockaddr_in a{};
  26865. a.sin_family = AF_INET;
  26866. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26867. a.sin_port = htons(static_cast<unsigned short>(port));
  26868. return a;
  26869. }
  26870. static socket_t connect_to(int port) {
  26871. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26872. if (sock == INVALID_SOCKET) { return sock; }
  26873. auto a = loopback(port);
  26874. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26875. detail::close_socket(sock);
  26876. return INVALID_SOCKET;
  26877. }
  26878. return sock;
  26879. }
  26880. static bool send_all(socket_t sock, const char *data, size_t size) {
  26881. while (size > 0) {
  26882. auto n = detail::send_socket(sock, data, size, 0);
  26883. if (n <= 0) { return false; }
  26884. data += n;
  26885. size -= static_cast<size_t>(n);
  26886. }
  26887. return true;
  26888. }
  26889. void run() {
  26890. for (;;) {
  26891. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26892. if (stop_) {
  26893. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26894. return;
  26895. }
  26896. if (client == INVALID_SOCKET) { continue; }
  26897. serve(client);
  26898. detail::close_socket(client);
  26899. }
  26900. }
  26901. void serve(socket_t client) {
  26902. std::string head;
  26903. char buf[2048];
  26904. while (head.find("\r\n\r\n") == std::string::npos) {
  26905. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26906. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26907. if (n <= 0) { return; }
  26908. head.append(buf, static_cast<size_t>(n));
  26909. }
  26910. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26911. connect_hits_++;
  26912. {
  26913. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26914. connect_request_ = head;
  26915. }
  26916. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26917. if (!send_all(client, res.data(), res.size()) ||
  26918. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26919. return;
  26920. }
  26921. auto origin = connect_to(forward_port_);
  26922. if (origin == INVALID_SOCKET) { return; }
  26923. // When either side stops, shut both down so the other pump returns too.
  26924. auto pump = [&](socket_t from, socket_t to) {
  26925. char b[8192];
  26926. for (;;) {
  26927. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26928. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26929. }
  26930. detail::shutdown_socket(client);
  26931. detail::shutdown_socket(origin);
  26932. };
  26933. std::thread up([&] { pump(client, origin); });
  26934. pump(origin, client);
  26935. up.join();
  26936. detail::close_socket(origin);
  26937. }
  26938. int forward_port_;
  26939. ConnectReply reply_;
  26940. socket_t listen_sock_ = INVALID_SOCKET;
  26941. int port_ = 0;
  26942. std::thread th_;
  26943. std::atomic<bool> stop_{false};
  26944. std::atomic<int> connect_hits_{0};
  26945. mutable std::mutex connect_request_mutex_;
  26946. std::string connect_request_;
  26947. };
  26948. } // namespace proxy_tunnel_test
  26949. #ifdef CPPHTTPLIB_SSL_ENABLED
  26950. namespace proxy_tunnel_test {
  26951. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26952. class ScopedSSLServer {
  26953. public:
  26954. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26955. port_ = svr_.bind_to_any_port("127.0.0.1");
  26956. }
  26957. ~ScopedSSLServer() {
  26958. svr_.stop();
  26959. if (th_.joinable()) { th_.join(); }
  26960. }
  26961. SSLServer &svr() { return svr_; }
  26962. int port() const { return port_; }
  26963. void listen() {
  26964. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26965. svr_.wait_until_ready();
  26966. }
  26967. private:
  26968. SSLServer svr_;
  26969. std::thread th_;
  26970. int port_ = 0;
  26971. };
  26972. // Sends one request through the CONNECT proxy to the TLS origin with a
  26973. // credential configured for each hop, and checks that each credential reaches
  26974. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26975. // origin's (every header in origin_headers) on the tunnelled request.
  26976. void CredentialsStayWithTheirHop(
  26977. const std::function<void(SSLClient &)> &set_credentials,
  26978. const std::string &scheme,
  26979. const std::vector<std::string> &origin_headers = {"Authorization"},
  26980. bool stream = false) {
  26981. std::atomic<int> origin_hits{0};
  26982. std::atomic<bool> origin_saw_proxy_authz{false};
  26983. std::atomic<bool> origin_saw_headers{false};
  26984. ScopedSSLServer origin;
  26985. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26986. origin_hits++;
  26987. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26988. origin_saw_headers =
  26989. std::all_of(origin_headers.begin(), origin_headers.end(),
  26990. [&](const std::string &h) { return req.has_header(h); });
  26991. res.set_content("ok", "text/plain");
  26992. });
  26993. origin.listen();
  26994. ScopedConnectProxy proxy(origin.port());
  26995. ASSERT_NE(0, proxy.port());
  26996. // Pinned to 127.0.0.1 for the same reason as the test below.
  26997. SSLClient cli("127.0.0.1", origin.port());
  26998. cli.enable_server_certificate_verification(false);
  26999. cli.set_proxy("127.0.0.1", proxy.port());
  27000. set_credentials(cli);
  27001. if (stream) {
  27002. auto handle = cli.open_stream("GET", "/x");
  27003. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27004. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27005. } else {
  27006. auto res = cli.Get("/x");
  27007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27008. EXPECT_EQ(StatusCode::OK_200, res->status);
  27009. }
  27010. EXPECT_EQ(1, origin_hits.load());
  27011. EXPECT_EQ(1, proxy.connect_hits());
  27012. EXPECT_TRUE(origin_saw_headers.load());
  27013. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27014. << "Proxy-Authorization must not be sent inside the tunnel";
  27015. auto connect_req = proxy.connect_request();
  27016. EXPECT_NE(std::string::npos,
  27017. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27018. for (const auto &h : origin_headers) {
  27019. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27020. << h << " must not be sent to the proxy on CONNECT";
  27021. }
  27022. }
  27023. } // namespace proxy_tunnel_test
  27024. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27025. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27026. [](SSLClient &cli) {
  27027. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27028. cli.set_basic_auth("origin-user", "origin-pass");
  27029. },
  27030. "Basic");
  27031. }
  27032. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27033. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27034. [](SSLClient &cli) {
  27035. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27036. cli.set_basic_auth("origin-user", "origin-pass");
  27037. },
  27038. "Basic", {"Authorization"}, true);
  27039. }
  27040. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27041. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27042. [](SSLClient &cli) {
  27043. cli.set_proxy_bearer_token_auth("proxy-token");
  27044. cli.set_bearer_token_auth("origin-token");
  27045. },
  27046. "Bearer");
  27047. }
  27048. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27049. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27050. [](SSLClient &cli) {
  27051. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27052. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27053. {"Cookie", "sid=origin-session"},
  27054. {"X-Api-Key", "origin-key"}});
  27055. },
  27056. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27057. }
  27058. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27059. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27060. // retry; otherwise proxy creds would be sent to the origin.
  27061. std::atomic<int> origin_hits{0};
  27062. std::atomic<bool> origin_saw_proxy_authz{false};
  27063. proxy_tunnel_test::ScopedSSLServer origin;
  27064. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27065. origin_hits++;
  27066. if (req.has_header("Proxy-Authorization")) {
  27067. origin_saw_proxy_authz = true;
  27068. }
  27069. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27070. res.set_header("Proxy-Authenticate",
  27071. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27072. "algorithm=MD5");
  27073. });
  27074. origin.listen();
  27075. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27076. ASSERT_NE(0, proxy.port());
  27077. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27078. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27079. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27080. // and answer with its own status, making this test flaky.
  27081. SSLClient cli("127.0.0.1", origin.port());
  27082. cli.enable_server_certificate_verification(false);
  27083. cli.set_proxy("127.0.0.1", proxy.port());
  27084. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27085. auto res = cli.Get("/x");
  27086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27087. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27088. EXPECT_EQ(1, origin_hits.load());
  27089. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27090. EXPECT_EQ(1, proxy.connect_hits());
  27091. }
  27092. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27093. std::string origin_sni;
  27094. std::string origin_host;
  27095. proxy_tunnel_test::ScopedSSLServer origin;
  27096. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27097. origin_sni = req.sni();
  27098. origin_host = req.get_header_value("Host");
  27099. res.set_content("ok", "text/plain");
  27100. });
  27101. origin.listen();
  27102. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27103. ASSERT_NE(0, proxy.port());
  27104. SSLClient cli("origin.example", origin.port());
  27105. cli.enable_server_certificate_verification(false);
  27106. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27107. cli.set_proxy("127.0.0.1", proxy.port());
  27108. auto res = cli.Get("/x");
  27109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27110. EXPECT_EQ(StatusCode::OK_200, res->status);
  27111. auto port = std::to_string(origin.port());
  27112. auto target = "127.0.0.1:" + port;
  27113. auto connect_req = proxy.connect_request();
  27114. EXPECT_EQ(1, proxy.connect_hits());
  27115. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27116. EXPECT_NE(std::string::npos,
  27117. connect_req.find("\r\nHost: " + target + "\r\n"));
  27118. EXPECT_EQ("origin.example", origin_sni);
  27119. EXPECT_EQ("origin.example:" + port, origin_host);
  27120. }
  27121. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27122. proxy_tunnel_test::ScopedSSLServer origin;
  27123. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27124. res.set_content("ok", "text/plain");
  27125. });
  27126. origin.listen();
  27127. proxy_tunnel_test::ScopedConnectProxy proxy(
  27128. origin.port(), [](const std::string &head) -> std::string {
  27129. if (head.find(
  27130. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27131. std::string::npos) {
  27132. return proxy_tunnel_test::kTunnelEstablished;
  27133. }
  27134. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27135. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27136. "nonce=\"abc\", algorithm=MD5\r\n"
  27137. "Content-Length: 0\r\n\r\n";
  27138. });
  27139. ASSERT_NE(0, proxy.port());
  27140. SSLClient cli("origin.example", origin.port());
  27141. cli.enable_server_certificate_verification(false);
  27142. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27143. cli.set_proxy("127.0.0.1", proxy.port());
  27144. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27145. auto res = cli.Get("/x");
  27146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27147. EXPECT_EQ(StatusCode::OK_200, res->status);
  27148. // The retried CONNECT is the one the proxy saw last.
  27149. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27150. auto connect_req = proxy.connect_request();
  27151. EXPECT_EQ(2, proxy.connect_hits());
  27152. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27153. EXPECT_NE(std::string::npos,
  27154. connect_req.find("\r\nHost: " + target + "\r\n"));
  27155. }
  27156. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27157. proxy_tunnel_test::ScopedSSLServer origin;
  27158. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27159. res.set_content("ok", "text/plain");
  27160. });
  27161. origin.listen();
  27162. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27163. ASSERT_NE(0, proxy.port());
  27164. SSLClient cli("origin.example", origin.port());
  27165. cli.enable_server_certificate_verification(false);
  27166. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27167. cli.set_proxy("127.0.0.1", proxy.port());
  27168. auto res = cli.Get("/x");
  27169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27170. EXPECT_EQ(StatusCode::OK_200, res->status);
  27171. auto target = "origin.example:" + std::to_string(origin.port());
  27172. auto connect_req = proxy.connect_request();
  27173. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27174. EXPECT_NE(std::string::npos,
  27175. connect_req.find("\r\nHost: " + target + "\r\n"));
  27176. }
  27177. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27178. proxy_tunnel_test::ScopedSSLServer origin;
  27179. auto port = std::to_string(origin.port());
  27180. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27181. res.set_redirect("https://next.example:" + port + "/y");
  27182. });
  27183. origin.svr().Get("/y", [](const Request &, Response &res) {
  27184. res.set_content("ok", "text/plain");
  27185. });
  27186. origin.listen();
  27187. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27188. ASSERT_NE(0, proxy.port());
  27189. SSLClient cli("origin.example", origin.port());
  27190. cli.enable_server_certificate_verification(false);
  27191. cli.set_tunnel_hostname_addr_map(
  27192. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27193. cli.set_proxy("127.0.0.1", proxy.port());
  27194. cli.set_follow_location(true);
  27195. auto res = cli.Get("/x");
  27196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27197. EXPECT_EQ("ok", res->body);
  27198. // The last CONNECT is the redirect client's.
  27199. ASSERT_EQ(2, proxy.connect_hits());
  27200. auto target = "127.0.0.1:" + port;
  27201. auto connect_req = proxy.connect_request();
  27202. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27203. EXPECT_NE(std::string::npos,
  27204. connect_req.find("\r\nHost: " + target + "\r\n"));
  27205. }
  27206. #endif
  27207. namespace proxy_tunnel_test {
  27208. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27209. // anything else gets a 407 with `challenge`.
  27210. ConnectReply require_proxy_auth(const std::string &expected,
  27211. const std::string &challenge) {
  27212. return [=](const std::string &head) -> std::string {
  27213. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27214. std::string::npos) {
  27215. return kTunnelEstablished;
  27216. }
  27217. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27218. "Proxy-Authenticate: " +
  27219. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27220. };
  27221. }
  27222. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27223. // request, then echoes.
  27224. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27225. ws.send(
  27226. "authorization:" + req.get_header_value("Authorization") +
  27227. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27228. std::string msg;
  27229. while (ws.read(msg)) {
  27230. ws.send(msg);
  27231. }
  27232. }
  27233. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27234. class ScopedWebSocketOrigin {
  27235. public:
  27236. ScopedWebSocketOrigin() {
  27237. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27238. server_.listen();
  27239. }
  27240. int port() const { return server_.port(); }
  27241. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27242. std::string url() const {
  27243. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27244. }
  27245. private:
  27246. no_proxy_test::ScopedServer server_;
  27247. };
  27248. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27249. // passed as a constructor header, and checks that each reaches only its hop.
  27250. void WebSocketCredentialsStayWithTheirHop(
  27251. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27252. const std::string &proxy_authz, const std::string &origin_authz) {
  27253. ScopedWebSocketOrigin origin;
  27254. ScopedConnectProxy proxy(
  27255. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27256. ASSERT_NE(0, proxy.port());
  27257. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27258. client.set_proxy("127.0.0.1", proxy.port());
  27259. set_proxy_credentials(client);
  27260. auto res = client.connect();
  27261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27262. std::string msg;
  27263. ASSERT_TRUE(client.read(msg));
  27264. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27265. client.close();
  27266. EXPECT_EQ(1, proxy.connect_hits());
  27267. EXPECT_EQ(std::string::npos,
  27268. proxy.connect_request().find("\r\nAuthorization: "))
  27269. << "origin credentials must not be sent to the proxy";
  27270. }
  27271. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27272. void WebSocketSetterCredentialsStayWithTheirHop(
  27273. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27274. const std::string &proxy_authz, const std::string &origin_authz) {
  27275. ScopedWebSocketOrigin origin;
  27276. ScopedConnectProxy proxy(
  27277. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27278. ASSERT_NE(0, proxy.port());
  27279. ws::WebSocketClient client(origin.url());
  27280. client.set_proxy("127.0.0.1", proxy.port());
  27281. set_credentials(client);
  27282. auto res = client.connect();
  27283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27284. std::string msg;
  27285. ASSERT_TRUE(client.read(msg));
  27286. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27287. client.close();
  27288. EXPECT_EQ(1, proxy.connect_hits());
  27289. EXPECT_EQ(std::string::npos,
  27290. proxy.connect_request().find("\r\nAuthorization: "))
  27291. << "origin credentials must not be sent to the proxy";
  27292. }
  27293. } // namespace proxy_tunnel_test
  27294. namespace {
  27295. // Connects `client` and returns the Authorization header its upgrade
  27296. // request carried, or "<failed>" when the connection could not be opened.
  27297. std::string websocket_authorization(ws::WebSocketClient &client) {
  27298. if (!client.connect()) { return "<failed>"; }
  27299. std::string msg;
  27300. if (!client.read(msg)) { return "<failed>"; }
  27301. client.close();
  27302. auto prefix = std::string("authorization:");
  27303. auto end = msg.find("|proxy-authorization:");
  27304. return msg.substr(prefix.size(), end - prefix.size());
  27305. }
  27306. } // namespace
  27307. TEST(WebSocketClientAuthTest, BasicAuth) {
  27308. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27309. ws::WebSocketClient client(origin.url());
  27310. client.set_basic_auth("user", "pass");
  27311. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27312. websocket_authorization(client));
  27313. }
  27314. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27315. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27316. ws::WebSocketClient client(origin.url());
  27317. client.set_basic_auth("user", "");
  27318. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27319. websocket_authorization(client));
  27320. }
  27321. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27322. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27323. ws::WebSocketClient client(origin.url());
  27324. client.set_bearer_token_auth("token123");
  27325. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27326. }
  27327. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27328. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27329. ws::WebSocketClient client(origin.url());
  27330. client.set_bearer_token_auth("token123");
  27331. client.set_basic_auth("user", "pass");
  27332. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27333. websocket_authorization(client));
  27334. }
  27335. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27336. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27337. ws::WebSocketClient client(origin.url(),
  27338. {{"Authorization", "Bearer from-header"}});
  27339. client.set_bearer_token_auth("from-setter");
  27340. client.set_basic_auth("user", "pass");
  27341. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27342. }
  27343. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27344. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27345. ws::WebSocketClient client(origin.url());
  27346. EXPECT_EQ("", websocket_authorization(client));
  27347. client.set_bearer_token_auth("first");
  27348. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27349. client.set_bearer_token_auth("second");
  27350. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27351. client.set_bearer_token_auth("");
  27352. EXPECT_EQ("", websocket_authorization(client));
  27353. }
  27354. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27355. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27356. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27357. ASSERT_NE(0, proxy.port());
  27358. ws::WebSocketClient client(origin.url());
  27359. client.set_proxy("127.0.0.1", proxy.port());
  27360. auto res = client.connect();
  27361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27362. std::string msg;
  27363. ASSERT_TRUE(client.read(msg));
  27364. ASSERT_TRUE(client.send("hello"));
  27365. ASSERT_TRUE(client.read(msg));
  27366. EXPECT_EQ("hello", msg);
  27367. client.close();
  27368. EXPECT_EQ(1, proxy.connect_hits());
  27369. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27370. auto connect_req = proxy.connect_request();
  27371. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27372. EXPECT_NE(std::string::npos,
  27373. connect_req.find("\r\nHost: " + target + "\r\n"));
  27374. }
  27375. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27376. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27377. [](ws::WebSocketClient &cli) {
  27378. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27379. },
  27380. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27381. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27382. }
  27383. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27384. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27385. [](ws::WebSocketClient &cli) {
  27386. cli.set_proxy_bearer_token_auth("proxy-token");
  27387. },
  27388. "Bearer proxy-token", "Bearer origin-token");
  27389. }
  27390. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27391. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27392. [](ws::WebSocketClient &cli) {
  27393. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27394. cli.set_basic_auth("origin-user", "origin-pass");
  27395. },
  27396. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27397. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27398. }
  27399. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27400. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27401. [](ws::WebSocketClient &cli) {
  27402. cli.set_proxy_bearer_token_auth("proxy-token");
  27403. cli.set_bearer_token_auth("origin-token");
  27404. },
  27405. "Bearer proxy-token", "Bearer origin-token");
  27406. }
  27407. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27408. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27409. proxy_tunnel_test::ScopedConnectProxy proxy(
  27410. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27411. "Basic " + detail::base64_encode("proxy-user:"),
  27412. "Basic realm=\"proxy\""));
  27413. ASSERT_NE(0, proxy.port());
  27414. ws::WebSocketClient client(origin.url());
  27415. client.set_proxy("127.0.0.1", proxy.port());
  27416. client.set_proxy_basic_auth("proxy-user", "");
  27417. auto res = client.connect();
  27418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27419. client.close();
  27420. EXPECT_EQ(1, proxy.connect_hits());
  27421. }
  27422. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27423. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27424. proxy_tunnel_test::ScopedConnectProxy proxy(
  27425. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27426. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27427. ASSERT_NE(0, proxy.port());
  27428. ws::WebSocketClient client(origin.url());
  27429. client.set_proxy("127.0.0.1", proxy.port());
  27430. auto res = client.connect();
  27431. EXPECT_FALSE(res);
  27432. EXPECT_EQ(Error::ProxyConnection, res.error());
  27433. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27434. EXPECT_EQ("Basic realm=\"proxy\"",
  27435. res.get_header_value("Proxy-Authenticate"));
  27436. EXPECT_FALSE(client.is_open());
  27437. }
  27438. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27439. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27440. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27441. ASSERT_NE(0, proxy.port());
  27442. ws::WebSocketClient client(origin.url());
  27443. client.set_proxy("127.0.0.1", proxy.port());
  27444. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27445. client.set_no_proxy({"127.0.0.1"});
  27446. auto res = client.connect();
  27447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27448. std::string msg;
  27449. ASSERT_TRUE(client.read(msg));
  27450. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27451. << "proxy credentials must not reach a bypassed origin";
  27452. client.close();
  27453. EXPECT_EQ(0, proxy.connect_hits());
  27454. }
  27455. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27456. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27457. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27458. ASSERT_NE(0, proxy.port());
  27459. ws::WebSocketClient client(origin.url());
  27460. client.set_proxy("127.0.0.1", proxy.port());
  27461. ASSERT_TRUE(client.connect());
  27462. ASSERT_TRUE(client.connect());
  27463. client.close();
  27464. EXPECT_EQ(2, proxy.connect_hits());
  27465. }
  27466. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27467. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27468. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27469. ASSERT_NE(0, proxy.port());
  27470. auto port = std::to_string(origin.port());
  27471. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27472. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27473. client.set_proxy("127.0.0.1", proxy.port());
  27474. auto res = client.connect();
  27475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27476. std::string msg;
  27477. ASSERT_TRUE(client.read(msg));
  27478. client.close();
  27479. EXPECT_EQ(1, proxy.connect_hits());
  27480. auto target = "127.0.0.1:" + port;
  27481. auto connect_req = proxy.connect_request();
  27482. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27483. EXPECT_NE(std::string::npos,
  27484. connect_req.find("\r\nHost: " + target + "\r\n"));
  27485. }
  27486. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27487. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27488. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27489. ASSERT_NE(0, proxy.port());
  27490. auto port = std::to_string(origin.port());
  27491. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27492. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27493. client.set_proxy("127.0.0.1", proxy.port());
  27494. auto res = client.connect();
  27495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27496. client.close();
  27497. auto target = "origin.example:" + port;
  27498. auto connect_req = proxy.connect_request();
  27499. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27500. EXPECT_NE(std::string::npos,
  27501. connect_req.find("\r\nHost: " + target + "\r\n"));
  27502. }
  27503. #ifdef CPPHTTPLIB_SSL_ENABLED
  27504. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27505. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27506. proxy_tunnel_test::ScopedConnectProxy proxy(
  27507. origin.port(), [](const std::string &head) -> std::string {
  27508. if (head.find(
  27509. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27510. std::string::npos) {
  27511. return proxy_tunnel_test::kTunnelEstablished;
  27512. }
  27513. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27514. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27515. "nonce=\"abc\", algorithm=MD5\r\n"
  27516. "Content-Length: 0\r\n\r\n";
  27517. });
  27518. ASSERT_NE(0, proxy.port());
  27519. ws::WebSocketClient client(origin.url());
  27520. client.set_proxy("127.0.0.1", proxy.port());
  27521. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27522. auto res = client.connect();
  27523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27524. std::string msg;
  27525. ASSERT_TRUE(client.read(msg));
  27526. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27527. client.close();
  27528. EXPECT_EQ(2, proxy.connect_hits());
  27529. }
  27530. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27531. proxy_tunnel_test::ScopedSSLServer origin;
  27532. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27533. origin.listen();
  27534. proxy_tunnel_test::ScopedConnectProxy proxy(
  27535. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27536. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27537. ASSERT_NE(0, proxy.port());
  27538. ws::WebSocketClient client(
  27539. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27540. client.enable_server_certificate_verification(false);
  27541. client.set_proxy("127.0.0.1", proxy.port());
  27542. client.set_proxy_bearer_token_auth("proxy-token");
  27543. auto res = client.connect();
  27544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27545. std::string msg;
  27546. ASSERT_TRUE(client.read(msg));
  27547. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27548. << "Proxy-Authorization must not be sent inside the tunnel";
  27549. client.close();
  27550. EXPECT_EQ(1, proxy.connect_hits());
  27551. }
  27552. #endif