1
0

test.cc 710 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  595. string original = "Piri Tommy Villiers - on & on";
  596. string encoded = httplib::encode_uri_component(original);
  597. string decoded = httplib::decode_uri_component(encoded);
  598. EXPECT_EQ(decoded, original);
  599. }
  600. TEST(TrimTests, TrimStringTests) {
  601. EXPECT_EQ("abc", detail::trim_copy("abc"));
  602. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  603. EXPECT_TRUE(detail::trim_copy("").empty());
  604. }
  605. TEST(AsciiTest, LocaleIndependentClassification) {
  606. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  607. // which consult the global C locale: std::isalnum(0xC5) can return true
  608. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  609. // helpers must classify every byte by the ASCII grammar alone.
  610. for (int i = 0; i < 256; i++) {
  611. auto c = static_cast<char>(i);
  612. auto is_digit = i >= '0' && i <= '9';
  613. auto is_upper = i >= 'A' && i <= 'Z';
  614. auto is_lower = i >= 'a' && i <= 'z';
  615. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  616. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  617. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  618. << "byte " << i;
  619. }
  620. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  621. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  622. // Non-ASCII bytes must be percent-encoded, never passed through as
  623. // alphanumeric.
  624. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  625. }
  626. TEST(FromCharsTest, Double) {
  627. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  628. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  629. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  630. auto parse = [](const std::string &s, double &v) {
  631. return detail::from_chars(s.data(), s.data() + s.size(), v);
  632. };
  633. double v = -1.0;
  634. // Representative quality values.
  635. EXPECT_EQ(parse("0", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.0);
  637. EXPECT_EQ(parse("1", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.8);
  641. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.001);
  643. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  644. EXPECT_DOUBLE_EQ(v, 1.0);
  645. // A missing integer or fractional part is tolerated.
  646. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  647. EXPECT_DOUBLE_EQ(v, 0.5);
  648. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 5.0);
  650. // Values outside [0, 1] still parse; the caller range-checks them.
  651. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  652. EXPECT_DOUBLE_EQ(v, 123.456);
  653. // Stops at the first byte that is not part of the number and reports where.
  654. std::string trailing = "0.9, text/html";
  655. auto r = parse(trailing, v);
  656. EXPECT_EQ(r.ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.9);
  658. EXPECT_EQ(*r.ptr, ',');
  659. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  660. // outright, and an 'e'/'E' simply ends the number.
  661. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  662. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  663. std::string exp_input = "1.5e3";
  664. r = parse(exp_input, v);
  665. EXPECT_EQ(r.ec, std::errc{});
  666. EXPECT_DOUBLE_EQ(v, 1.5);
  667. EXPECT_EQ(*r.ptr, 'e');
  668. // Invalid inputs.
  669. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  670. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  671. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  672. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  673. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  674. // Pathological but well-formed inputs must stay bounded (no overflow, no
  675. // out-of-bounds table access) and stay within [0, 1] for the caller.
  676. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  677. std::errc{});
  678. EXPECT_DOUBLE_EQ(v, 0.0);
  679. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  680. std::errc{});
  681. EXPECT_GE(v, 0.0);
  682. EXPECT_LE(v, 1.0);
  683. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  684. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  685. }
  686. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  687. // Simple case without quality values
  688. std::vector<std::string> result1;
  689. EXPECT_TRUE(detail::parse_accept_header(
  690. "text/html,application/json,text/plain", result1));
  691. EXPECT_EQ(result1.size(), 3U);
  692. EXPECT_EQ(result1[0], "text/html");
  693. EXPECT_EQ(result1[1], "application/json");
  694. EXPECT_EQ(result1[2], "text/plain");
  695. // With quality values
  696. std::vector<std::string> result2;
  697. EXPECT_TRUE(detail::parse_accept_header(
  698. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  699. EXPECT_EQ(result2.size(), 3U);
  700. EXPECT_EQ(result2[0], "application/json"); // highest q value
  701. EXPECT_EQ(result2[1], "text/html");
  702. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  703. }
  704. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  705. // Mixed with and without quality values
  706. std::vector<std::string> result;
  707. EXPECT_TRUE(detail::parse_accept_header(
  708. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  709. EXPECT_EQ(result.size(), 3U);
  710. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  711. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  712. EXPECT_EQ(result[2], "application/json"); // q=0.5
  713. }
  714. TEST(ParseAcceptHeaderTest, EdgeCases) {
  715. // Empty header
  716. std::vector<std::string> empty_result;
  717. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  718. EXPECT_TRUE(empty_result.empty());
  719. // Single type
  720. std::vector<std::string> single_result;
  721. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  722. EXPECT_EQ(single_result.size(), 1U);
  723. EXPECT_EQ(single_result[0], "application/json");
  724. // Wildcard types
  725. std::vector<std::string> wildcard_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  728. EXPECT_EQ(wildcard_result.size(), 3U);
  729. EXPECT_EQ(wildcard_result[0], "application/json");
  730. EXPECT_EQ(wildcard_result[1], "text/*");
  731. EXPECT_EQ(wildcard_result[2], "*/*");
  732. }
  733. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  734. // Common browser Accept header
  735. std::vector<std::string> browser_result;
  736. EXPECT_TRUE(
  737. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  738. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  739. browser_result));
  740. EXPECT_EQ(browser_result.size(), 6U);
  741. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  742. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  743. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  744. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  745. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  746. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  747. // API client header
  748. std::vector<std::string> api_result;
  749. EXPECT_TRUE(detail::parse_accept_header(
  750. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  751. api_result));
  752. EXPECT_EQ(api_result.size(), 3U);
  753. EXPECT_EQ(api_result[0], "application/json");
  754. EXPECT_EQ(api_result[1], "application/xml");
  755. EXPECT_EQ(api_result[2], "text/plain");
  756. }
  757. TEST(ParseAcceptHeaderTest, SpecialCases) {
  758. // Quality value with 3 decimal places
  759. std::vector<std::string> decimal_result;
  760. EXPECT_TRUE(detail::parse_accept_header(
  761. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  762. EXPECT_EQ(decimal_result.size(), 2U);
  763. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  764. EXPECT_EQ(decimal_result[1], "text/html");
  765. // Zero quality (should still be included but with lowest priority)
  766. std::vector<std::string> zero_q_result;
  767. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  768. zero_q_result));
  769. EXPECT_EQ(zero_q_result.size(), 2U);
  770. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  771. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  772. // No spaces around commas
  773. std::vector<std::string> no_space_result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  776. no_space_result));
  777. EXPECT_EQ(no_space_result.size(), 3U);
  778. EXPECT_EQ(no_space_result[0], "text/html");
  779. EXPECT_EQ(no_space_result[1], "application/json");
  780. EXPECT_EQ(no_space_result[2], "text/plain");
  781. }
  782. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  783. // Quality values always use '.' as the decimal separator, so parsing must
  784. // not depend on the process locale. An embedding application may have
  785. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  786. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  787. std::string saved = cur ? cur : "C";
  788. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  789. "fr_FR.UTF-8"};
  790. bool switched = false;
  791. for (const auto loc : comma_locales) {
  792. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  793. std::localeconv()->decimal_point[0] == ',') {
  794. switched = true;
  795. break;
  796. }
  797. }
  798. if (!switched) {
  799. std::setlocale(LC_NUMERIC, saved.c_str());
  800. GTEST_SKIP() << "no comma-decimal locale available on this host";
  801. }
  802. // The higher-weighted type appears later in the list, so a correct parse
  803. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  804. // sensitive parse reads both weights as 0 and leaves the original order.
  805. std::vector<std::string> result;
  806. EXPECT_TRUE(detail::parse_accept_header(
  807. "application/json;q=0.1,text/html;q=0.9", result));
  808. ASSERT_EQ(result.size(), 2U);
  809. EXPECT_EQ(result[0], "text/html");
  810. EXPECT_EQ(result[1], "application/json");
  811. std::setlocale(LC_NUMERIC, saved.c_str());
  812. }
  813. TEST(ParseAcceptHeaderTest, InvalidCases) {
  814. std::vector<std::string> result;
  815. // Invalid quality value (> 1.0)
  816. EXPECT_FALSE(
  817. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  818. // Invalid quality value (< 0.0)
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  821. // Invalid quality value (not a number)
  822. EXPECT_FALSE(detail::parse_accept_header(
  823. "text/html;q=invalid,application/json", result));
  824. // Empty quality value
  825. EXPECT_FALSE(
  826. detail::parse_accept_header("text/html;q=,application/json", result));
  827. // Invalid media type format (no slash and not wildcard)
  828. EXPECT_FALSE(
  829. detail::parse_accept_header("invalidtype,application/json", result));
  830. // Empty media type
  831. result.clear();
  832. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  833. // Only commas
  834. result.clear();
  835. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  836. // Valid cases should still work
  837. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "*/*");
  840. EXPECT_TRUE(detail::parse_accept_header("*", result));
  841. EXPECT_EQ(result.size(), 1U);
  842. EXPECT_EQ(result[0], "*");
  843. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  844. EXPECT_EQ(result.size(), 1U);
  845. EXPECT_EQ(result[0], "text/*");
  846. }
  847. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  848. Server svr;
  849. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  850. EXPECT_EQ(req.accept_content_types.size(), 3U);
  851. EXPECT_EQ(req.accept_content_types[0], "application/json");
  852. EXPECT_EQ(req.accept_content_types[1], "text/html");
  853. EXPECT_EQ(req.accept_content_types[2], "*/*");
  854. res.set_content("ok", "text/plain");
  855. });
  856. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  857. EXPECT_TRUE(false);
  858. res.set_content("bad request", "text/plain");
  859. });
  860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  861. auto se = detail::scope_exit([&] {
  862. svr.stop();
  863. listen_thread.join();
  864. ASSERT_FALSE(svr.is_running());
  865. });
  866. svr.wait_until_ready();
  867. Client cli("localhost", PORT);
  868. {
  869. auto res = cli.Get(
  870. "/accept_ok",
  871. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::OK_200, res->status);
  874. }
  875. {
  876. auto res = cli.Get("/accept_bad_request",
  877. Headers{{"Accept", "text/html;q=abc,application/json"}});
  878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  880. }
  881. }
  882. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  883. Server svr;
  884. svr.Get("/", [](const Request & /*req*/, Response &res) {
  885. res.set_content("ok", "text/plain");
  886. });
  887. std::atomic<int> start_count{0};
  888. std::atomic<bool> running_when_called{false};
  889. svr.set_start_handler([&]() {
  890. running_when_called = svr.is_running();
  891. start_count++;
  892. });
  893. auto port = svr.bind_to_any_port(HOST);
  894. std::thread t([&]() { svr.listen_after_bind(); });
  895. auto se = detail::scope_exit([&] {
  896. svr.stop();
  897. t.join();
  898. ASSERT_FALSE(svr.is_running());
  899. });
  900. svr.wait_until_ready();
  901. // A successful request proves the accept loop is running, which the start
  902. // handler precedes; so by now the handler must have run exactly once.
  903. Client cli(HOST, port);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res = cli.Get("/");
  906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  907. EXPECT_EQ(StatusCode::OK_200, res->status);
  908. EXPECT_EQ(1, start_count.load());
  909. EXPECT_TRUE(running_when_called.load());
  910. }
  911. TEST(DivideTest, DivideStringTests) {
  912. auto divide = [](const std::string &str, char d) {
  913. std::string lhs;
  914. std::string rhs;
  915. detail::divide(str, d,
  916. [&](const char *lhs_data, std::size_t lhs_size,
  917. const char *rhs_data, std::size_t rhs_size) {
  918. lhs.assign(lhs_data, lhs_size);
  919. rhs.assign(rhs_data, rhs_size);
  920. });
  921. return std::make_pair(std::move(lhs), std::move(rhs));
  922. };
  923. {
  924. const auto res = divide("", '=');
  925. EXPECT_EQ(res.first, "");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("=", '=');
  930. EXPECT_EQ(res.first, "");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide(" ", '=');
  935. EXPECT_EQ(res.first, " ");
  936. EXPECT_EQ(res.second, "");
  937. }
  938. {
  939. const auto res = divide("a", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("a=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide("=b", '=');
  950. EXPECT_EQ(res.first, "");
  951. EXPECT_EQ(res.second, "b");
  952. }
  953. {
  954. const auto res = divide("a=b", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "b");
  957. }
  958. {
  959. const auto res = divide("a=b=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "b=");
  962. }
  963. {
  964. const auto res = divide("a=b=c", '=');
  965. EXPECT_EQ(res.first, "a");
  966. EXPECT_EQ(res.second, "b=c");
  967. }
  968. }
  969. TEST(SplitTest, ParseQueryString) {
  970. string s = "key1=val1&key2=val2&key3=val3";
  971. Params dic;
  972. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  973. [&](const char *b, const char *e) {
  974. string key, val;
  975. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  976. if (key.empty()) {
  977. key.assign(b2, e2);
  978. } else {
  979. val.assign(b2, e2);
  980. }
  981. });
  982. dic.emplace(key, val);
  983. });
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. TEST(SplitTest, ParseInvalidQueryTests) {
  989. {
  990. string s = " ";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. {
  996. string s = " = =";
  997. Params dict;
  998. detail::parse_query_text(s, dict);
  999. EXPECT_TRUE(dict.empty());
  1000. }
  1001. }
  1002. TEST(ParseQueryTest, ParseQueryString) {
  1003. {
  1004. std::string s = "key1=val1&key2=val2&key3=val3";
  1005. Params dic;
  1006. detail::parse_query_text(s, dic);
  1007. EXPECT_EQ("val1", dic.find("key1")->second);
  1008. EXPECT_EQ("val2", dic.find("key2")->second);
  1009. EXPECT_EQ("val3", dic.find("key3")->second);
  1010. }
  1011. {
  1012. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1013. Params dic;
  1014. detail::parse_query_text(s, dic);
  1015. EXPECT_EQ("", dic.find("key1")->second);
  1016. EXPECT_EQ("val1", dic.find("key2")->second);
  1017. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1018. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1019. }
  1020. }
  1021. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1022. Params dic;
  1023. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1024. dic.emplace("key1", "val1");
  1025. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1026. dic.emplace("key2", "val2");
  1027. dic.emplace("key3", "val3");
  1028. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1029. }
  1030. // Joins every entry of a Headers or Params into "key=value " so a whole
  1031. // traversal can be compared in one assertion. Both are instantiations of the
  1032. // same insertion-ordered container, so one helper serves both.
  1033. template <typename Map> static std::string entries_to_string(const Map &m) {
  1034. std::string s;
  1035. for (const auto &entry : m) {
  1036. s += entry.first + "=" + entry.second + " ";
  1037. }
  1038. return s;
  1039. }
  1040. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1041. // Params used to be a std::multimap, which sorted by name and handed the
  1042. // caller's query back alphabetised. A client signing its query string could
  1043. // not reproduce the order it asked for.
  1044. Params dic;
  1045. dic.emplace("zulu", "1");
  1046. dic.emplace("alpha", "2");
  1047. dic.emplace("mike", "3");
  1048. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1049. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1050. }
  1051. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1052. Params dic;
  1053. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1054. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1055. }
  1056. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1057. Request req;
  1058. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1059. req.params);
  1060. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1061. EXPECT_EQ("first", req.get_param_value("tag"));
  1062. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1063. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1064. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1065. EXPECT_EQ("", req.get_param_value("tag", 3));
  1066. }
  1067. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1068. // Params shares its container with Headers, which matches field names
  1069. // case-insensitively. Parameter names must not pick that up.
  1070. Params dic;
  1071. dic.emplace("Key", "upper");
  1072. dic.emplace("key", "lower");
  1073. EXPECT_EQ(2U, dic.size());
  1074. EXPECT_EQ(1U, dic.count("Key"));
  1075. EXPECT_EQ(1U, dic.count("key"));
  1076. EXPECT_EQ("upper", dic.find("Key")->second);
  1077. EXPECT_EQ("lower", dic.find("key")->second);
  1078. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1079. }
  1080. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1081. Server svr;
  1082. std::string order;
  1083. svr.Get("/order", [&](const Request &req, Response &res) {
  1084. order = entries_to_string(req.params);
  1085. res.set_content("ok", "text/plain");
  1086. });
  1087. auto port = svr.bind_to_any_port(HOST);
  1088. thread t = thread([&] { svr.listen_after_bind(); });
  1089. auto se = detail::scope_exit([&] {
  1090. svr.stop();
  1091. t.join();
  1092. ASSERT_FALSE(svr.is_running());
  1093. });
  1094. svr.wait_until_ready();
  1095. Client cli(HOST, port);
  1096. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1097. ASSERT_TRUE(res);
  1098. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1099. }
  1100. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1101. Server svr;
  1102. std::string field_order, file_order;
  1103. svr.Post("/order", [&](const Request &req, Response &res) {
  1104. for (const auto &field : req.form.fields) {
  1105. field_order += field.first + "=" + field.second.content + " ";
  1106. }
  1107. for (const auto &file : req.form.files) {
  1108. file_order += file.first + "=" + file.second.filename + " ";
  1109. }
  1110. res.set_content("ok", "text/plain");
  1111. });
  1112. auto port = svr.bind_to_any_port(HOST);
  1113. thread t = thread([&] { svr.listen_after_bind(); });
  1114. auto se = detail::scope_exit([&] {
  1115. svr.stop();
  1116. t.join();
  1117. ASSERT_FALSE(svr.is_running());
  1118. });
  1119. svr.wait_until_ready();
  1120. UploadFormDataItems items = {
  1121. {"zulu", "1", "", ""},
  1122. {"alpha", "2", "", ""},
  1123. {"mike", "3", "", ""},
  1124. {"zebra", "z", "z.txt", "text/plain"},
  1125. {"apple", "a", "a.txt", "text/plain"},
  1126. };
  1127. Client cli(HOST, port);
  1128. auto res = cli.Post("/order", items);
  1129. ASSERT_TRUE(res);
  1130. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1131. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1132. }
  1133. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1134. Server svr;
  1135. std::vector<std::string> values;
  1136. std::string first, second, out_of_range, order;
  1137. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1138. values = req.form.get_fields("tag");
  1139. first = req.form.get_field("tag", 0);
  1140. second = req.form.get_field("tag", 1);
  1141. out_of_range = req.form.get_field("tag", 2);
  1142. for (const auto &field : req.form.fields) {
  1143. order += field.first + "=" + field.second.content + " ";
  1144. }
  1145. res.set_content("ok", "text/plain");
  1146. });
  1147. auto port = svr.bind_to_any_port(HOST);
  1148. thread t = thread([&] { svr.listen_after_bind(); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. t.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1156. // not adjacent in the container.
  1157. UploadFormDataItems items = {
  1158. {"tag", "first", "", ""},
  1159. {"other", "x", "", ""},
  1160. {"tag", "second", "", ""},
  1161. };
  1162. Client cli(HOST, port);
  1163. auto res = cli.Post("/repeated", items);
  1164. ASSERT_TRUE(res);
  1165. ASSERT_EQ(2U, values.size());
  1166. EXPECT_EQ("first", values[0]);
  1167. EXPECT_EQ("second", values[1]);
  1168. EXPECT_EQ("first", first);
  1169. EXPECT_EQ("second", second);
  1170. // std::multimap already kept entries sharing a name in insertion order, so
  1171. // everything above passes without this change too. The whole traversal is
  1172. // what tells the two apart: sorting by name would hoist "other" to the front
  1173. // and the two "tag" parts would end up adjacent.
  1174. EXPECT_EQ("tag=first other=x tag=second ", order);
  1175. // Advancing past the last entry of a name used to run off the container;
  1176. // the container's saturating increment makes it return the default instead.
  1177. EXPECT_EQ("", out_of_range);
  1178. }
  1179. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1180. // Server::read_content() keeps a FormFields::iterator alive across the
  1181. // content callbacks that fill the part it points at. The container is
  1182. // vector-backed, so a later emplace can reallocate and invalidate an older
  1183. // iterator; 64 parts grow the vector through seven reallocations, which
  1184. // checks that every part's content still lands in its own entry.
  1185. const size_t part_count = 64;
  1186. // One formula for both the parts sent and the values expected back, so the
  1187. // two cannot drift apart.
  1188. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1189. auto content_of = [](size_t i) {
  1190. return std::string(64, static_cast<char>('a' + (i % 26)));
  1191. };
  1192. Server svr;
  1193. std::vector<std::pair<std::string, std::string>> received;
  1194. svr.Post("/many", [&](const Request &req, Response &res) {
  1195. for (const auto &field : req.form.fields) {
  1196. received.emplace_back(field.first, field.second.content);
  1197. }
  1198. res.set_content("ok", "text/plain");
  1199. });
  1200. auto port = svr.bind_to_any_port(HOST);
  1201. thread t = thread([&] { svr.listen_after_bind(); });
  1202. auto se = detail::scope_exit([&] {
  1203. svr.stop();
  1204. t.join();
  1205. ASSERT_FALSE(svr.is_running());
  1206. });
  1207. svr.wait_until_ready();
  1208. UploadFormDataItems items;
  1209. for (size_t i = 0; i < part_count; i++) {
  1210. items.push_back({name_of(i), content_of(i), "", ""});
  1211. }
  1212. Client cli(HOST, port);
  1213. auto res = cli.Post("/many", items);
  1214. ASSERT_TRUE(res);
  1215. ASSERT_EQ(part_count, received.size());
  1216. for (size_t i = 0; i < part_count; i++) {
  1217. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1218. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1219. }
  1220. }
  1221. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1222. string content_type = "multipart/form-data; boundary=something";
  1223. string boundary;
  1224. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1225. EXPECT_TRUE(ret);
  1226. EXPECT_EQ(boundary, "something");
  1227. }
  1228. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1229. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1230. string boundary;
  1231. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1232. EXPECT_TRUE(ret);
  1233. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1234. }
  1235. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1236. string content_type =
  1237. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1244. string content_type =
  1245. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1246. string boundary;
  1247. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1248. EXPECT_TRUE(ret);
  1249. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1250. }
  1251. TEST(GetHeaderValueTest, DefaultValue) {
  1252. Headers headers = {{"Dummy", "Dummy"}};
  1253. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1254. EXPECT_STREQ("text/plain", val);
  1255. }
  1256. TEST(GetHeaderValueTest, DefaultValueInt) {
  1257. Headers headers = {{"Dummy", "Dummy"}};
  1258. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1259. EXPECT_EQ(100ull, val);
  1260. }
  1261. TEST(GetHeaderValueTest, RegularValue) {
  1262. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1263. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1264. EXPECT_STREQ("text/html", val);
  1265. }
  1266. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1267. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1269. EXPECT_STREQ("text/html", val);
  1270. }
  1271. TEST(GetHeaderValueTest, SetContent) {
  1272. Response res;
  1273. res.set_content("html", "text/html");
  1274. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1275. res.set_content("text", "text/plain");
  1276. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1277. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1278. }
  1279. TEST(GetHeaderValueTest, RegularValueInt) {
  1280. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1281. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1282. EXPECT_EQ(100ull, val);
  1283. }
  1284. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1285. Headers headers = {{"Content-Length", "x"}};
  1286. auto is_invalid_value = false;
  1287. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1288. is_invalid_value);
  1289. EXPECT_EQ(0ull, val);
  1290. EXPECT_TRUE(is_invalid_value);
  1291. }
  1292. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1293. // An all-digit value that overflows size_t must be reported as invalid, not
  1294. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1295. // a large length to a small one on 32-bit builds, leaving the framing length
  1296. // wrong while is_invalid_value stayed false.
  1297. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1298. auto is_invalid_value = false;
  1299. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1300. is_invalid_value);
  1301. EXPECT_TRUE(is_invalid_value);
  1302. // A well-formed length is unaffected.
  1303. Headers ok = {{"Content-Length", "1234"}};
  1304. is_invalid_value = false;
  1305. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1306. is_invalid_value);
  1307. EXPECT_EQ(1234ull, val);
  1308. EXPECT_FALSE(is_invalid_value);
  1309. }
  1310. TEST(GetHeaderValueTest, Range) {
  1311. {
  1312. Headers headers = {make_range_header({{1, -1}})};
  1313. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1314. EXPECT_STREQ("bytes=1-", val);
  1315. }
  1316. {
  1317. Headers headers = {make_range_header({{-1, 1}})};
  1318. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1319. EXPECT_STREQ("bytes=-1", val);
  1320. }
  1321. {
  1322. Headers headers = {make_range_header({{1, 10}})};
  1323. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1324. EXPECT_STREQ("bytes=1-10", val);
  1325. }
  1326. {
  1327. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-10, 100-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=0-0, -1", val);
  1340. }
  1341. }
  1342. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1343. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1344. // to depend on the standard library (libstdc++ handed back duplicates in
  1345. // reverse insertion order, libc++ in insertion order).
  1346. Request req;
  1347. req.set_header("Accept-Encoding", "gzip");
  1348. req.set_header("Accept-Encoding", "deflate");
  1349. req.set_header("Accept-Encoding", "br");
  1350. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1351. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1352. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1353. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1354. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1355. }
  1356. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1357. Request req;
  1358. req.set_header("X-Test", "only");
  1359. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1360. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1361. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1362. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1363. }
  1364. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1365. Headers headers;
  1366. headers.emplace("Host", "example.com");
  1367. headers.emplace("Accept-Encoding", "gzip");
  1368. headers.emplace("User-Agent", "test");
  1369. headers.emplace("Accept-Encoding", "deflate");
  1370. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1371. "Accept-Encoding=deflate ",
  1372. entries_to_string(headers));
  1373. }
  1374. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1375. Headers headers = {{"Content-Type", "text/html"},
  1376. {"CONTENT-TYPE", "text/xml"}};
  1377. EXPECT_EQ(2U, headers.count("content-type"));
  1378. auto it = headers.find("content-type");
  1379. ASSERT_TRUE(it != headers.end());
  1380. EXPECT_EQ("text/html", it->second);
  1381. }
  1382. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1383. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1384. // drop only those fields and leave everything positioned between them.
  1385. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1386. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1387. auto rng = headers.equal_range("a");
  1388. headers.erase(rng.first, rng.second);
  1389. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1390. }
  1391. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1392. Headers headers = {
  1393. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1394. EXPECT_EQ(3U, headers.erase("A"));
  1395. EXPECT_EQ(0U, headers.count("A"));
  1396. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1397. }
  1398. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1399. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1400. headers.emplace_front("Host", "example.com");
  1401. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1402. entries_to_string(headers));
  1403. }
  1404. TEST(ParseHeaderValueTest, Range) {
  1405. {
  1406. Ranges ranges;
  1407. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1408. EXPECT_TRUE(ret);
  1409. EXPECT_EQ(1u, ranges.size());
  1410. EXPECT_EQ(1u, ranges[0].first);
  1411. EXPECT_EQ(-1, ranges[0].second);
  1412. }
  1413. {
  1414. Ranges ranges;
  1415. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1416. EXPECT_TRUE(ret);
  1417. EXPECT_EQ(1u, ranges.size());
  1418. EXPECT_EQ(-1, ranges[0].first);
  1419. EXPECT_EQ(1u, ranges[0].second);
  1420. }
  1421. {
  1422. Ranges ranges;
  1423. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1424. EXPECT_TRUE(ret);
  1425. EXPECT_EQ(1u, ranges.size());
  1426. EXPECT_EQ(1u, ranges[0].first);
  1427. EXPECT_EQ(10u, ranges[0].second);
  1428. }
  1429. {
  1430. Ranges ranges;
  1431. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1432. EXPECT_FALSE(ret);
  1433. }
  1434. {
  1435. Ranges ranges;
  1436. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1437. EXPECT_TRUE(ret);
  1438. EXPECT_EQ(2u, ranges.size());
  1439. EXPECT_EQ(1u, ranges[0].first);
  1440. EXPECT_EQ(10u, ranges[0].second);
  1441. EXPECT_EQ(100u, ranges[1].first);
  1442. EXPECT_EQ(-1, ranges[1].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret =
  1447. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1448. EXPECT_TRUE(ret);
  1449. EXPECT_EQ(3u, ranges.size());
  1450. EXPECT_EQ(1u, ranges[0].first);
  1451. EXPECT_EQ(10u, ranges[0].second);
  1452. EXPECT_EQ(100u, ranges[1].first);
  1453. EXPECT_EQ(200u, ranges[1].second);
  1454. EXPECT_EQ(300u, ranges[2].first);
  1455. EXPECT_EQ(400u, ranges[2].second);
  1456. }
  1457. {
  1458. Ranges ranges;
  1459. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1460. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1461. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1462. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1463. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1464. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1465. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1466. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1467. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1468. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1469. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1470. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1471. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1472. EXPECT_TRUE(ranges.empty());
  1473. }
  1474. }
  1475. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1476. Request req;
  1477. req.set_header("Accept-Encoding", "gzip");
  1478. Response res;
  1479. res.set_header("Content-Type", "text/plain");
  1480. auto ret = detail::encoding_type(req, res);
  1481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1482. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1483. #else
  1484. EXPECT_TRUE(ret == detail::EncodingType::None);
  1485. #endif
  1486. }
  1487. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1488. Request req;
  1489. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1490. Response res;
  1491. res.set_header("Content-Type", "text/plain");
  1492. auto ret = detail::encoding_type(req, res);
  1493. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1494. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1495. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1496. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1497. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1498. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1499. #else
  1500. EXPECT_TRUE(ret == detail::EncodingType::None);
  1501. #endif
  1502. }
  1503. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1504. Request req;
  1505. req.set_header("Accept-Encoding",
  1506. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1507. Response res;
  1508. res.set_header("Content-Type", "text/plain");
  1509. auto ret = detail::encoding_type(req, res);
  1510. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1512. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1514. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1521. // All supported encodings rejected with q=0 should return None
  1522. Request req;
  1523. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1524. Response res;
  1525. res.set_header("Content-Type", "text/plain");
  1526. auto ret = detail::encoding_type(req, res);
  1527. EXPECT_TRUE(ret == detail::EncodingType::None);
  1528. }
  1529. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1530. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1531. Request req;
  1532. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1533. Response res;
  1534. res.set_header("Content-Type", "text/plain");
  1535. auto ret = detail::encoding_type(req, res);
  1536. EXPECT_TRUE(ret == detail::EncodingType::None);
  1537. }
  1538. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1539. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1540. Request req;
  1541. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1542. Response res;
  1543. res.set_header("Content-Type", "text/plain");
  1544. auto ret = detail::encoding_type(req, res);
  1545. EXPECT_TRUE(ret == detail::EncodingType::None);
  1546. }
  1547. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1548. // RFC 7231: Accept-Encoding values are case-insensitive
  1549. Request req;
  1550. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1551. Response res;
  1552. res.set_header("Content-Type", "text/plain");
  1553. auto ret = detail::encoding_type(req, res);
  1554. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1555. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1556. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1557. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1558. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1559. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1560. #else
  1561. EXPECT_TRUE(ret == detail::EncodingType::None);
  1562. #endif
  1563. }
  1564. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1565. // q value should determine priority, not hardcoded order
  1566. Request req;
  1567. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1568. Response res;
  1569. res.set_header("Content-Type", "text/plain");
  1570. auto ret = detail::encoding_type(req, res);
  1571. // gzip has highest q=1.0, so it should be selected even though
  1572. // br and zstd are also supported
  1573. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1575. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1576. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1577. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1578. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1579. #else
  1580. EXPECT_TRUE(ret == detail::EncodingType::None);
  1581. #endif
  1582. }
  1583. TEST(BufferStreamTest, read) {
  1584. detail::BufferStream strm1;
  1585. Stream &strm = strm1;
  1586. EXPECT_EQ(5, strm.write("hello"));
  1587. char buf[512];
  1588. EXPECT_EQ(2, strm.read(buf, 2));
  1589. EXPECT_EQ('h', buf[0]);
  1590. EXPECT_EQ('e', buf[1]);
  1591. EXPECT_EQ(2, strm.read(buf, 2));
  1592. EXPECT_EQ('l', buf[0]);
  1593. EXPECT_EQ('l', buf[1]);
  1594. EXPECT_EQ(1, strm.read(buf, 1));
  1595. EXPECT_EQ('o', buf[0]);
  1596. EXPECT_EQ(0, strm.read(buf, 1));
  1597. }
  1598. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1599. auto host = "www.httpwatch.com";
  1600. auto ip = hosted_at(host);
  1601. EXPECT_EQ("23.96.13.243", ip);
  1602. std::vector<std::string> addrs;
  1603. hosted_at(host, addrs);
  1604. EXPECT_EQ(1u, addrs.size());
  1605. }
  1606. #if 0 // It depends on each test environment...
  1607. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1608. auto host = "www.youtube.com";
  1609. std::vector<std::string> addrs;
  1610. hosted_at(host, addrs);
  1611. EXPECT_EQ(20u, addrs.size());
  1612. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1613. EXPECT_TRUE(it != addrs.end());
  1614. }
  1615. #endif
  1616. class ChunkedEncodingTest : public ::testing::Test {
  1617. protected:
  1618. ChunkedEncodingTest()
  1619. : cli_(HOST, PORT)
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. ,
  1622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1623. #endif
  1624. {
  1625. cli_.set_connection_timeout(2);
  1626. #ifdef CPPHTTPLIB_SSL_ENABLED
  1627. cli_.enable_server_certificate_verification(false);
  1628. #endif
  1629. }
  1630. virtual void SetUp() {
  1631. read_file("./image.jpg", image_data_);
  1632. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("Hello World!", "text/plain");
  1634. });
  1635. svr_.Get(
  1636. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1637. res.set_chunked_content_provider(
  1638. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1639. size_t remaining = image_data_.size() - offset;
  1640. if (remaining == 0) {
  1641. sink.done();
  1642. } else {
  1643. constexpr size_t CHUNK_SIZE = 1024;
  1644. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1645. sink.write(&image_data_[offset], send_size);
  1646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1647. }
  1648. return true;
  1649. });
  1650. });
  1651. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1652. svr_.wait_until_ready();
  1653. }
  1654. virtual void TearDown() {
  1655. svr_.stop();
  1656. if (!request_threads_.empty()) {
  1657. std::this_thread::sleep_for(std::chrono::seconds(1));
  1658. for (auto &t : request_threads_) {
  1659. t.join();
  1660. }
  1661. }
  1662. t_.join();
  1663. }
  1664. #ifdef CPPHTTPLIB_SSL_ENABLED
  1665. SSLClient cli_;
  1666. SSLServer svr_;
  1667. #else
  1668. Client cli_;
  1669. Server svr_;
  1670. #endif
  1671. thread t_;
  1672. std::vector<thread> request_threads_;
  1673. std::string image_data_;
  1674. };
  1675. TEST_F(ChunkedEncodingTest, NormalGet) {
  1676. auto res = cli_.Get("/chunked");
  1677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1678. std::string out;
  1679. read_file("./image.jpg", out);
  1680. EXPECT_EQ(StatusCode::OK_200, res->status);
  1681. EXPECT_EQ(out, res->body);
  1682. }
  1683. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1684. std::string body;
  1685. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1690. std::string out;
  1691. read_file("./image.jpg", out);
  1692. EXPECT_EQ(StatusCode::OK_200, res->status);
  1693. EXPECT_EQ(out, body);
  1694. }
  1695. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1696. std::string body;
  1697. auto res = cli_.Get(
  1698. "/chunked",
  1699. [&](const Response &response) {
  1700. EXPECT_EQ(StatusCode::OK_200, response.status);
  1701. return true;
  1702. },
  1703. [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1708. std::string out;
  1709. read_file("./image.jpg", out);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. EXPECT_EQ(out, body);
  1712. }
  1713. TEST(RangeTest, FromHTTPBin_Online) {
  1714. auto host = "httpbingo.org";
  1715. auto path = std::string{"/range/32"};
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. auto port = 443;
  1718. SSLClient cli(host, port);
  1719. #else
  1720. auto port = 80;
  1721. Client cli(host, port);
  1722. #endif
  1723. cli.set_connection_timeout(5);
  1724. {
  1725. auto res = cli.Get(path);
  1726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1727. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. {
  1731. Headers headers = {make_range_header({{1, -1}})};
  1732. auto res = cli.Get(path, headers);
  1733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1734. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{1, 10}})};
  1739. auto res = cli.Get(path, headers);
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. EXPECT_EQ("bcdefghijk", res->body);
  1742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1743. }
  1744. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1745. // entire resource, while the original httpbin returned 200. Both are
  1746. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1747. {
  1748. Headers headers = {make_range_header({{0, 31}})};
  1749. auto res = cli.Get(path, headers);
  1750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1751. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1752. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1753. res->status == StatusCode::PartialContent_206);
  1754. }
  1755. {
  1756. Headers headers = {make_range_header({{0, -1}})};
  1757. auto res = cli.Get(path, headers);
  1758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1759. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1760. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1761. res->status == StatusCode::PartialContent_206);
  1762. }
  1763. // go-httpbin returns 206 with clamped range for over-range requests,
  1764. // while the original httpbin returned 416. Both behaviors are observed
  1765. // in real servers, so we only verify the request succeeds.
  1766. {
  1767. Headers headers = {make_range_header({{0, 32}})};
  1768. auto res = cli.Get(path, headers);
  1769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1770. }
  1771. }
  1772. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1773. auto host = "unresolvableaddress.local";
  1774. auto path = std::string{"/"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. cli.set_connection_timeout(1);
  1783. {
  1784. auto res = cli.Get(path);
  1785. ASSERT_FALSE(res);
  1786. }
  1787. std::this_thread::sleep_for(std::chrono::seconds(8));
  1788. }
  1789. #if defined(__linux__) && defined(__GLIBC__) && \
  1790. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1791. // Forward declaration: in split builds split.py strips `inline` and moves the
  1792. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1793. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1794. // against the symbol in both header-only and split builds.
  1795. namespace httplib {
  1796. namespace detail {
  1797. int getaddrinfo_with_timeout(const char *node, const char *service,
  1798. const struct addrinfo *hints,
  1799. struct addrinfo **res, time_t timeout_sec);
  1800. } // namespace detail
  1801. } // namespace httplib
  1802. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1803. //
  1804. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1805. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1806. // gai_suspend() call hits the connection timeout the function calls
  1807. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1808. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1809. // still alive and still references the now-destroyed stack frame.
  1810. //
  1811. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1812. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1813. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1814. // and runs them in a container.
  1815. namespace {
  1816. bool should_run_issue_2431_tests() {
  1817. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1818. return v && *v && std::string(v) != "0";
  1819. }
  1820. std::string unique_unresolvable_host(int n) {
  1821. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1822. // glibc still asks the configured nameserver — which is exactly the path
  1823. // we want to exercise. A unique label per call avoids the resolver cache.
  1824. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1825. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1826. std::to_string(n) + ".invalid";
  1827. }
  1828. } // namespace
  1829. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1830. if (!should_run_issue_2431_tests()) {
  1831. GTEST_SKIP()
  1832. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1833. }
  1834. for (int i = 0; i < 8; ++i) {
  1835. struct addrinfo hints;
  1836. memset(&hints, 0, sizeof(hints));
  1837. hints.ai_family = AF_UNSPEC;
  1838. hints.ai_socktype = SOCK_STREAM;
  1839. auto host = unique_unresolvable_host(i);
  1840. struct addrinfo *result = nullptr;
  1841. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1842. &result, /*timeout_sec=*/1);
  1843. if (rc == 0 && result) { freeaddrinfo(result); }
  1844. }
  1845. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1846. // stack region they still believe holds their gaicb.
  1847. std::this_thread::sleep_for(std::chrono::seconds(3));
  1848. }
  1849. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1850. if (!should_run_issue_2431_tests()) {
  1851. GTEST_SKIP()
  1852. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1853. }
  1854. std::atomic<bool> stop{false};
  1855. std::vector<std::thread> threads;
  1856. for (int t = 0; t < 8; ++t) {
  1857. threads.emplace_back([t, &stop] {
  1858. int i = 0;
  1859. while (!stop.load(std::memory_order_relaxed)) {
  1860. struct addrinfo hints;
  1861. memset(&hints, 0, sizeof(hints));
  1862. hints.ai_family = AF_UNSPEC;
  1863. hints.ai_socktype = SOCK_STREAM;
  1864. auto host = unique_unresolvable_host(t * 100000 + i++);
  1865. struct addrinfo *result = nullptr;
  1866. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1867. &result, /*timeout_sec=*/1);
  1868. if (rc == 0 && result) { freeaddrinfo(result); }
  1869. }
  1870. });
  1871. }
  1872. std::this_thread::sleep_for(std::chrono::seconds(8));
  1873. stop.store(true, std::memory_order_relaxed);
  1874. for (auto &th : threads) {
  1875. th.join();
  1876. }
  1877. std::this_thread::sleep_for(std::chrono::seconds(3));
  1878. }
  1879. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1880. if (!should_run_issue_2431_tests()) {
  1881. GTEST_SKIP()
  1882. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1883. }
  1884. std::atomic<bool> stop{false};
  1885. std::vector<std::thread> threads;
  1886. for (int t = 0; t < 8; ++t) {
  1887. threads.emplace_back([t, &stop] {
  1888. int i = 0;
  1889. while (!stop.load(std::memory_order_relaxed)) {
  1890. auto host = unique_unresolvable_host(t * 100000 + i++);
  1891. Client cli(host, 80);
  1892. cli.set_connection_timeout(1, 0);
  1893. cli.set_read_timeout(1, 0);
  1894. cli.set_write_timeout(1, 0);
  1895. (void)cli.Get("/");
  1896. }
  1897. });
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. stop.store(true, std::memory_order_relaxed);
  1901. for (auto &th : threads) {
  1902. th.join();
  1903. }
  1904. std::this_thread::sleep_for(std::chrono::seconds(3));
  1905. }
  1906. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1907. TEST(ConnectionErrorTest, InvalidHost) {
  1908. auto host = "-abcde.com";
  1909. #ifdef CPPHTTPLIB_SSL_ENABLED
  1910. auto port = 443;
  1911. SSLClient cli(host, port);
  1912. #else
  1913. auto port = 80;
  1914. Client cli(host, port);
  1915. #endif
  1916. cli.set_connection_timeout(std::chrono::seconds(2));
  1917. auto res = cli.Get("/");
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Connection, res.error());
  1920. }
  1921. TEST(ConnectionErrorTest, InvalidHost2) {
  1922. auto host = "httpcan.org/";
  1923. #ifdef CPPHTTPLIB_SSL_ENABLED
  1924. SSLClient cli(host);
  1925. #else
  1926. Client cli(host);
  1927. #endif
  1928. cli.set_connection_timeout(std::chrono::seconds(2));
  1929. auto res = cli.Get("/");
  1930. ASSERT_TRUE(!res);
  1931. EXPECT_EQ(Error::Connection, res.error());
  1932. }
  1933. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1934. auto host = "httpcan.org/";
  1935. #ifdef CPPHTTPLIB_SSL_ENABLED
  1936. SSLClient cli(host);
  1937. #else
  1938. Client cli(host);
  1939. #endif
  1940. cli.set_connection_timeout(std::chrono::seconds(2));
  1941. auto res = cli.Get("/");
  1942. ASSERT_TRUE(!res);
  1943. stringstream s;
  1944. s << "error code: " << res.error();
  1945. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1946. }
  1947. TEST(ConnectionErrorTest, InvalidPort) {
  1948. auto host = "localhost";
  1949. auto port = 44380;
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host, port);
  1952. #else
  1953. Client cli(host, port);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. EXPECT_TRUE(Error::Connection == res.error() ||
  1959. Error::ConnectionTimeout == res.error());
  1960. }
  1961. TEST(ConnectionErrorTest, Timeout_Online) {
  1962. auto host = "google.com";
  1963. #ifdef CPPHTTPLIB_SSL_ENABLED
  1964. auto port = 44380;
  1965. SSLClient cli(host, port);
  1966. #else
  1967. auto port = 8080;
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. // only probe one address type so that the error reason
  1972. // correlates to the timed-out IPv4, not the unsupported
  1973. // IPv6 connection attempt
  1974. cli.set_address_family(AF_INET);
  1975. auto res = cli.Get("/");
  1976. ASSERT_TRUE(!res);
  1977. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1978. }
  1979. TEST(CancelTest, NoCancel_Online) {
  1980. auto host = "httpbingo.org";
  1981. auto path = std::string{"/range/32"};
  1982. #ifdef CPPHTTPLIB_SSL_ENABLED
  1983. auto port = 443;
  1984. SSLClient cli(host, port);
  1985. #else
  1986. auto port = 80;
  1987. Client cli(host, port);
  1988. #endif
  1989. cli.set_connection_timeout(std::chrono::seconds(5));
  1990. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1992. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1993. EXPECT_EQ(StatusCode::OK_200, res->status);
  1994. }
  1995. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1996. // Use /bytes with a large payload so that the DownloadProgress callback
  1997. // (which only fires for Content-Length responses) is invoked before the
  1998. // entire body is received, giving cancellation a chance to fire.
  1999. auto host = "httpbingo.org";
  2000. auto path = std::string{"/bytes/524288"};
  2001. #ifdef CPPHTTPLIB_SSL_ENABLED
  2002. auto port = 443;
  2003. SSLClient cli(host, port);
  2004. #else
  2005. auto port = 80;
  2006. Client cli(host, port);
  2007. #endif
  2008. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2009. cli.set_connection_timeout(std::chrono::seconds(5));
  2010. ASSERT_TRUE(!res);
  2011. EXPECT_EQ(Error::Canceled, res.error());
  2012. }
  2013. TEST(CancelTest, WithCancelLargePayload_Online) {
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. cli.set_connection_timeout(std::chrono::seconds(5));
  2024. uint32_t count = 0;
  2025. auto res =
  2026. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2027. ASSERT_TRUE(!res);
  2028. EXPECT_EQ(Error::Canceled, res.error());
  2029. }
  2030. TEST(CancelTest, NoCancelPost) {
  2031. Server svr;
  2032. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2033. res.set_content("Hello World!", "text/plain");
  2034. });
  2035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2036. auto se = detail::scope_exit([&] {
  2037. svr.stop();
  2038. thread.join();
  2039. ASSERT_FALSE(svr.is_running());
  2040. });
  2041. svr.wait_until_ready();
  2042. Client cli(HOST, PORT);
  2043. cli.set_connection_timeout(std::chrono::seconds(5));
  2044. auto res =
  2045. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2046. "application/json", [](uint64_t, uint64_t) { return true; });
  2047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2048. EXPECT_EQ("Hello World!", res->body);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2052. Server svr;
  2053. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2054. res.set_content("Hello World!", "text/plain");
  2055. });
  2056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2057. auto se = detail::scope_exit([&] {
  2058. svr.stop();
  2059. thread.join();
  2060. ASSERT_FALSE(svr.is_running());
  2061. });
  2062. svr.wait_until_ready();
  2063. Client cli(HOST, PORT);
  2064. cli.set_connection_timeout(std::chrono::seconds(5));
  2065. auto res =
  2066. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2067. "application/json", [](uint64_t, uint64_t) { return false; });
  2068. ASSERT_TRUE(!res);
  2069. EXPECT_EQ(Error::Canceled, res.error());
  2070. }
  2071. TEST(CancelTest, WithCancelLargePayloadPost) {
  2072. Server svr;
  2073. svr.set_payload_max_length(200 * 1024 * 1024);
  2074. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2075. res.set_content(LARGE_DATA, "text/plain");
  2076. });
  2077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2078. auto se = detail::scope_exit([&] {
  2079. svr.stop();
  2080. thread.join();
  2081. ASSERT_FALSE(svr.is_running());
  2082. });
  2083. svr.wait_until_ready();
  2084. Client cli(HOST, PORT);
  2085. cli.set_payload_max_length(200 * 1024 * 1024);
  2086. cli.set_connection_timeout(std::chrono::seconds(5));
  2087. auto res =
  2088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2089. "application/json", [](uint64_t, uint64_t) { return false; });
  2090. ASSERT_TRUE(!res);
  2091. EXPECT_EQ(Error::Canceled, res.error());
  2092. }
  2093. TEST(CancelTest, NoCancelPut) {
  2094. Server svr;
  2095. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2096. res.set_content("Hello World!", "text/plain");
  2097. });
  2098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2099. auto se = detail::scope_exit([&] {
  2100. svr.stop();
  2101. thread.join();
  2102. ASSERT_FALSE(svr.is_running());
  2103. });
  2104. svr.wait_until_ready();
  2105. Client cli(HOST, PORT);
  2106. cli.set_connection_timeout(std::chrono::seconds(5));
  2107. auto res =
  2108. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2109. "application/json", [](uint64_t, uint64_t) { return true; });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. EXPECT_EQ("Hello World!", res->body);
  2112. EXPECT_EQ(StatusCode::OK_200, res->status);
  2113. }
  2114. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2115. Server svr;
  2116. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2117. res.set_content("Hello World!", "text/plain");
  2118. });
  2119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2120. auto se = detail::scope_exit([&] {
  2121. svr.stop();
  2122. thread.join();
  2123. ASSERT_FALSE(svr.is_running());
  2124. });
  2125. svr.wait_until_ready();
  2126. Client cli(HOST, PORT);
  2127. cli.set_connection_timeout(std::chrono::seconds(5));
  2128. auto res =
  2129. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2130. "application/json", [](uint64_t, uint64_t) { return false; });
  2131. ASSERT_TRUE(!res);
  2132. EXPECT_EQ(Error::Canceled, res.error());
  2133. }
  2134. TEST(CancelTest, WithCancelLargePayloadPut) {
  2135. Server svr;
  2136. svr.set_payload_max_length(200 * 1024 * 1024);
  2137. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2138. res.set_content(LARGE_DATA, "text/plain");
  2139. });
  2140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2141. auto se = detail::scope_exit([&] {
  2142. svr.stop();
  2143. thread.join();
  2144. ASSERT_FALSE(svr.is_running());
  2145. });
  2146. svr.wait_until_ready();
  2147. Client cli(HOST, PORT);
  2148. cli.set_payload_max_length(200 * 1024 * 1024);
  2149. cli.set_connection_timeout(std::chrono::seconds(5));
  2150. auto res =
  2151. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2152. "application/json", [](uint64_t, uint64_t) { return false; });
  2153. ASSERT_TRUE(!res);
  2154. EXPECT_EQ(Error::Canceled, res.error());
  2155. }
  2156. TEST(CancelTest, NoCancelPatch) {
  2157. Server svr;
  2158. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2159. res.set_content("Hello World!", "text/plain");
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. cli.set_connection_timeout(std::chrono::seconds(5));
  2170. auto res =
  2171. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2172. "application/json", [](uint64_t, uint64_t) { return true; });
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("Hello World!", res->body);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. }
  2177. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2178. Server svr;
  2179. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2180. res.set_content("Hello World!", "text/plain");
  2181. });
  2182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2183. auto se = detail::scope_exit([&] {
  2184. svr.stop();
  2185. thread.join();
  2186. ASSERT_FALSE(svr.is_running());
  2187. });
  2188. svr.wait_until_ready();
  2189. Client cli(HOST, PORT);
  2190. cli.set_connection_timeout(std::chrono::seconds(5));
  2191. auto res =
  2192. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2193. "application/json", [](uint64_t, uint64_t) { return false; });
  2194. ASSERT_TRUE(!res);
  2195. EXPECT_EQ(Error::Canceled, res.error());
  2196. }
  2197. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2198. Server svr;
  2199. svr.set_payload_max_length(200 * 1024 * 1024);
  2200. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2201. res.set_content(LARGE_DATA, "text/plain");
  2202. });
  2203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2204. auto se = detail::scope_exit([&] {
  2205. svr.stop();
  2206. thread.join();
  2207. ASSERT_FALSE(svr.is_running());
  2208. });
  2209. svr.wait_until_ready();
  2210. Client cli(HOST, PORT);
  2211. cli.set_payload_max_length(200 * 1024 * 1024);
  2212. cli.set_connection_timeout(std::chrono::seconds(5));
  2213. auto res =
  2214. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2215. "application/json", [](uint64_t, uint64_t) { return false; });
  2216. ASSERT_TRUE(!res);
  2217. EXPECT_EQ(Error::Canceled, res.error());
  2218. }
  2219. TEST(CancelTest, NoCancelDelete) {
  2220. Server svr;
  2221. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2222. res.set_content("Hello World!", "text/plain");
  2223. });
  2224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2225. auto se = detail::scope_exit([&] {
  2226. svr.stop();
  2227. thread.join();
  2228. ASSERT_FALSE(svr.is_running());
  2229. });
  2230. svr.wait_until_ready();
  2231. Client cli(HOST, PORT);
  2232. cli.set_connection_timeout(std::chrono::seconds(5));
  2233. auto res =
  2234. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2235. "application/json", [](uint64_t, uint64_t) { return true; });
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("Hello World!", res->body);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. }
  2240. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2241. Server svr;
  2242. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2243. res.set_content("Hello World!", "text/plain");
  2244. });
  2245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2246. auto se = detail::scope_exit([&] {
  2247. svr.stop();
  2248. thread.join();
  2249. ASSERT_FALSE(svr.is_running());
  2250. });
  2251. svr.wait_until_ready();
  2252. Client cli(HOST, PORT);
  2253. cli.set_connection_timeout(std::chrono::seconds(5));
  2254. auto res =
  2255. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2256. "application/json", [](uint64_t, uint64_t) { return false; });
  2257. ASSERT_TRUE(!res);
  2258. EXPECT_EQ(Error::Canceled, res.error());
  2259. }
  2260. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2261. Server svr;
  2262. svr.set_payload_max_length(200 * 1024 * 1024);
  2263. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2264. res.set_content(LARGE_DATA, "text/plain");
  2265. });
  2266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2267. auto se = detail::scope_exit([&] {
  2268. svr.stop();
  2269. thread.join();
  2270. ASSERT_FALSE(svr.is_running());
  2271. });
  2272. svr.wait_until_ready();
  2273. Client cli(HOST, PORT);
  2274. cli.set_payload_max_length(200 * 1024 * 1024);
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. auto res =
  2277. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2278. "application/json", [](uint64_t, uint64_t) { return false; });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. static std::string remove_whitespace(const std::string &input) {
  2283. std::string output;
  2284. output.reserve(input.size());
  2285. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2286. [](unsigned char c) { return !std::isspace(c); });
  2287. return output;
  2288. }
  2289. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2290. auto host = "httpbingo.org";
  2291. auto path = std::string{"/basic-auth/hello/world"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. {
  2300. auto res = cli.Get(path);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2303. }
  2304. {
  2305. auto res = cli.Get(
  2306. path, Headers{make_basic_authentication_header("hello", "world")});
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. auto body = remove_whitespace(res->body);
  2309. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2310. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2311. EXPECT_EQ(StatusCode::OK_200, res->status);
  2312. }
  2313. {
  2314. cli.set_basic_auth("hello", "world");
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. auto body = remove_whitespace(res->body);
  2318. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2319. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2320. EXPECT_EQ(StatusCode::OK_200, res->status);
  2321. }
  2322. {
  2323. cli.set_basic_auth("hello", "bad");
  2324. auto res = cli.Get(path);
  2325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2326. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("bad", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2333. }
  2334. }
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2337. auto host = "httpbingo.org";
  2338. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2339. auto paths = std::vector<std::string>{
  2340. "/digest-auth/auth/hello/world/MD5",
  2341. "/digest-auth/auth/hello/world/SHA-256",
  2342. };
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. {
  2346. auto res = cli.Get(unauth_path);
  2347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2349. }
  2350. {
  2351. cli.set_digest_auth("hello", "world");
  2352. for (const auto &path : paths) {
  2353. auto res = cli.Get(path.c_str());
  2354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2355. auto body = remove_whitespace(res->body);
  2356. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2357. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2358. EXPECT_EQ(StatusCode::OK_200, res->status);
  2359. }
  2360. cli.set_digest_auth("hello", "bad");
  2361. for (const auto &path : paths) {
  2362. auto res = cli.Get(path.c_str());
  2363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2364. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2365. }
  2366. }
  2367. }
  2368. #endif
  2369. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2370. auto host = "google.com";
  2371. auto another_host = "example.com";
  2372. auto wrong_ip = "0.0.0.0";
  2373. #ifdef CPPHTTPLIB_SSL_ENABLED
  2374. SSLClient cli(host);
  2375. #else
  2376. Client cli(host);
  2377. #endif
  2378. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2379. auto res = cli.Get("/");
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2382. }
  2383. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2384. auto host = "google.com";
  2385. auto wrong_ip = "0.0.0.0";
  2386. #ifdef CPPHTTPLIB_SSL_ENABLED
  2387. SSLClient cli(host);
  2388. #else
  2389. Client cli(host);
  2390. #endif
  2391. cli.set_hostname_addr_map({{host, wrong_ip}});
  2392. auto res = cli.Get("/");
  2393. ASSERT_TRUE(!res);
  2394. EXPECT_EQ(Error::Connection, res.error());
  2395. }
  2396. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2397. // A mapped value that is not an IP literal must be resolved. "localhost"
  2398. // resolves from the hosts file, so this test needs no external DNS.
  2399. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2400. auto host = "target.invalid";
  2401. Server svr;
  2402. std::string received_host;
  2403. svr.Get("/hi", [&](const Request &req, Response &res) {
  2404. received_host = req.get_header_value("Host");
  2405. res.set_content("Hello World!", "text/plain");
  2406. });
  2407. auto port = svr.bind_to_any_port(HOST);
  2408. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2409. auto se = detail::scope_exit([&] {
  2410. svr.stop();
  2411. thread.join();
  2412. ASSERT_FALSE(svr.is_running());
  2413. });
  2414. svr.wait_until_ready();
  2415. Client cli(host, port);
  2416. cli.set_hostname_addr_map({{host, HOST}});
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. // The mapping only redirects the connection; the identity stays host_.
  2421. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2422. }
  2423. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2424. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2425. auto host = "target.invalid";
  2426. Server svr;
  2427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. });
  2430. auto port = svr.bind_to_any_port("127.0.0.1");
  2431. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(host, port);
  2439. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2440. auto res = cli.Get("/hi");
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ(StatusCode::OK_200, res->status);
  2443. }
  2444. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2445. // An empty mapped value must leave host_ as the connection target. Without
  2446. // that guard the empty value would become the host argument, getaddrinfo
  2447. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2448. // loopback - silently connecting somewhere the caller never asked for.
  2449. // The server listens on loopback, so such a fallback would succeed and is
  2450. // therefore observable as a failure of this test.
  2451. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2452. Server svr;
  2453. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2454. res.set_content("Hello World!", "text/plain");
  2455. });
  2456. auto port = svr.bind_to_any_port(HOST);
  2457. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2458. auto se = detail::scope_exit([&] {
  2459. svr.stop();
  2460. thread.join();
  2461. ASSERT_FALSE(svr.is_running());
  2462. });
  2463. svr.wait_until_ready();
  2464. Client cli(blackhole, port);
  2465. cli.set_hostname_addr_map({{blackhole, ""}});
  2466. cli.set_connection_timeout(1);
  2467. auto res = cli.Get("/hi");
  2468. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2469. }
  2470. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2471. auto host = "httpbingo.org";
  2472. auto path = std::string{"/absolute-redirect/3"};
  2473. #ifdef CPPHTTPLIB_SSL_ENABLED
  2474. SSLClient cli(host);
  2475. #else
  2476. Client cli(host);
  2477. #endif
  2478. cli.set_follow_location(true);
  2479. auto res = cli.Get(path);
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. EXPECT_EQ(StatusCode::OK_200, res->status);
  2482. }
  2483. TEST(RedirectTest, Redirect_Online) {
  2484. auto host = "httpbingo.org";
  2485. auto path = std::string{"/redirect/3"};
  2486. #ifdef CPPHTTPLIB_SSL_ENABLED
  2487. SSLClient cli(host);
  2488. #else
  2489. Client cli(host);
  2490. #endif
  2491. cli.set_follow_location(true);
  2492. auto res = cli.Get(path);
  2493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2494. EXPECT_EQ(StatusCode::OK_200, res->status);
  2495. }
  2496. TEST(RelativeRedirectTest, Redirect_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/relative-redirect/3"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. SSLClient cli(host);
  2501. #else
  2502. Client cli(host);
  2503. #endif
  2504. cli.set_follow_location(true);
  2505. auto res = cli.Get(path);
  2506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2507. EXPECT_EQ(StatusCode::OK_200, res->status);
  2508. }
  2509. TEST(TooManyRedirectTest, Redirect_Online) {
  2510. auto host = "httpbingo.org";
  2511. auto path = std::string{"/redirect/21"};
  2512. #ifdef CPPHTTPLIB_SSL_ENABLED
  2513. SSLClient cli(host);
  2514. #else
  2515. Client cli(host);
  2516. #endif
  2517. cli.set_follow_location(true);
  2518. auto res = cli.Get(path);
  2519. ASSERT_TRUE(!res);
  2520. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2521. }
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. TEST(YahooRedirectTest, Redirect_Online) {
  2524. Client cli("yahoo.com");
  2525. auto res = cli.Get("/");
  2526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2527. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2528. cli.set_follow_location(true);
  2529. res = cli.Get("/");
  2530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2531. EXPECT_EQ(StatusCode::OK_200, res->status);
  2532. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2533. }
  2534. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2535. #define REDIR_HOST "httpbingo.org"
  2536. #define REDIR_PATH "/redirect-to"
  2537. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2538. SSLClient cli(REDIR_HOST);
  2539. cli.set_follow_location(true);
  2540. auto res =
  2541. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. }
  2545. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2546. SSLClient cli(REDIR_HOST);
  2547. cli.set_follow_location(true);
  2548. Params params;
  2549. params.emplace("url", "http://example.com");
  2550. params.emplace("status_code", "302");
  2551. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2556. SSLClient cli(REDIR_HOST);
  2557. cli.set_follow_location(true);
  2558. Params params;
  2559. params.emplace("url", "http://example.com");
  2560. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. TEST(UrlWithSpace, Redirect_Online) {
  2565. SSLClient cli("edge.forgecdn.net");
  2566. cli.set_follow_location(true);
  2567. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ(StatusCode::OK_200, res->status);
  2570. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2571. }
  2572. #endif
  2573. #if !defined(_WIN32) && !defined(_WIN64)
  2574. TEST(ReceiveSignals, Signal) {
  2575. auto setupSignalHandlers = []() {
  2576. struct sigaction act;
  2577. sigemptyset(&act.sa_mask);
  2578. act.sa_flags = SA_SIGINFO;
  2579. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2580. switch (sig) {
  2581. case SIGINT:
  2582. default: break;
  2583. }
  2584. };
  2585. ::sigaction(SIGINT, &act, nullptr);
  2586. };
  2587. Server svr;
  2588. int port = 0;
  2589. auto thread = std::thread([&]() {
  2590. setupSignalHandlers();
  2591. port = svr.bind_to_any_port(HOST);
  2592. svr.listen_after_bind();
  2593. });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. ASSERT_TRUE(svr.is_running());
  2601. pthread_kill(thread.native_handle(), SIGINT);
  2602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2603. ASSERT_TRUE(svr.is_running());
  2604. }
  2605. #endif
  2606. TEST(RedirectToDifferentPort, Redirect) {
  2607. Server svr1;
  2608. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2609. res.set_content("Hello World!", "text/plain");
  2610. });
  2611. int svr1_port = 0;
  2612. auto thread1 = std::thread([&]() {
  2613. svr1_port = svr1.bind_to_any_port(HOST);
  2614. svr1.listen_after_bind();
  2615. });
  2616. Server svr2;
  2617. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2618. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2619. });
  2620. int svr2_port = 0;
  2621. auto thread2 = std::thread([&]() {
  2622. svr2_port = svr2.bind_to_any_port(HOST);
  2623. svr2.listen_after_bind();
  2624. });
  2625. auto se = detail::scope_exit([&] {
  2626. svr2.stop();
  2627. thread2.join();
  2628. svr1.stop();
  2629. thread1.join();
  2630. ASSERT_FALSE(svr2.is_running());
  2631. ASSERT_FALSE(svr1.is_running());
  2632. });
  2633. svr1.wait_until_ready();
  2634. svr2.wait_until_ready();
  2635. Client cli("localhost", svr2_port);
  2636. cli.set_follow_location(true);
  2637. auto res = cli.Get("/2");
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. }
  2642. static void
  2643. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2644. Server svr1;
  2645. std::string captured_authorization;
  2646. svr1.Get("/target", [&](const Request &req, Response &res) {
  2647. captured_authorization = req.get_header_value("Authorization");
  2648. res.set_content("OK", "text/plain");
  2649. });
  2650. int svr1_port = 0;
  2651. auto thread1 = std::thread([&]() {
  2652. svr1_port = svr1.bind_to_any_port(HOST);
  2653. svr1.listen_after_bind();
  2654. });
  2655. Server svr2;
  2656. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2657. res.set_redirect(
  2658. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2659. });
  2660. int svr2_port = 0;
  2661. auto thread2 = std::thread([&]() {
  2662. svr2_port = svr2.bind_to_any_port(HOST);
  2663. svr2.listen_after_bind();
  2664. });
  2665. auto se = detail::scope_exit([&] {
  2666. svr2.stop();
  2667. thread2.join();
  2668. svr1.stop();
  2669. thread1.join();
  2670. ASSERT_FALSE(svr2.is_running());
  2671. ASSERT_FALSE(svr1.is_running());
  2672. });
  2673. svr1.wait_until_ready();
  2674. svr2.wait_until_ready();
  2675. Client cli("localhost", svr2_port);
  2676. cli.set_follow_location(true);
  2677. set_auth(cli);
  2678. auto res = cli.Get("/redir");
  2679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2680. EXPECT_EQ(StatusCode::OK_200, res->status);
  2681. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2682. EXPECT_TRUE(captured_authorization.empty());
  2683. }
  2684. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2685. TestDoNotForwardCredentialsOnRedirect(
  2686. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2687. }
  2688. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2689. TestDoNotForwardCredentialsOnRedirect(
  2690. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2691. }
  2692. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2693. Server svr1;
  2694. std::string captured_cookie;
  2695. bool target_hit = false;
  2696. svr1.Get("/target", [&](const Request &req, Response &res) {
  2697. captured_cookie = req.get_header_value("Cookie");
  2698. target_hit = true;
  2699. res.set_content("OK", "text/plain");
  2700. });
  2701. int svr1_port = 0;
  2702. auto thread1 = std::thread([&]() {
  2703. svr1_port = svr1.bind_to_any_port(HOST);
  2704. svr1.listen_after_bind();
  2705. });
  2706. Server svr2;
  2707. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2708. res.set_redirect(
  2709. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2710. });
  2711. int svr2_port = 0;
  2712. auto thread2 = std::thread([&]() {
  2713. svr2_port = svr2.bind_to_any_port(HOST);
  2714. svr2.listen_after_bind();
  2715. });
  2716. auto se = detail::scope_exit([&] {
  2717. svr2.stop();
  2718. thread2.join();
  2719. svr1.stop();
  2720. thread1.join();
  2721. ASSERT_FALSE(svr2.is_running());
  2722. ASSERT_FALSE(svr1.is_running());
  2723. });
  2724. svr1.wait_until_ready();
  2725. svr2.wait_until_ready();
  2726. Client cli("localhost", svr2_port);
  2727. cli.set_follow_location(true);
  2728. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2729. auto res = cli.Get("/redir", headers);
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ(StatusCode::OK_200, res->status);
  2732. EXPECT_TRUE(target_hit);
  2733. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2734. EXPECT_TRUE(captured_cookie.empty());
  2735. }
  2736. TEST(RedirectToSamePort, ForwardCookie) {
  2737. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2738. // header so that ordinary session flows keep working.
  2739. Server svr;
  2740. std::string captured_cookie;
  2741. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2742. res.set_redirect("/target", 302);
  2743. });
  2744. svr.Get("/target", [&](const Request &req, Response &res) {
  2745. captured_cookie = req.get_header_value("Cookie");
  2746. res.set_content("OK", "text/plain");
  2747. });
  2748. auto port = svr.bind_to_any_port(HOST);
  2749. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, port);
  2757. cli.set_follow_location(true);
  2758. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2759. auto res = cli.Get("/redir", headers);
  2760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2763. }
  2764. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2765. Server svr;
  2766. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2767. // Port number that overflows int — should not crash
  2768. res.set_redirect("http://localhost:99999999999999999999/target");
  2769. });
  2770. auto port = svr.bind_to_any_port(HOST);
  2771. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2772. auto se = detail::scope_exit([&] {
  2773. svr.stop();
  2774. thread.join();
  2775. ASSERT_FALSE(svr.is_running());
  2776. });
  2777. svr.wait_until_ready();
  2778. Client cli(HOST, port);
  2779. cli.set_follow_location(true);
  2780. auto res = cli.Get("/redir");
  2781. // Should fail gracefully, not crash (no valid response due to bad port)
  2782. EXPECT_FALSE(res);
  2783. }
  2784. TEST(RedirectFromPageWithContent, Redirect) {
  2785. Server svr;
  2786. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("___", "text/plain");
  2788. res.set_redirect("/2");
  2789. });
  2790. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!", "text/plain");
  2792. });
  2793. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. th.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. {
  2801. Client cli("localhost", PORT);
  2802. cli.set_follow_location(true);
  2803. std::string body;
  2804. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2805. body.append(data, data_length);
  2806. return true;
  2807. });
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(StatusCode::OK_200, res->status);
  2810. EXPECT_EQ("Hello World!", body);
  2811. }
  2812. {
  2813. Client cli("localhost", PORT);
  2814. std::string body;
  2815. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2816. body.append(data, data_length);
  2817. return true;
  2818. });
  2819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2820. EXPECT_EQ(StatusCode::Found_302, res->status);
  2821. EXPECT_EQ("___", body);
  2822. }
  2823. }
  2824. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2825. Server svr;
  2826. auto port_str = std::to_string(PORT);
  2827. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2828. auto expected_host = "[::1]:" + port_str;
  2829. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2830. res.set_content("___", "text/plain");
  2831. // res.set_redirect("/2");
  2832. res.set_redirect(redirect_url);
  2833. });
  2834. svr.Get("/2", [&](const Request &req, Response &res) {
  2835. auto host_header = req.headers.find("Host");
  2836. ASSERT_TRUE(host_header != req.headers.end());
  2837. EXPECT_EQ(expected_host, host_header->second);
  2838. res.set_content("Hello World!", "text/plain");
  2839. });
  2840. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2841. auto se = detail::scope_exit([&] {
  2842. svr.stop();
  2843. th.join();
  2844. ASSERT_FALSE(svr.is_running());
  2845. });
  2846. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2847. // actually starts anything, so the condition !svr.is_running() will
  2848. // always remain true, and the loop never stops.
  2849. // This basically counts how many milliseconds have passed since the
  2850. // call to svr.listen(), and if after 5 seconds nothing started yet
  2851. // aborts the test.
  2852. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2853. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2854. ASSERT_LT(milliseconds, 5000U);
  2855. }
  2856. {
  2857. Client cli("::1", PORT);
  2858. cli.set_follow_location(true);
  2859. std::string body;
  2860. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2861. body.append(data, data_length);
  2862. return true;
  2863. });
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. EXPECT_EQ("Hello World!", body);
  2867. }
  2868. {
  2869. Client cli("::1", PORT);
  2870. std::string body;
  2871. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Found_302, res->status);
  2877. EXPECT_EQ("___", body);
  2878. }
  2879. }
  2880. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2881. Server svr;
  2882. svr.Get("/foo", [](const Request &req, Response &res) {
  2883. auto a = req.params.find("a");
  2884. if (a != req.params.end()) {
  2885. res.set_content((*a).second, "text/plain");
  2886. res.status = StatusCode::OK_200;
  2887. } else {
  2888. res.status = StatusCode::BadRequest_400;
  2889. }
  2890. });
  2891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2892. auto se = detail::scope_exit([&] {
  2893. svr.stop();
  2894. thread.join();
  2895. ASSERT_FALSE(svr.is_running());
  2896. });
  2897. svr.wait_until_ready();
  2898. {
  2899. Client cli(HOST, PORT);
  2900. cli.set_path_encode(false);
  2901. auto res = cli.Get("/foo?a=explicitly+encoded");
  2902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. // This expects it back with a space, as the `+` won't have been
  2905. // url-encoded, and server-side the params get decoded turning `+`
  2906. // into spaces.
  2907. EXPECT_EQ("explicitly encoded", res->body);
  2908. }
  2909. }
  2910. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2911. // When path encoding is disabled the client must transmit the supplied
  2912. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2913. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2914. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2915. // than a space (0x20). Assert on the raw wire target to catch this.
  2916. Server svr;
  2917. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2918. svr.Get("/foo", [&](const Request &req, Response &res) {
  2919. EXPECT_EQ(expected_target, req.target);
  2920. res.status = StatusCode::OK_200;
  2921. });
  2922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2923. auto se = detail::scope_exit([&] {
  2924. svr.stop();
  2925. thread.join();
  2926. ASSERT_FALSE(svr.is_running());
  2927. });
  2928. svr.wait_until_ready();
  2929. {
  2930. Client cli(HOST, PORT);
  2931. cli.set_path_encode(false);
  2932. auto res = cli.Get(expected_target.c_str());
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. }
  2936. }
  2937. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2938. // `open_stream()` used to skip the path encoding that the buffered send
  2939. // path applies, so the same `path` produced different bytes in the request
  2940. // line depending on which API was used. Assert the two agree.
  2941. Server svr;
  2942. std::string target;
  2943. svr.Get(".*", [&](const Request &req, Response &res) {
  2944. target = req.target;
  2945. res.status = StatusCode::OK_200;
  2946. });
  2947. auto port = svr.bind_to_any_port(HOST);
  2948. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2949. auto se = detail::scope_exit([&] {
  2950. svr.stop();
  2951. thread.join();
  2952. ASSERT_FALSE(svr.is_running());
  2953. });
  2954. svr.wait_until_ready();
  2955. struct {
  2956. const char *path;
  2957. const char *expected;
  2958. } cases[] = {
  2959. {"/a b?x=1", "/a%20b?x=1"},
  2960. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2961. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2962. };
  2963. for (const auto &c : cases) {
  2964. Client cli(HOST, port);
  2965. target.clear();
  2966. auto res = cli.Get(c.path);
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2969. auto buffered_target = target;
  2970. target.clear();
  2971. auto handle = cli.open_stream("GET", c.path);
  2972. EXPECT_TRUE(handle.is_valid())
  2973. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2974. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2975. }
  2976. }
  2977. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2978. // The `set_path_encode(false)` contract — transmit the supplied target
  2979. // verbatim — must hold for the streaming API too.
  2980. Server svr;
  2981. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2982. std::string target;
  2983. svr.Get("/foo", [&](const Request &req, Response &res) {
  2984. target = req.target;
  2985. res.status = StatusCode::OK_200;
  2986. });
  2987. auto port = svr.bind_to_any_port(HOST);
  2988. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2989. auto se = detail::scope_exit([&] {
  2990. svr.stop();
  2991. thread.join();
  2992. ASSERT_FALSE(svr.is_running());
  2993. });
  2994. svr.wait_until_ready();
  2995. {
  2996. Client cli(HOST, port);
  2997. cli.set_path_encode(false);
  2998. auto handle = cli.open_stream("GET", expected_target);
  2999. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3000. EXPECT_EQ(expected_target, target);
  3001. }
  3002. }
  3003. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3004. // With path encoding enabled a CR/LF in the target is percent-encoded
  3005. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3006. // write_request_line still backstops `set_path_encode(false)`, which is
  3007. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3008. Server svr;
  3009. // Captured before routing: the decoded path contains a newline, which a
  3010. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3011. std::string target;
  3012. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3013. target = req.target;
  3014. res.status = StatusCode::OK_200;
  3015. return Server::HandlerResponse::Handled;
  3016. });
  3017. auto port = svr.bind_to_any_port(HOST);
  3018. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3019. auto se = detail::scope_exit([&] {
  3020. svr.stop();
  3021. thread.join();
  3022. ASSERT_FALSE(svr.is_running());
  3023. });
  3024. svr.wait_until_ready();
  3025. {
  3026. Client cli(HOST, port);
  3027. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3028. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3029. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3033. // Nothing may reach the wire: a raw CR/LF target would split the request
  3034. // line and inject headers.
  3035. Server svr;
  3036. // Pre-routing so that "not called" means nothing reached the server at all,
  3037. // rather than merely failing to match a handler pattern.
  3038. auto handler_called = false;
  3039. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3040. handler_called = true;
  3041. res.status = StatusCode::OK_200;
  3042. return Server::HandlerResponse::Handled;
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. thread.join();
  3049. ASSERT_FALSE(svr.is_running());
  3050. });
  3051. svr.wait_until_ready();
  3052. {
  3053. Client cli(HOST, port);
  3054. cli.set_path_encode(false);
  3055. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3056. EXPECT_FALSE(handle.is_valid());
  3057. EXPECT_EQ(Error::Write, handle.error);
  3058. EXPECT_FALSE(handler_called);
  3059. }
  3060. }
  3061. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3062. // Which of the two branches runs is decided by whether the query component
  3063. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3064. // an empty query and must still fall back to building one from
  3065. // `req.params`, while a non-empty query must win over `req.params`.
  3066. Server svr;
  3067. std::string target;
  3068. svr.Get("/foo", [&](const Request &req, Response &res) {
  3069. target = req.target;
  3070. res.status = StatusCode::OK_200;
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. thread.join();
  3077. ASSERT_FALSE(svr.is_running());
  3078. });
  3079. svr.wait_until_ready();
  3080. {
  3081. // Trailing `?` -> empty query component -> `req.params` is used.
  3082. Client cli(HOST, port);
  3083. Request req;
  3084. req.method = "GET";
  3085. req.path = "/foo?";
  3086. req.params.emplace("a", "1");
  3087. target.clear();
  3088. auto res = cli.send(req);
  3089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3090. EXPECT_EQ("/foo?a=1", target);
  3091. }
  3092. {
  3093. // Non-empty query in `req.path` -> `req.params` is not appended.
  3094. Client cli(HOST, port);
  3095. Request req;
  3096. req.method = "GET";
  3097. req.path = "/foo?b=2";
  3098. req.params.emplace("a", "1");
  3099. target.clear();
  3100. auto res = cli.send(req);
  3101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3102. EXPECT_EQ("/foo?b=2", target);
  3103. }
  3104. }
  3105. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3106. Server svr;
  3107. svr.Get("/", [](const Request &req, Response &) {
  3108. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3109. });
  3110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. {
  3118. Client cli(HOST, PORT);
  3119. cli.set_path_encode(false);
  3120. auto res = cli.Get("/?something=%0A");
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. EXPECT_EQ(StatusCode::OK_200, res->status);
  3123. }
  3124. }
  3125. TEST(BindServerTest, BindDualStack) {
  3126. Server svr;
  3127. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3128. res.set_content("Hello World!", "text/plain");
  3129. });
  3130. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3131. auto se = detail::scope_exit([&] {
  3132. svr.stop();
  3133. thread.join();
  3134. ASSERT_FALSE(svr.is_running());
  3135. });
  3136. svr.wait_until_ready();
  3137. {
  3138. Client cli("127.0.0.1", PORT);
  3139. auto res = cli.Get("/1");
  3140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. }
  3144. {
  3145. Client cli("::1", PORT);
  3146. auto res = cli.Get("/1");
  3147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3148. EXPECT_EQ(StatusCode::OK_200, res->status);
  3149. EXPECT_EQ("Hello World!", res->body);
  3150. }
  3151. }
  3152. TEST(BindServerTest, BindAndListenSeparately) {
  3153. Server svr;
  3154. int port = svr.bind_to_any_port("0.0.0.0");
  3155. ASSERT_TRUE(svr.is_valid());
  3156. ASSERT_TRUE(port > 0);
  3157. svr.stop();
  3158. }
  3159. // Reports whether anything is still listening on a loopback port. A plain
  3160. // connect() is used instead of a Client request because a socket left bound by
  3161. // mistake accepts the connection into its backlog and never answers, which
  3162. // would hang the test instead of failing it.
  3163. static bool is_loopback_port_accepting(int port) {
  3164. sockaddr_in addr{};
  3165. addr.sin_family = AF_INET;
  3166. addr.sin_port = htons(static_cast<uint16_t>(port));
  3167. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3168. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3169. EXPECT_NE(sock, INVALID_SOCKET);
  3170. if (sock == INVALID_SOCKET) { return false; }
  3171. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3172. static_cast<socklen_t>(sizeof(addr)));
  3173. detail::close_socket(sock);
  3174. return ret == 0;
  3175. }
  3176. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3177. Server svr;
  3178. auto port = svr.bind_to_any_port("127.0.0.1");
  3179. ASSERT_TRUE(port > 0);
  3180. svr.stop();
  3181. // bind_to_any_port() already called listen(2), so until stop() closed the
  3182. // descriptor the port kept accepting connections into the backlog. ASSERT
  3183. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3184. // below blocks forever in the accept loop.
  3185. ASSERT_FALSE(is_loopback_port_accepting(port));
  3186. // Nothing is left to accept on, so listen_after_bind() must report failure
  3187. // instead of returning success without ever serving.
  3188. EXPECT_FALSE(svr.listen_after_bind());
  3189. // The failed listen marks the server decommissioned, so a waiter returns
  3190. // instead of spinning forever.
  3191. svr.wait_until_ready();
  3192. }
  3193. #ifdef CPPHTTPLIB_SSL_ENABLED
  3194. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3196. CLIENT_CA_CERT_DIR);
  3197. int port = svr.bind_to_any_port("0.0.0.0");
  3198. ASSERT_TRUE(svr.is_valid());
  3199. ASSERT_TRUE(port > 0);
  3200. svr.stop();
  3201. }
  3202. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3203. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3204. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3205. int port = svr.bind_to_any_port("0.0.0.0");
  3206. ASSERT_TRUE(svr.is_valid());
  3207. ASSERT_TRUE(port > 0);
  3208. svr.stop();
  3209. }
  3210. TEST(BindServerTest, UpdateCertsPem) {
  3211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. // Read PEM files
  3216. std::string cert_pem, key_pem, ca_pem;
  3217. read_file(SERVER_CERT_FILE, cert_pem);
  3218. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3219. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3220. // Update server certificates using PEM API
  3221. ASSERT_TRUE(
  3222. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3223. ASSERT_TRUE(svr.is_valid());
  3224. svr.stop();
  3225. }
  3226. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3227. // Start server with client CA (enables client auth)
  3228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3229. ASSERT_TRUE(svr.is_valid());
  3230. bool handler_called = false;
  3231. svr.Get("/test", [&](const Request &req, Response &res) {
  3232. handler_called = true;
  3233. // Verify client certificate is present
  3234. auto cert = req.peer_cert();
  3235. EXPECT_TRUE(static_cast<bool>(cert));
  3236. res.set_content("ok", "text/plain");
  3237. });
  3238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3239. auto se = detail::scope_exit([&] {
  3240. svr.stop();
  3241. t.join();
  3242. ASSERT_FALSE(svr.is_running());
  3243. });
  3244. svr.wait_until_ready();
  3245. // Read PEM files
  3246. std::string cert_pem, key_pem, ca_pem;
  3247. read_file(SERVER_CERT_FILE, cert_pem);
  3248. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3249. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3250. // Update server certificates and client CA using PEM API while server running
  3251. ASSERT_TRUE(
  3252. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3253. // Connect with client certificate
  3254. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3255. cli.enable_server_certificate_verification(false);
  3256. cli.set_connection_timeout(30);
  3257. auto res = cli.Get("/test");
  3258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. ASSERT_TRUE(handler_called);
  3261. EXPECT_EQ("ok", res->body);
  3262. }
  3263. #endif
  3264. TEST(ErrorHandlerTest, ContentLength) {
  3265. Server svr;
  3266. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3267. res.status = StatusCode::OK_200;
  3268. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3269. "text/html"); // <= Content-Length still 13
  3270. });
  3271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3272. res.set_content("Hello World!\n", "text/plain");
  3273. res.status = 524;
  3274. });
  3275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3276. auto se = detail::scope_exit([&] {
  3277. svr.stop();
  3278. thread.join();
  3279. ASSERT_FALSE(svr.is_running());
  3280. });
  3281. svr.wait_until_ready();
  3282. {
  3283. Client cli(HOST, PORT);
  3284. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3288. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3289. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3290. }
  3291. }
  3292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3293. TEST(ExceptionTest, WithoutExceptionHandler) {
  3294. Server svr;
  3295. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3296. throw std::runtime_error("exception...");
  3297. });
  3298. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3299. throw std::runtime_error("exception\r\n...");
  3300. });
  3301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3302. auto se = detail::scope_exit([&] {
  3303. svr.stop();
  3304. listen_thread.join();
  3305. ASSERT_FALSE(svr.is_running());
  3306. });
  3307. svr.wait_until_ready();
  3308. Client cli("localhost", PORT);
  3309. {
  3310. auto res = cli.Get("/exception");
  3311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3313. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3314. }
  3315. {
  3316. auto res = cli.Get("/unknown");
  3317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3319. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3320. }
  3321. }
  3322. TEST(ExceptionTest, WithExceptionHandler) {
  3323. Server svr;
  3324. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3325. std::exception_ptr ep) {
  3326. EXPECT_FALSE(ep == nullptr);
  3327. try {
  3328. std::rethrow_exception(ep);
  3329. } catch (std::exception &e) {
  3330. EXPECT_EQ("abc", std::string(e.what()));
  3331. } catch (...) {}
  3332. res.status = StatusCode::InternalServerError_500;
  3333. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3334. "text/html"); // <= Content-Length still 13 at this point
  3335. });
  3336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3337. res.set_content("Hello World!\n", "text/plain");
  3338. throw std::runtime_error("abc");
  3339. });
  3340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. for (size_t i = 0; i < 10; i++) {
  3348. Client cli(HOST, PORT);
  3349. for (size_t j = 0; j < 100; j++) {
  3350. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3352. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3353. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3354. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3355. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3356. }
  3357. cli.set_keep_alive(true);
  3358. for (size_t j = 0; j < 100; j++) {
  3359. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3361. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3363. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3364. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3365. }
  3366. }
  3367. }
  3368. TEST(ExceptionTest, AndErrorHandler) {
  3369. Server svr;
  3370. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3371. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3372. });
  3373. svr.set_exception_handler(
  3374. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3375. EXPECT_FALSE(ep == nullptr);
  3376. try {
  3377. std::rethrow_exception(ep);
  3378. } catch (std::exception &e) {
  3379. res.set_content(e.what(), "text/html");
  3380. } catch (...) {}
  3381. res.status = StatusCode::InternalServerError_500;
  3382. });
  3383. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3384. throw std::runtime_error("EXCEPTION");
  3385. });
  3386. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3387. res.set_content("ERROR", "text/html");
  3388. res.status = StatusCode::InternalServerError_500;
  3389. });
  3390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3391. auto se = detail::scope_exit([&] {
  3392. svr.stop();
  3393. thread.join();
  3394. ASSERT_FALSE(svr.is_running());
  3395. });
  3396. svr.wait_until_ready();
  3397. Client cli(HOST, PORT);
  3398. {
  3399. auto res = cli.Get("/exception");
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3402. EXPECT_EQ("EXCEPTION", res->body);
  3403. }
  3404. {
  3405. auto res = cli.Get("/error");
  3406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3407. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3408. EXPECT_EQ("ERROR", res->body);
  3409. }
  3410. {
  3411. auto res = cli.Get("/invalid");
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3414. EXPECT_EQ("NOT_FOUND", res->body);
  3415. }
  3416. }
  3417. #endif
  3418. TEST(NoContentTest, ContentLength) {
  3419. Server svr;
  3420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3421. res.status = StatusCode::NoContent_204;
  3422. });
  3423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. thread.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli(HOST, PORT);
  3432. auto res = cli.Get("/hi");
  3433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3434. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3435. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3436. }
  3437. }
  3438. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3441. ASSERT_TRUE(svr.is_valid());
  3442. #else
  3443. Server svr;
  3444. #endif
  3445. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3446. if (req.path == "/routing_handler") {
  3447. res.set_header("PRE_ROUTING", "on");
  3448. res.set_content("Routing Handler", "text/plain");
  3449. return httplib::Server::HandlerResponse::Handled;
  3450. }
  3451. return httplib::Server::HandlerResponse::Unhandled;
  3452. });
  3453. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3454. res.set_content("Error", "text/html");
  3455. });
  3456. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3457. if (req.path == "/routing_handler") {
  3458. res.set_header("POST_ROUTING", "on");
  3459. }
  3460. });
  3461. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3462. res.set_content("Hello World!\n", "text/plain");
  3463. });
  3464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3465. auto se = detail::scope_exit([&] {
  3466. svr.stop();
  3467. thread.join();
  3468. ASSERT_FALSE(svr.is_running());
  3469. });
  3470. svr.wait_until_ready();
  3471. {
  3472. #ifdef CPPHTTPLIB_SSL_ENABLED
  3473. SSLClient cli(HOST, PORT);
  3474. cli.enable_server_certificate_verification(false);
  3475. #else
  3476. Client cli(HOST, PORT);
  3477. #endif
  3478. auto res = cli.Get("/routing_handler");
  3479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3480. EXPECT_EQ(StatusCode::OK_200, res->status);
  3481. EXPECT_EQ("Routing Handler", res->body);
  3482. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3483. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3484. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3485. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3486. }
  3487. {
  3488. #ifdef CPPHTTPLIB_SSL_ENABLED
  3489. SSLClient cli(HOST, PORT);
  3490. cli.enable_server_certificate_verification(false);
  3491. #else
  3492. Client cli(HOST, PORT);
  3493. #endif
  3494. auto res = cli.Get("/hi");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("Hello World!\n", res->body);
  3498. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3499. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3500. }
  3501. {
  3502. #ifdef CPPHTTPLIB_SSL_ENABLED
  3503. SSLClient cli(HOST, PORT);
  3504. cli.enable_server_certificate_verification(false);
  3505. #else
  3506. Client cli(HOST, PORT);
  3507. #endif
  3508. auto res = cli.Get("/aaa");
  3509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3511. EXPECT_EQ("Error", res->body);
  3512. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3513. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3514. }
  3515. }
  3516. TEST(RequestHandlerTest, PreRequestHandler) {
  3517. auto route_path = "/user/:user";
  3518. Server svr;
  3519. svr.Get("/hi", [](const Request &, Response &res) {
  3520. res.set_content("hi", "text/plain");
  3521. });
  3522. svr.Get(route_path, [](const Request &req, Response &res) {
  3523. res.set_content(req.path_params.at("user"), "text/plain");
  3524. });
  3525. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3526. if (req.matched_route == route_path) {
  3527. auto user = req.path_params.at("user");
  3528. if (user != "john") {
  3529. res.status = StatusCode::Forbidden_403;
  3530. res.set_content("error", "text/html");
  3531. return Server::HandlerResponse::Handled;
  3532. }
  3533. }
  3534. return Server::HandlerResponse::Unhandled;
  3535. });
  3536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, PORT);
  3544. {
  3545. auto res = cli.Get("/hi");
  3546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3547. EXPECT_EQ(StatusCode::OK_200, res->status);
  3548. EXPECT_EQ("hi", res->body);
  3549. }
  3550. {
  3551. auto res = cli.Get("/user/john");
  3552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. EXPECT_EQ("john", res->body);
  3555. }
  3556. {
  3557. auto res = cli.Get("/user/invalid-user");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3560. EXPECT_EQ("error", res->body);
  3561. }
  3562. }
  3563. // The pre-request handler must run before the request body is read, so a
  3564. // rejected request never forces the server to buffer a (potentially large)
  3565. // body. Here the posted body is larger than the payload limit: if the body
  3566. // were read first the server would answer 413, but because the pre-request
  3567. // handler runs first it answers 403 and the body is never read.
  3568. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3569. Server svr;
  3570. svr.set_payload_max_length(8);
  3571. auto handler_ran = false;
  3572. svr.Post("/reject", [&](const Request &req, Response &res) {
  3573. handler_ran = true;
  3574. res.set_content(req.body, "text/plain");
  3575. });
  3576. svr.Post("/accept", [](const Request &req, Response &res) {
  3577. res.set_content(req.body, "text/plain");
  3578. });
  3579. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3580. if (req.matched_route == "/reject") {
  3581. res.status = StatusCode::Forbidden_403;
  3582. res.set_content("denied", "text/plain");
  3583. return Server::HandlerResponse::Handled;
  3584. }
  3585. return Server::HandlerResponse::Unhandled;
  3586. });
  3587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. thread.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. svr.wait_until_ready();
  3594. Client cli(HOST, PORT);
  3595. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3596. // rejects with 403 before the body is read, so 413 is never reached.
  3597. {
  3598. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3600. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3601. EXPECT_EQ("denied", res->body);
  3602. EXPECT_FALSE(handler_ran);
  3603. }
  3604. // An approved route still reads the body and enforces the payload limit.
  3605. {
  3606. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3609. }
  3610. }
  3611. TEST(UserDataTest, BasicOperations) {
  3612. httplib::UserData ud;
  3613. // Initially empty
  3614. EXPECT_FALSE(ud.has("key"));
  3615. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3616. // set and get
  3617. ud.set("key", 42);
  3618. EXPECT_TRUE(ud.has("key"));
  3619. auto *p = ud.get<int>("key");
  3620. ASSERT_NE(nullptr, p);
  3621. EXPECT_EQ(42, *p);
  3622. // Type mismatch → nullptr
  3623. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3624. // Overwrite with different type
  3625. ud.set("key", std::string("hello"));
  3626. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3627. auto *s = ud.get<std::string>("key");
  3628. ASSERT_NE(nullptr, s);
  3629. EXPECT_EQ("hello", *s);
  3630. // erase
  3631. ud.erase("key");
  3632. EXPECT_FALSE(ud.has("key"));
  3633. // clear
  3634. ud.set("a", 1);
  3635. ud.set("b", 2);
  3636. ud.clear();
  3637. EXPECT_FALSE(ud.has("a"));
  3638. EXPECT_FALSE(ud.has("b"));
  3639. }
  3640. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3641. struct AuthCtx {
  3642. std::string user_id;
  3643. };
  3644. Server svr;
  3645. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3646. res.user_data.set("auth", AuthCtx{"alice"});
  3647. return Server::HandlerResponse::Unhandled;
  3648. });
  3649. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3650. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3651. ASSERT_NE(nullptr, ctx);
  3652. res.set_content("Hello " + ctx->user_id, "text/plain");
  3653. });
  3654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3655. auto se = detail::scope_exit([&] {
  3656. svr.stop();
  3657. thread.join();
  3658. ASSERT_FALSE(svr.is_running());
  3659. });
  3660. svr.wait_until_ready();
  3661. Client cli(HOST, PORT);
  3662. auto res = cli.Get("/me");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("Hello alice", res->body);
  3666. }
  3667. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3668. struct RoleCtx {
  3669. std::string role;
  3670. };
  3671. Server svr;
  3672. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3673. res.user_data.set("role", RoleCtx{"admin"});
  3674. return Server::HandlerResponse::Unhandled;
  3675. });
  3676. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3677. auto *ctx = res.user_data.get<RoleCtx>("role");
  3678. ASSERT_NE(nullptr, ctx);
  3679. res.set_content(ctx->role, "text/plain");
  3680. });
  3681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3682. auto se = detail::scope_exit([&] {
  3683. svr.stop();
  3684. thread.join();
  3685. ASSERT_FALSE(svr.is_running());
  3686. });
  3687. svr.wait_until_ready();
  3688. Client cli(HOST, PORT);
  3689. auto res = cli.Get("/role");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("admin", res->body);
  3693. }
  3694. TEST(InvalidFormatTest, StatusCode) {
  3695. Server svr;
  3696. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3697. res.set_content("Hello World!\n", "text/plain");
  3698. res.status = 9999; // Status should be a three-digit code...
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. auto res = cli.Get("/hi");
  3710. ASSERT_FALSE(res);
  3711. }
  3712. }
  3713. TEST(URLFragmentTest, WithFragment) {
  3714. Server svr;
  3715. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3716. EXPECT_TRUE(req.target == "/hi");
  3717. });
  3718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3719. auto se = detail::scope_exit([&] {
  3720. svr.stop();
  3721. thread.join();
  3722. ASSERT_FALSE(svr.is_running());
  3723. });
  3724. svr.wait_until_ready();
  3725. {
  3726. Client cli(HOST, PORT);
  3727. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3728. EXPECT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. res = cli.Get("/hi%23key1=val1=key2=val2");
  3731. EXPECT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. }
  3735. TEST(HeaderWriter, SetHeaderWriter) {
  3736. Server svr;
  3737. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3738. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3739. return detail::write_headers(strm, hdrs);
  3740. });
  3741. svr.Get("/hi", [](const Request &req, Response &res) {
  3742. auto it = req.headers.find("CustomClientHeader");
  3743. EXPECT_TRUE(it != req.headers.end());
  3744. EXPECT_EQ(it->second, "CustomClientValue");
  3745. res.set_content("Hello World!\n", "text/plain");
  3746. });
  3747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. {
  3755. Client cli(HOST, PORT);
  3756. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3757. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3758. return detail::write_headers(strm, hdrs);
  3759. });
  3760. auto res = cli.Get("/hi");
  3761. EXPECT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. auto it = res->headers.find("CustomServerHeader");
  3764. EXPECT_TRUE(it != res->headers.end());
  3765. EXPECT_EQ(it->second, "CustomServerValue");
  3766. }
  3767. }
  3768. class ServerTest : public ::testing::Test {
  3769. protected:
  3770. ServerTest()
  3771. : cli_(HOST, PORT)
  3772. #ifdef CPPHTTPLIB_SSL_ENABLED
  3773. ,
  3774. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3775. #endif
  3776. {
  3777. #ifdef CPPHTTPLIB_SSL_ENABLED
  3778. cli_.enable_server_certificate_verification(false);
  3779. #endif
  3780. // Allow LARGE_DATA (100MB) responses
  3781. cli_.set_payload_max_length(200 * 1024 * 1024);
  3782. }
  3783. virtual void SetUp() {
  3784. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3785. svr_.set_payload_max_length(200 * 1024 * 1024);
  3786. svr_.set_mount_point("/", "./www");
  3787. svr_.set_mount_point("/mount", "./www2");
  3788. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3789. svr_.Get("/hi",
  3790. [&](const Request & /*req*/, Response &res) {
  3791. res.set_content("Hello World!", "text/plain");
  3792. })
  3793. .Get("/file_content",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. res.set_file_content("./www/dir/test.html");
  3796. })
  3797. .Get("/file_content_with_content_type",
  3798. [&](const Request & /*req*/, Response &res) {
  3799. res.set_file_content("./www/file", "text/plain");
  3800. })
  3801. .Get("/invalid_file_content",
  3802. [&](const Request & /*req*/, Response &res) {
  3803. res.set_file_content("./www/dir/invalid_file_path");
  3804. })
  3805. .Get("/http_response_splitting",
  3806. [&](const Request & /*req*/, Response &res) {
  3807. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3808. EXPECT_EQ(0U, res.headers.size());
  3809. EXPECT_FALSE(res.has_header("a"));
  3810. res.set_header("a", "1\nSet-Cookie: a=1");
  3811. EXPECT_EQ(0U, res.headers.size());
  3812. EXPECT_FALSE(res.has_header("a"));
  3813. res.set_header("a", "1\rSet-Cookie: a=1");
  3814. EXPECT_EQ(0U, res.headers.size());
  3815. EXPECT_FALSE(res.has_header("a"));
  3816. res.set_header("a\r\nb", "0");
  3817. EXPECT_EQ(0U, res.headers.size());
  3818. EXPECT_FALSE(res.has_header("a"));
  3819. res.set_header("a\rb", "0");
  3820. EXPECT_EQ(0U, res.headers.size());
  3821. EXPECT_FALSE(res.has_header("a"));
  3822. res.set_header("a\nb", "0");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_redirect("1\r\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("Location"));
  3828. })
  3829. .Get("/slow",
  3830. [&](const Request & /*req*/, Response &res) {
  3831. std::this_thread::sleep_for(std::chrono::seconds(4));
  3832. res.set_content("slow", "text/plain");
  3833. })
  3834. #if 0
  3835. .Post("/slowpost",
  3836. [&](const Request & /*req*/, Response &res) {
  3837. std::this_thread::sleep_for(std::chrono::seconds(2));
  3838. res.set_content("slow", "text/plain");
  3839. })
  3840. #endif
  3841. .Get("/remote_addr",
  3842. [&](const Request &req, Response &res) {
  3843. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3844. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3845. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3846. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3847. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3848. #endif
  3849. res.set_content(req.remote_addr, "text/plain");
  3850. })
  3851. .Get("/local_addr",
  3852. [&](const Request &req, Response &res) {
  3853. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3854. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3855. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3856. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3857. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3858. #endif
  3859. auto local_addr = req.local_addr;
  3860. auto local_port = std::to_string(req.local_port);
  3861. res.set_content(local_addr.append(":").append(local_port),
  3862. "text/plain");
  3863. })
  3864. .Get("/endwith%",
  3865. [&](const Request & /*req*/, Response &res) {
  3866. res.set_content("Hello World!", "text/plain");
  3867. })
  3868. .Get("/a\\+\\+b",
  3869. [&](const Request &req, Response &res) {
  3870. ASSERT_TRUE(req.has_param("a +b"));
  3871. auto val = req.get_param_value("a +b");
  3872. res.set_content(val, "text/plain");
  3873. })
  3874. .Get("/", [&](const Request & /*req*/,
  3875. Response &res) { res.set_redirect("/hi"); })
  3876. .Post("/1",
  3877. [](const Request & /*req*/, Response &res) {
  3878. res.set_redirect("/2", StatusCode::SeeOther_303);
  3879. })
  3880. .Get("/2",
  3881. [](const Request & /*req*/, Response &res) {
  3882. res.set_content("redirected.", "text/plain");
  3883. res.status = StatusCode::OK_200;
  3884. })
  3885. .Post("/person",
  3886. [&](const Request &req, Response &res) {
  3887. if (req.has_param("name") && req.has_param("note")) {
  3888. persons_[req.get_param_value("name")] =
  3889. req.get_param_value("note");
  3890. } else {
  3891. res.status = StatusCode::BadRequest_400;
  3892. }
  3893. })
  3894. .Put("/person",
  3895. [&](const Request &req, Response &res) {
  3896. if (req.has_param("name") && req.has_param("note")) {
  3897. persons_[req.get_param_value("name")] =
  3898. req.get_param_value("note");
  3899. } else {
  3900. res.status = StatusCode::BadRequest_400;
  3901. }
  3902. })
  3903. .Get("/person/(.*)",
  3904. [&](const Request &req, Response &res) {
  3905. string name = req.matches[1];
  3906. if (persons_.find(name) != persons_.end()) {
  3907. auto note = persons_[name];
  3908. res.set_content(note, "text/plain");
  3909. } else {
  3910. res.status = StatusCode::NotFound_404;
  3911. }
  3912. })
  3913. .Delete("/person",
  3914. [&](const Request &req, Response &res) {
  3915. if (req.has_param("name")) {
  3916. string name = req.get_param_value("name");
  3917. if (persons_.find(name) != persons_.end()) {
  3918. persons_.erase(name);
  3919. res.set_content("DELETED", "text/plain");
  3920. } else {
  3921. res.status = StatusCode::NotFound_404;
  3922. }
  3923. } else {
  3924. res.status = StatusCode::BadRequest_400;
  3925. }
  3926. })
  3927. .Post("/x-www-form-urlencoded-json",
  3928. [&](const Request &req, Response &res) {
  3929. auto json = req.get_param_value("json");
  3930. ASSERT_EQ(JSON_DATA, json);
  3931. res.set_content(json, "appliation/json");
  3932. res.status = StatusCode::OK_200;
  3933. })
  3934. .Get("/streamed-chunked",
  3935. [&](const Request & /*req*/, Response &res) {
  3936. res.set_chunked_content_provider(
  3937. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3938. sink.os << "123";
  3939. sink.os << "456";
  3940. sink.os << "789";
  3941. sink.done();
  3942. return true;
  3943. });
  3944. })
  3945. .Get("/streamed-chunked-with-prohibited-trailer",
  3946. [&](const Request & /*req*/, Response &res) {
  3947. auto i = new int(0);
  3948. // Declare both a prohibited trailer (Content-Length) and an
  3949. // allowed one
  3950. res.set_header("Trailer", "Content-Length, X-Allowed");
  3951. res.set_chunked_content_provider(
  3952. "text/plain",
  3953. [i](size_t /*offset*/, DataSink &sink) {
  3954. switch (*i) {
  3955. case 0: sink.os << "123"; break;
  3956. case 1: sink.os << "456"; break;
  3957. case 2: sink.os << "789"; break;
  3958. case 3: {
  3959. sink.done_with_trailer(
  3960. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3961. } break;
  3962. }
  3963. (*i)++;
  3964. return true;
  3965. },
  3966. [i](bool success) {
  3967. EXPECT_TRUE(success);
  3968. delete i;
  3969. });
  3970. })
  3971. .Get("/streamed-chunked2",
  3972. [&](const Request & /*req*/, Response &res) {
  3973. auto i = new int(0);
  3974. res.set_chunked_content_provider(
  3975. "text/plain",
  3976. [i](size_t /*offset*/, DataSink &sink) {
  3977. switch (*i) {
  3978. case 0: sink.os << "123"; break;
  3979. case 1: sink.os << "456"; break;
  3980. case 2: sink.os << "789"; break;
  3981. case 3: sink.done(); break;
  3982. }
  3983. (*i)++;
  3984. return true;
  3985. },
  3986. [i](bool success) {
  3987. EXPECT_TRUE(success);
  3988. delete i;
  3989. });
  3990. })
  3991. .Get("/streamed-chunked-with-trailer",
  3992. [&](const Request & /*req*/, Response &res) {
  3993. auto i = new int(0);
  3994. res.set_header("Trailer", "Dummy1, Dummy2");
  3995. res.set_chunked_content_provider(
  3996. "text/plain",
  3997. [i](size_t /*offset*/, DataSink &sink) {
  3998. switch (*i) {
  3999. case 0: sink.os << "123"; break;
  4000. case 1: sink.os << "456"; break;
  4001. case 2: sink.os << "789"; break;
  4002. case 3: {
  4003. sink.done_with_trailer(
  4004. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4005. } break;
  4006. }
  4007. (*i)++;
  4008. return true;
  4009. },
  4010. [i](bool success) {
  4011. EXPECT_TRUE(success);
  4012. delete i;
  4013. });
  4014. })
  4015. .Get("/streamed",
  4016. [&](const Request & /*req*/, Response &res) {
  4017. res.set_content_provider(
  4018. 6, "text/plain",
  4019. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4020. sink.os << (offset < 3 ? "a" : "b");
  4021. return true;
  4022. });
  4023. })
  4024. .Get("/streamed-without-length",
  4025. [&](const Request & /*req*/, Response &res) {
  4026. auto data = new std::string("abcdefg");
  4027. res.set_content_provider(
  4028. "text/plain",
  4029. [data](size_t offset, DataSink &sink) {
  4030. if (offset < data->size()) {
  4031. sink.os << data->substr(offset);
  4032. }
  4033. sink.done();
  4034. return true;
  4035. },
  4036. [data](bool success) {
  4037. EXPECT_TRUE(success);
  4038. delete data;
  4039. });
  4040. })
  4041. .Get("/streamed-with-range",
  4042. [&](const Request &req, Response &res) {
  4043. auto data = new std::string("abcdefg");
  4044. // An explicit status keeps the server from picking the 206 it
  4045. // would otherwise choose for a ranged request, so the response
  4046. // is not a partial representation.
  4047. auto status = req.get_param_value("status");
  4048. if (status == "200") {
  4049. res.status = StatusCode::OK_200;
  4050. } else if (status == "403") {
  4051. res.status = StatusCode::Forbidden_403;
  4052. }
  4053. res.set_content_provider(
  4054. data->size(), "text/plain",
  4055. [data](size_t offset, size_t length, DataSink &sink) {
  4056. size_t DATA_CHUNK_SIZE = 4;
  4057. const auto &d = *data;
  4058. auto out_len =
  4059. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4060. auto ret =
  4061. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4062. EXPECT_TRUE(ret);
  4063. return true;
  4064. },
  4065. [data, &req](bool success) {
  4066. EXPECT_EQ(success, !req.has_param("error"));
  4067. delete data;
  4068. });
  4069. })
  4070. .Get("/streamed-cancel",
  4071. [&](const Request & /*req*/, Response &res) {
  4072. res.set_content_provider(
  4073. size_t(-1), "text/plain",
  4074. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4075. sink.os << "data_chunk";
  4076. return true;
  4077. });
  4078. })
  4079. .Get("/regex-with-delimiter",
  4080. [&](const Request &req, Response & /*res*/) {
  4081. ASSERT_TRUE(req.has_param("key"));
  4082. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4083. })
  4084. .Get("/with-range",
  4085. [&](const Request & /*req*/, Response &res) {
  4086. res.set_content("abcdefg", "text/plain");
  4087. })
  4088. .Get("/test-start-time",
  4089. [&](const Request &req, Response & /*res*/) {
  4090. EXPECT_NE(req.start_time_,
  4091. std::chrono::steady_clock::time_point::min());
  4092. })
  4093. .Get("/with-range-customized-response",
  4094. [&](const Request & /*req*/, Response &res) {
  4095. res.status = StatusCode::BadRequest_400;
  4096. res.set_content(JSON_DATA, "application/json");
  4097. })
  4098. .Post("/chunked",
  4099. [&](const Request &req, Response & /*res*/) {
  4100. EXPECT_EQ(req.body, "dechunked post body");
  4101. })
  4102. .Post("/large-chunked",
  4103. [&](const Request &req, Response & /*res*/) {
  4104. std::string expected(6 * 30 * 1024u, 'a');
  4105. EXPECT_EQ(req.body, expected);
  4106. })
  4107. .Post("/multipart",
  4108. [&](const Request &req, Response & /*res*/) {
  4109. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4110. req.form.get_field_count("text2") +
  4111. req.form.get_field_count("file3") +
  4112. req.form.get_field_count("file4"));
  4113. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4114. req.form.get_file_count("file2"));
  4115. ASSERT_TRUE(!req.form.has_file("???"));
  4116. ASSERT_TRUE(!req.form.has_field("???"));
  4117. ASSERT_TRUE(req.body.empty());
  4118. {
  4119. const auto &text = req.form.get_field("text1");
  4120. EXPECT_EQ("text default", text);
  4121. }
  4122. {
  4123. const auto &text = req.form.get_field("text2");
  4124. EXPECT_EQ("aωb", text);
  4125. }
  4126. {
  4127. const auto &file = req.form.get_file("file1");
  4128. EXPECT_EQ("hello.txt", file.filename);
  4129. EXPECT_EQ("text/plain", file.content_type);
  4130. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4131. }
  4132. {
  4133. const auto &file = req.form.get_file("file2");
  4134. EXPECT_EQ("world.json", file.filename);
  4135. EXPECT_EQ("application/json", file.content_type);
  4136. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4137. }
  4138. {
  4139. const auto &text = req.form.get_field("file3");
  4140. EXPECT_EQ(0u, text.size());
  4141. }
  4142. {
  4143. const auto &text = req.form.get_field("file4");
  4144. EXPECT_EQ(0u, text.size());
  4145. }
  4146. })
  4147. .Post("/multipart/multi_file_values",
  4148. [&](const Request &req, Response & /*res*/) {
  4149. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4150. req.form.get_field_count("multi_text1"));
  4151. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4152. ASSERT_TRUE(!req.form.has_file("???"));
  4153. ASSERT_TRUE(!req.form.has_field("???"));
  4154. ASSERT_TRUE(req.body.empty());
  4155. {
  4156. const auto &text = req.form.get_field("text");
  4157. EXPECT_EQ("default text", text);
  4158. }
  4159. {
  4160. const auto &text1_values = req.form.get_fields("multi_text1");
  4161. EXPECT_EQ(2u, text1_values.size());
  4162. EXPECT_EQ("aaaaa", text1_values[0]);
  4163. EXPECT_EQ("bbbbb", text1_values[1]);
  4164. }
  4165. {
  4166. const auto &file1_values = req.form.get_files("multi_file1");
  4167. EXPECT_EQ(2u, file1_values.size());
  4168. auto file1 = file1_values[0];
  4169. EXPECT_EQ(file1.filename, "hello.txt");
  4170. EXPECT_EQ(file1.content_type, "text/plain");
  4171. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4172. auto file2 = file1_values[1];
  4173. EXPECT_EQ(file2.filename, "world.json");
  4174. EXPECT_EQ(file2.content_type, "application/json");
  4175. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4176. }
  4177. })
  4178. .Post("/empty",
  4179. [&](const Request &req, Response &res) {
  4180. EXPECT_EQ(req.body, "");
  4181. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4182. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4183. res.set_content("empty", "text/plain");
  4184. })
  4185. .Post("/empty-no-content-type",
  4186. [&](const Request &req, Response &res) {
  4187. EXPECT_EQ(req.body, "");
  4188. EXPECT_FALSE(req.has_header("Content-Type"));
  4189. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4190. res.set_content("empty-no-content-type", "text/plain");
  4191. })
  4192. .Post("/path-only",
  4193. [&](const Request &req, Response &res) {
  4194. EXPECT_EQ(req.body, "");
  4195. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4196. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4197. res.set_content("path-only", "text/plain");
  4198. })
  4199. .Post("/path-headers-only",
  4200. [&](const Request &req, Response &res) {
  4201. EXPECT_EQ(req.body, "");
  4202. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4203. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4204. EXPECT_EQ("world", req.get_header_value("hello"));
  4205. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4206. res.set_content("path-headers-only", "text/plain");
  4207. })
  4208. .Post("/post-large",
  4209. [&](const Request &req, Response &res) {
  4210. EXPECT_EQ(req.body, LARGE_DATA);
  4211. res.set_content(req.body, "text/plain");
  4212. })
  4213. .Post("/post-loopback",
  4214. [&](const Request &, Response &res,
  4215. ContentReader const &content_reader) {
  4216. std::string body;
  4217. content_reader([&](const char *data, size_t data_length) {
  4218. body.append(data, data_length);
  4219. return true;
  4220. });
  4221. res.set_content(body, "text/plain");
  4222. })
  4223. .Put("/put-loopback",
  4224. [&](const Request &, Response &res,
  4225. ContentReader const &content_reader) {
  4226. std::string body;
  4227. content_reader([&](const char *data, size_t data_length) {
  4228. body.append(data, data_length);
  4229. return true;
  4230. });
  4231. res.set_content(body, "text/plain");
  4232. })
  4233. .Patch("/patch-loopback",
  4234. [&](const Request &, Response &res,
  4235. ContentReader const &content_reader) {
  4236. std::string body;
  4237. content_reader([&](const char *data, size_t data_length) {
  4238. body.append(data, data_length);
  4239. return true;
  4240. });
  4241. res.set_content(body, "text/plain");
  4242. })
  4243. .Put("/empty-no-content-type",
  4244. [&](const Request &req, Response &res) {
  4245. EXPECT_EQ(req.body, "");
  4246. EXPECT_FALSE(req.has_header("Content-Type"));
  4247. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4248. res.set_content("empty-no-content-type", "text/plain");
  4249. })
  4250. .Put("/put",
  4251. [&](const Request &req, Response &res) {
  4252. EXPECT_EQ(req.body, "PUT");
  4253. res.set_content(req.body, "text/plain");
  4254. })
  4255. .Put("/put-large",
  4256. [&](const Request &req, Response &res) {
  4257. EXPECT_EQ(req.body, LARGE_DATA);
  4258. res.set_content(req.body, "text/plain");
  4259. })
  4260. .Patch("/patch",
  4261. [&](const Request &req, Response &res) {
  4262. EXPECT_EQ(req.body, "PATCH");
  4263. res.set_content(req.body, "text/plain");
  4264. })
  4265. .Delete("/delete",
  4266. [&](const Request & /*req*/, Response &res) {
  4267. res.set_content("DELETE", "text/plain");
  4268. })
  4269. .Delete("/delete-body",
  4270. [&](const Request &req, Response &res) {
  4271. EXPECT_EQ(req.body, "content");
  4272. res.set_content(req.body, "text/plain");
  4273. })
  4274. .Options(R"(\*)",
  4275. [&](const Request & /*req*/, Response &res) {
  4276. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4277. })
  4278. .Get("/request-target",
  4279. [&](const Request &req, Response & /*res*/) {
  4280. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4281. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4282. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4283. })
  4284. .Get("/long-query-value",
  4285. [&](const Request &req, Response & /*res*/) {
  4286. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4287. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4288. })
  4289. .Get("/too-long-query-value",
  4290. [&](const Request &req, Response & /*res*/) {
  4291. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4292. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4293. })
  4294. .Get("/array-param",
  4295. [&](const Request &req, Response & /*res*/) {
  4296. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4297. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4298. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4299. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4300. })
  4301. .Get("/array-param-values",
  4302. [&](const Request &req, Response & /*res*/) {
  4303. auto values = req.get_param_values("array");
  4304. EXPECT_EQ(3u, values.size());
  4305. EXPECT_EQ("value1", values[0]);
  4306. EXPECT_EQ("value2", values[1]);
  4307. EXPECT_EQ("value3", values[2]);
  4308. auto empty = req.get_param_values("nonexistent");
  4309. EXPECT_TRUE(empty.empty());
  4310. })
  4311. .Post("/validate-no-multiple-headers",
  4312. [&](const Request &req, Response & /*res*/) {
  4313. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4314. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4315. })
  4316. .Post("/content_receiver",
  4317. [&](const Request &req, Response &res,
  4318. const ContentReader &content_reader) {
  4319. if (req.is_multipart_form_data()) {
  4320. std::vector<FormData> items;
  4321. content_reader(
  4322. [&](const FormData &file) {
  4323. items.push_back(file);
  4324. return true;
  4325. },
  4326. [&](const char *data, size_t data_length) {
  4327. items.back().content.append(data, data_length);
  4328. return true;
  4329. });
  4330. EXPECT_EQ(5u, items.size());
  4331. {
  4332. const auto &file = get_file_value(items, "text1");
  4333. EXPECT_TRUE(file.filename.empty());
  4334. EXPECT_EQ("text default", file.content);
  4335. }
  4336. {
  4337. const auto &file = get_file_value(items, "text2");
  4338. EXPECT_TRUE(file.filename.empty());
  4339. EXPECT_EQ("aωb", file.content);
  4340. }
  4341. {
  4342. const auto &file = get_file_value(items, "file1");
  4343. EXPECT_EQ("hello.txt", file.filename);
  4344. EXPECT_EQ("text/plain", file.content_type);
  4345. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4346. }
  4347. {
  4348. const auto &file = get_file_value(items, "file2");
  4349. EXPECT_EQ("world.json", file.filename);
  4350. EXPECT_EQ("application/json", file.content_type);
  4351. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4352. }
  4353. {
  4354. const auto &file = get_file_value(items, "file3");
  4355. EXPECT_TRUE(file.filename.empty());
  4356. EXPECT_EQ("application/octet-stream", file.content_type);
  4357. EXPECT_EQ(0u, file.content.size());
  4358. }
  4359. } else {
  4360. std::string body;
  4361. content_reader([&](const char *data, size_t data_length) {
  4362. EXPECT_EQ(7U, data_length);
  4363. body.append(data, data_length);
  4364. return true;
  4365. });
  4366. EXPECT_EQ(body, "content");
  4367. res.set_content(body, "text/plain");
  4368. }
  4369. })
  4370. .Put("/content_receiver",
  4371. [&](const Request & /*req*/, Response &res,
  4372. const ContentReader &content_reader) {
  4373. std::string body;
  4374. content_reader([&](const char *data, size_t data_length) {
  4375. body.append(data, data_length);
  4376. return true;
  4377. });
  4378. EXPECT_EQ(body, "content");
  4379. res.set_content(body, "text/plain");
  4380. })
  4381. .Patch("/content_receiver",
  4382. [&](const Request & /*req*/, Response &res,
  4383. const ContentReader &content_reader) {
  4384. std::string body;
  4385. content_reader([&](const char *data, size_t data_length) {
  4386. body.append(data, data_length);
  4387. return true;
  4388. });
  4389. EXPECT_EQ(body, "content");
  4390. res.set_content(body, "text/plain");
  4391. })
  4392. .Post("/query-string-and-body",
  4393. [&](const Request &req, Response & /*res*/) {
  4394. ASSERT_TRUE(req.has_param("key"));
  4395. EXPECT_EQ(req.get_param_value("key"), "value");
  4396. EXPECT_EQ(req.body, "content");
  4397. })
  4398. .Get("/last-request",
  4399. [&](const Request &req, Response & /*res*/) {
  4400. EXPECT_EQ("close", req.get_header_value("Connection"));
  4401. })
  4402. .Get(R"(/redirect/(\d+))",
  4403. [&](const Request &req, Response &res) {
  4404. auto num = std::stoi(req.matches[1]) + 1;
  4405. std::string url = "/redirect/" + std::to_string(num);
  4406. res.set_redirect(url);
  4407. })
  4408. .Post("/binary",
  4409. [&](const Request &req, Response &res) {
  4410. EXPECT_EQ(4U, req.body.size());
  4411. EXPECT_EQ("application/octet-stream",
  4412. req.get_header_value("Content-Type"));
  4413. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4414. res.set_content(req.body, "application/octet-stream");
  4415. })
  4416. .Put("/binary",
  4417. [&](const Request &req, Response &res) {
  4418. EXPECT_EQ(4U, req.body.size());
  4419. EXPECT_EQ("application/octet-stream",
  4420. req.get_header_value("Content-Type"));
  4421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4422. res.set_content(req.body, "application/octet-stream");
  4423. })
  4424. .Patch("/binary",
  4425. [&](const Request &req, Response &res) {
  4426. EXPECT_EQ(4U, req.body.size());
  4427. EXPECT_EQ("application/octet-stream",
  4428. req.get_header_value("Content-Type"));
  4429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4430. res.set_content(req.body, "application/octet-stream");
  4431. })
  4432. .Delete("/binary",
  4433. [&](const Request &req, Response &res) {
  4434. EXPECT_EQ(4U, req.body.size());
  4435. EXPECT_EQ("application/octet-stream",
  4436. req.get_header_value("Content-Type"));
  4437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4438. res.set_content(req.body, "application/octet-stream");
  4439. })
  4440. .Get("/issue1772",
  4441. [&](const Request & /*req*/, Response &res) {
  4442. res.status = 401;
  4443. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4444. })
  4445. .Delete("/issue609",
  4446. [](const httplib::Request &, httplib::Response &res,
  4447. const httplib::ContentReader &) {
  4448. res.set_content("ok", "text/plain");
  4449. })
  4450. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4451. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4452. .Get("/compress",
  4453. [&](const Request & /*req*/, Response &res) {
  4454. res.set_content(
  4455. "12345678901234567890123456789012345678901234567890123456789"
  4456. "01234567890123456789012345678901234567890",
  4457. "text/plain");
  4458. })
  4459. .Get("/compress-with-charset",
  4460. [&](const Request & /*req*/, Response &res) {
  4461. res.set_content(
  4462. "12345678901234567890123456789012345678901234567890123456789"
  4463. "01234567890123456789012345678901234567890",
  4464. "application/json; charset=utf-8");
  4465. })
  4466. .Get("/nocompress",
  4467. [&](const Request & /*req*/, Response &res) {
  4468. res.set_content(
  4469. "12345678901234567890123456789012345678901234567890123456789"
  4470. "01234567890123456789012345678901234567890",
  4471. "application/octet-stream");
  4472. })
  4473. .Post("/compress-multipart",
  4474. [&](const Request &req, Response & /*res*/) {
  4475. EXPECT_EQ(2u, req.form.fields.size());
  4476. ASSERT_TRUE(!req.form.has_field("???"));
  4477. {
  4478. const auto &text = req.form.get_field("key1");
  4479. EXPECT_EQ("test", text);
  4480. }
  4481. {
  4482. const auto &text = req.form.get_field("key2");
  4483. EXPECT_EQ("--abcdefg123", text);
  4484. }
  4485. })
  4486. #endif
  4487. ;
  4488. persons_["john"] = "programmer";
  4489. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4490. svr_.wait_until_ready();
  4491. }
  4492. virtual void TearDown() {
  4493. svr_.stop();
  4494. if (!request_threads_.empty()) {
  4495. std::this_thread::sleep_for(std::chrono::seconds(1));
  4496. for (auto &t : request_threads_) {
  4497. t.join();
  4498. }
  4499. }
  4500. t_.join();
  4501. }
  4502. map<string, string> persons_;
  4503. #ifdef CPPHTTPLIB_SSL_ENABLED
  4504. SSLClient cli_;
  4505. SSLServer svr_;
  4506. #else
  4507. Client cli_;
  4508. Server svr_;
  4509. #endif
  4510. thread t_;
  4511. std::vector<thread> request_threads_;
  4512. };
  4513. TEST_F(ServerTest, GetMethod200) {
  4514. auto res = cli_.Get("/hi");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ("HTTP/1.1", res->version);
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. EXPECT_EQ("OK", res->reason);
  4519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4520. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4521. EXPECT_EQ("Hello World!", res->body);
  4522. }
  4523. TEST_F(ServerTest, GetEmptyFile) {
  4524. auto res = cli_.Get("/empty_file");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4528. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4529. EXPECT_EQ("", res->body);
  4530. }
  4531. TEST_F(ServerTest, GetFileContent) {
  4532. auto res = cli_.Get("/file_content");
  4533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4536. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4537. EXPECT_EQ("test.html", res->body);
  4538. }
  4539. TEST_F(ServerTest, GetFileContentWithRange) {
  4540. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4542. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4544. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4545. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4546. EXPECT_EQ("est", res->body);
  4547. }
  4548. TEST_F(ServerTest, GetFileContentWithContentType) {
  4549. auto res = cli_.Get("/file_content_with_content_type");
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4553. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4554. EXPECT_EQ("file\n", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetInvalidFileContent) {
  4557. auto res = cli_.Get("/invalid_file_content");
  4558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4560. }
  4561. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4562. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("HTTP/1.1", res->version);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4567. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4568. EXPECT_EQ("Hello World!", res->body);
  4569. }
  4570. TEST_F(ServerTest, GetMethod302) {
  4571. auto res = cli_.Get("/");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::Found_302, res->status);
  4574. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4575. }
  4576. TEST_F(ServerTest, GetMethod302Redirect) {
  4577. cli_.set_follow_location(true);
  4578. auto res = cli_.Get("/");
  4579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("Hello World!", res->body);
  4582. EXPECT_EQ("/hi", res->location);
  4583. }
  4584. TEST_F(ServerTest, GetMethod404) {
  4585. auto res = cli_.Get("/invalid");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, HeadMethod200) {
  4590. auto res = cli_.Head("/hi");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4594. EXPECT_TRUE(res->body.empty());
  4595. }
  4596. TEST_F(ServerTest, HeadMethod200Static) {
  4597. auto res = cli_.Head("/mount/dir/index.html");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4601. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4602. EXPECT_TRUE(res->body.empty());
  4603. }
  4604. TEST_F(ServerTest, HeadMethod404) {
  4605. auto res = cli_.Head("/invalid");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4608. EXPECT_TRUE(res->body.empty());
  4609. }
  4610. TEST_F(ServerTest, GetMethodPersonJohn) {
  4611. auto res = cli_.Get("/person/john");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ("programmer", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMethod1) {
  4618. auto res = cli_.Get("/person/john1");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4621. res = cli_.Post("/person", "name=john1&note=coder",
  4622. "application/x-www-form-urlencoded");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. ASSERT_EQ(StatusCode::OK_200, res->status);
  4625. res = cli_.Get("/person/john1");
  4626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4627. ASSERT_EQ(StatusCode::OK_200, res->status);
  4628. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4629. ASSERT_EQ("coder", res->body);
  4630. }
  4631. TEST_F(ServerTest, PostMethod2) {
  4632. auto res = cli_.Get("/person/john2");
  4633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4634. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4635. Params params;
  4636. params.emplace("name", "john2");
  4637. params.emplace("note", "coder");
  4638. res = cli_.Post("/person", params);
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. ASSERT_EQ(StatusCode::OK_200, res->status);
  4641. res = cli_.Get("/person/john2");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. ASSERT_EQ(StatusCode::OK_200, res->status);
  4644. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4645. ASSERT_EQ("coder", res->body);
  4646. }
  4647. TEST_F(ServerTest, PutMethod3) {
  4648. auto res = cli_.Get("/person/john3");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4651. Params params;
  4652. params.emplace("name", "john3");
  4653. params.emplace("note", "coder");
  4654. res = cli_.Put("/person", params);
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. ASSERT_EQ(StatusCode::OK_200, res->status);
  4657. res = cli_.Get("/person/john3");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. ASSERT_EQ(StatusCode::OK_200, res->status);
  4660. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4661. ASSERT_EQ("coder", res->body);
  4662. }
  4663. TEST_F(ServerTest, DeleteMethod1) {
  4664. auto res = cli_.Get("/person/john4");
  4665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4666. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4667. Params params;
  4668. params.emplace("name", "john4");
  4669. params.emplace("note", "coder");
  4670. res = cli_.Post("/person", params);
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. ASSERT_EQ(StatusCode::OK_200, res->status);
  4673. res = cli_.Get("/person/john4");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. ASSERT_EQ(StatusCode::OK_200, res->status);
  4676. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4677. ASSERT_EQ("coder", res->body);
  4678. Params delete_params;
  4679. delete_params.emplace("name", "john4");
  4680. res = cli_.Delete("/person", delete_params);
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. ASSERT_EQ(StatusCode::OK_200, res->status);
  4683. ASSERT_EQ("DELETED", res->body);
  4684. res = cli_.Get("/person/john4");
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4687. }
  4688. TEST_F(ServerTest, DeleteMethod2) {
  4689. auto res = cli_.Get("/person/john5");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4692. Params params;
  4693. params.emplace("name", "john5");
  4694. params.emplace("note", "developer");
  4695. res = cli_.Post("/person", params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. res = cli_.Get("/person/john5");
  4699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4700. ASSERT_EQ(StatusCode::OK_200, res->status);
  4701. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4702. ASSERT_EQ("developer", res->body);
  4703. Params delete_params;
  4704. delete_params.emplace("name", "john5");
  4705. Headers headers;
  4706. headers.emplace("Custom-Header", "test-value");
  4707. res = cli_.Delete("/person", headers, delete_params);
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. ASSERT_EQ(StatusCode::OK_200, res->status);
  4710. ASSERT_EQ("DELETED", res->body);
  4711. res = cli_.Get("/person/john5");
  4712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4713. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4714. }
  4715. TEST_F(ServerTest, DeleteMethod3) {
  4716. auto res = cli_.Get("/person/john6");
  4717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4718. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4719. Params params;
  4720. params.emplace("name", "john6");
  4721. params.emplace("note", "tester");
  4722. res = cli_.Post("/person", params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. res = cli_.Get("/person/john6");
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. ASSERT_EQ(StatusCode::OK_200, res->status);
  4728. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4729. ASSERT_EQ("tester", res->body);
  4730. Params delete_params;
  4731. delete_params.emplace("name", "john6");
  4732. Headers headers;
  4733. headers.emplace("Custom-Header", "test-value");
  4734. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. ASSERT_EQ(StatusCode::OK_200, res->status);
  4737. ASSERT_EQ("DELETED", res->body);
  4738. res = cli_.Get("/person/john6");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4741. }
  4742. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4743. Params params;
  4744. params.emplace("json", JSON_DATA);
  4745. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4747. ASSERT_EQ(StatusCode::OK_200, res->status);
  4748. ASSERT_EQ(JSON_DATA, res->body);
  4749. }
  4750. TEST_F(ServerTest, PostEmptyContent) {
  4751. auto res = cli_.Post("/empty", "", "text/plain");
  4752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4753. ASSERT_EQ(StatusCode::OK_200, res->status);
  4754. ASSERT_EQ("empty", res->body);
  4755. }
  4756. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4757. auto res = cli_.Post("/empty-no-content-type");
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. ASSERT_EQ(StatusCode::OK_200, res->status);
  4760. ASSERT_EQ("empty-no-content-type", res->body);
  4761. }
  4762. TEST_F(ServerTest, PostPathOnly) {
  4763. auto res = cli_.Post("/path-only");
  4764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4765. ASSERT_EQ(StatusCode::OK_200, res->status);
  4766. ASSERT_EQ("path-only", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4769. auto res = cli_.Post("/path-headers-only",
  4770. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("path-headers-only", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostLarge) {
  4776. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. ASSERT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ(LARGE_DATA, res->body);
  4780. }
  4781. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4782. auto res = cli_.Put("/empty-no-content-type");
  4783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4784. ASSERT_EQ(StatusCode::OK_200, res->status);
  4785. ASSERT_EQ("empty-no-content-type", res->body);
  4786. }
  4787. TEST_F(ServerTest, GetMethodDir) {
  4788. auto res = cli_.Get("/dir/");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4792. auto body = R"(<html>
  4793. <head>
  4794. </head>
  4795. <body>
  4796. <a href="/dir/test.html">Test</a>
  4797. <a href="/hi">hi</a>
  4798. </body>
  4799. </html>
  4800. )";
  4801. EXPECT_EQ(body, res->body);
  4802. }
  4803. TEST_F(ServerTest, GetMethodDirTest) {
  4804. auto res = cli_.Get("/dir/test.html");
  4805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4808. EXPECT_EQ("test.html", res->body);
  4809. }
  4810. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4811. auto res = cli_.Get("/dir/../dir/test.html");
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4815. EXPECT_EQ("test.html", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetMethodInvalidPath) {
  4818. auto res = cli_.Get("/dir/../test.html");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4823. auto res = cli_.Get("/../www/dir/test.html");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4826. }
  4827. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4828. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4831. }
  4832. TEST_F(ServerTest, GetMethodDirMountTest) {
  4833. auto res = cli_.Get("/mount/dir/test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::OK_200, res->status);
  4836. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4837. EXPECT_EQ("test.html", res->body);
  4838. }
  4839. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4840. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4844. EXPECT_EQ("test.html", res->body);
  4845. }
  4846. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4847. auto res = cli_.Get("/mount/dir/../test.html");
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4850. }
  4851. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4852. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4855. }
  4856. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4857. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4860. }
  4861. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4862. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4865. }
  4866. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4867. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, PostMethod303) {
  4872. auto res = cli_.Post("/1", "body", "text/plain");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4875. EXPECT_EQ("/2", res->get_header_value("Location"));
  4876. }
  4877. TEST_F(ServerTest, PostMethod303Redirect) {
  4878. cli_.set_follow_location(true);
  4879. auto res = cli_.Post("/1", "body", "text/plain");
  4880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("redirected.", res->body);
  4883. EXPECT_EQ("/2", res->location);
  4884. }
  4885. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4886. auto res = cli_.Get("/dir/test.abcde");
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4890. EXPECT_EQ("abcde", res->body);
  4891. }
  4892. TEST_F(ServerTest, StaticFileRange) {
  4893. auto res =
  4894. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4897. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4898. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4899. EXPECT_EQ(true, res->has_header("Content-Range"));
  4900. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4901. EXPECT_EQ(std::string("cd"), res->body);
  4902. }
  4903. TEST_F(ServerTest, StaticFileRanges) {
  4904. auto res = cli_.Get("/dir/test.abcde",
  4905. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4908. EXPECT_TRUE(
  4909. res->get_header_value("Content-Type")
  4910. .find(
  4911. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4912. 0);
  4913. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4914. }
  4915. TEST_F(ServerTest, StaticFileRangeHead) {
  4916. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4919. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4921. EXPECT_EQ(true, res->has_header("Content-Range"));
  4922. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4923. }
  4924. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4925. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4929. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(true, res->has_header("Content-Range"));
  4931. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4932. res->get_header_value("Content-Range"));
  4933. EXPECT_EQ("LAST\n", res->body);
  4934. }
  4935. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4936. auto res =
  4937. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4939. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4941. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4942. EXPECT_EQ(true, res->has_header("Content-Range"));
  4943. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4944. }
  4945. TEST_F(ServerTest, StaticFileBigFile) {
  4946. auto res = cli_.Get("/dir/1MB.txt");
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4950. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4951. }
  4952. TEST_F(ServerTest, InvalidBaseDirMount) {
  4953. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4954. }
  4955. TEST_F(ServerTest, Binary) {
  4956. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4957. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4958. "application/octet-stream");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. ASSERT_EQ(StatusCode::OK_200, res->status);
  4961. ASSERT_EQ(4U, res->body.size());
  4962. res = cli_.Put("/binary", binary.data(), binary.size(),
  4963. "application/octet-stream");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. ASSERT_EQ(StatusCode::OK_200, res->status);
  4966. ASSERT_EQ(4U, res->body.size());
  4967. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4968. "application/octet-stream");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. ASSERT_EQ(StatusCode::OK_200, res->status);
  4971. ASSERT_EQ(4U, res->body.size());
  4972. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4973. "application/octet-stream");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ(4U, res->body.size());
  4977. }
  4978. TEST_F(ServerTest, BinaryString) {
  4979. auto binary = std::string("\x00\x01\x02\x03", 4);
  4980. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. ASSERT_EQ(StatusCode::OK_200, res->status);
  4983. ASSERT_EQ(4U, res->body.size());
  4984. res = cli_.Put("/binary", binary, "application/octet-stream");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. ASSERT_EQ(StatusCode::OK_200, res->status);
  4987. ASSERT_EQ(4U, res->body.size());
  4988. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. ASSERT_EQ(StatusCode::OK_200, res->status);
  4995. ASSERT_EQ(4U, res->body.size());
  4996. }
  4997. TEST_F(ServerTest, EmptyRequest) {
  4998. auto res = cli_.Get("");
  4999. ASSERT_TRUE(!res);
  5000. EXPECT_EQ(Error::Connection, res.error());
  5001. }
  5002. TEST_F(ServerTest, LongRequest) {
  5003. std::string request;
  5004. for (size_t i = 0; i < 545; i++) {
  5005. request += "/TooLongRequest";
  5006. }
  5007. request += "OK";
  5008. auto res = cli_.Get(request.c_str());
  5009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5011. }
  5012. TEST_F(ServerTest, TooLongRequest) {
  5013. std::string request;
  5014. for (size_t i = 0; i < 546; i++) {
  5015. request += "/TooLongRequest";
  5016. }
  5017. request += "_NG";
  5018. auto start = std::chrono::high_resolution_clock::now();
  5019. cli_.set_keep_alive(true);
  5020. auto res = cli_.Get(request.c_str());
  5021. auto end = std::chrono::high_resolution_clock::now();
  5022. auto elapsed =
  5023. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5024. .count();
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5027. EXPECT_LE(elapsed, 1000);
  5028. EXPECT_EQ("close", res->get_header_value("Connection"));
  5029. EXPECT_FALSE(cli_.is_socket_open());
  5030. }
  5031. TEST_F(ServerTest, AlmostTooLongRequest) {
  5032. // test for #2046 - URI length check shouldn't include other content on req
  5033. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5034. // leading /, space, HTTP/1.1)
  5035. std::string request =
  5036. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5037. auto res = cli_.Get(request.c_str());
  5038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5039. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5040. }
  5041. TEST_F(ServerTest, LongHeader) {
  5042. Request req;
  5043. req.method = "GET";
  5044. req.path = "/hi";
  5045. std::string host_and_port;
  5046. host_and_port += HOST;
  5047. host_and_port += ":";
  5048. host_and_port += std::to_string(PORT);
  5049. req.headers.emplace("Host", host_and_port.c_str());
  5050. req.headers.emplace("Accept", "*/*");
  5051. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5052. req.headers.emplace(
  5053. "Header-Name",
  5054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@");
  5083. auto res = std::make_shared<Response>();
  5084. auto error = Error::Success;
  5085. auto ret = cli_.send(req, *res, error);
  5086. ASSERT_TRUE(ret);
  5087. EXPECT_EQ(StatusCode::OK_200, res->status);
  5088. }
  5089. TEST_F(ServerTest, LongQueryValue) {
  5090. auto start = std::chrono::high_resolution_clock::now();
  5091. cli_.set_keep_alive(true);
  5092. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5093. auto end = std::chrono::high_resolution_clock::now();
  5094. auto elapsed =
  5095. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5096. .count();
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5099. EXPECT_LE(elapsed, 1000);
  5100. EXPECT_EQ("close", res->get_header_value("Connection"));
  5101. EXPECT_FALSE(cli_.is_socket_open());
  5102. }
  5103. TEST_F(ServerTest, TooLongQueryValue) {
  5104. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5105. ASSERT_FALSE(res);
  5106. EXPECT_EQ(Error::Read, res.error());
  5107. }
  5108. TEST_F(ServerTest, TooLongHeader) {
  5109. Request req;
  5110. req.method = "GET";
  5111. req.path = "/hi";
  5112. std::string host_and_port;
  5113. host_and_port += HOST;
  5114. host_and_port += ":";
  5115. host_and_port += std::to_string(PORT);
  5116. req.headers.emplace("Host", host_and_port.c_str());
  5117. req.headers.emplace("Accept", "*/*");
  5118. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5119. req.headers.emplace(
  5120. "Header-Name",
  5121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@");
  5150. auto res = std::make_shared<Response>();
  5151. auto error = Error::Success;
  5152. auto ret = cli_.send(req, *res, error);
  5153. ASSERT_TRUE(ret);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. TEST_F(ServerTest, HeaderCountAtLimit) {
  5157. // Test with headers just under the 100 limit
  5158. httplib::Headers headers;
  5159. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5160. // This should keep us just under the 100 header limit
  5161. for (int i = 0; i < 95; i++) {
  5162. std::string name = "X-Test-Header-" + std::to_string(i);
  5163. std::string value = "value" + std::to_string(i);
  5164. headers.emplace(name, value);
  5165. }
  5166. // This should work fine as we're under the limit
  5167. auto res = cli_.Get("/hi", headers);
  5168. EXPECT_TRUE(res);
  5169. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5170. }
  5171. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5172. // Test with many headers to exceed the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 150 headers to definitely exceed the 100 limit
  5175. for (int i = 0; i < 150; i++) {
  5176. std::string name = "X-Test-Header-" + std::to_string(i);
  5177. std::string value = "value" + std::to_string(i);
  5178. headers.emplace(name, value);
  5179. }
  5180. // This should fail due to exceeding header count limit
  5181. cli_.set_keep_alive(true);
  5182. auto res = cli_.Get("/hi", headers);
  5183. // The server should respond with 400 Bad Request
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. EXPECT_FALSE(cli_.is_socket_open());
  5188. }
  5189. TEST_F(ServerTest, PercentEncoding) {
  5190. auto res = cli_.Get("/e%6edwith%");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, PercentEncodingUnicode) {
  5195. auto res = cli_.Get("/e%u006edwith%");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, InvalidPercentEncoding) {
  5200. auto res = cli_.Get("/%endwith%");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5203. }
  5204. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5205. auto res = cli_.Get("/%uendwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5208. }
  5209. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5210. auto res = cli_.Get("/hello?aaa=bbb%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5213. }
  5214. TEST_F(ServerTest, PlusSignEncoding) {
  5215. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("a +b", res->body);
  5219. }
  5220. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5221. // This test simulates a potential DoS attack using many headers
  5222. // to verify our security fix prevents memory exhaustion
  5223. httplib::Headers attack_headers;
  5224. // Attempt to add many headers like an attacker would (200 headers to far
  5225. // exceed limit)
  5226. for (int i = 0; i < 200; i++) {
  5227. std::string name = "X-Attack-Header-" + std::to_string(i);
  5228. std::string value = "attack_payload_" + std::to_string(i);
  5229. attack_headers.emplace(name, value);
  5230. }
  5231. // Try to POST with excessive headers
  5232. cli_.set_keep_alive(true);
  5233. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5234. // Should either fail or return 400 Bad Request due to security limit
  5235. if (res) {
  5236. // If we get a response, it should be 400 Bad Request
  5237. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5238. EXPECT_EQ("close", res->get_header_value("Connection"));
  5239. }
  5240. EXPECT_FALSE(cli_.is_socket_open());
  5241. }
  5242. TEST_F(ServerTest, MultipartFormData) {
  5243. UploadFormDataItems items = {
  5244. {"text1", "text default", "", ""},
  5245. {"text2", "aωb", "", ""},
  5246. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5247. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5248. {"file3", "", "", "application/octet-stream"},
  5249. {"file4", "", "", " application/json tmp-string "}};
  5250. auto res = cli_.Post("/multipart", items);
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5255. UploadFormDataItems items = {
  5256. {"text", "default text", "", ""},
  5257. {"multi_text1", "aaaaa", "", ""},
  5258. {"multi_text1", "bbbbb", "", ""},
  5259. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5260. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5261. "application/json"},
  5262. };
  5263. auto res = cli_.Post("/multipart/multi_file_values", items);
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5268. auto res = cli_.Get("/hi");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5275. Request req;
  5276. req.method = "POST";
  5277. req.path = "/chunked";
  5278. std::string host_and_port;
  5279. host_and_port += HOST;
  5280. host_and_port += ":";
  5281. host_and_port += std::to_string(PORT);
  5282. req.headers.emplace("Host", host_and_port.c_str());
  5283. req.headers.emplace("Accept", "*/*");
  5284. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5285. req.headers.emplace("Content-Type", "text/plain");
  5286. req.headers.emplace("Content-Length", "0");
  5287. req.headers.emplace(
  5288. "Transfer-Encoding",
  5289. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5290. // Client does not chunk, so make a chunked body manually.
  5291. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5292. auto res = std::make_shared<Response>();
  5293. auto error = Error::Success;
  5294. auto ret = cli_.send(req, *res, error);
  5295. ASSERT_TRUE(ret);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. }
  5298. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5299. // rather than treat them as valid lengths.
  5300. template <typename ClientT>
  5301. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5302. Request req;
  5303. req.method = "POST";
  5304. req.path = "/chunked";
  5305. std::string host_and_port;
  5306. host_and_port += HOST;
  5307. host_and_port += ":";
  5308. host_and_port += std::to_string(PORT);
  5309. req.headers.emplace("Host", host_and_port.c_str());
  5310. req.headers.emplace("Content-Length", "0");
  5311. req.headers.emplace("Transfer-Encoding", "chunked");
  5312. req.body = body;
  5313. auto res = std::make_shared<Response>();
  5314. auto error = Error::Success;
  5315. ASSERT_TRUE(cli.send(req, *res, error));
  5316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5317. }
  5318. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5319. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5320. }
  5321. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5322. expect_chunked_body_rejected(
  5323. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5324. }
  5325. TEST_F(ServerTest, GetStreamed2) {
  5326. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5329. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ(true, res->has_header("Content-Range"));
  5331. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5332. EXPECT_EQ(std::string("ab"), res->body);
  5333. }
  5334. TEST_F(ServerTest, GetStreamed) {
  5335. auto res = cli_.Get("/streamed");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5339. EXPECT_EQ(std::string("aaabbb"), res->body);
  5340. }
  5341. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5342. auto res = cli_.Get("/streamed-without-length",
  5343. Headers{make_range_header({{0, -1}})});
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ(false, res->has_header("Content-Length"));
  5347. EXPECT_EQ(false, res->has_header("Content-Range"));
  5348. EXPECT_EQ(std::string("abcdefg"), res->body);
  5349. }
  5350. TEST_F(ServerTest, GetStreamedWithRange1) {
  5351. auto res =
  5352. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5355. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5356. EXPECT_EQ(true, res->has_header("Content-Range"));
  5357. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5358. EXPECT_EQ(std::string("def"), res->body);
  5359. }
  5360. TEST_F(ServerTest, GetStreamedWithRange2) {
  5361. auto res =
  5362. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5365. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ(true, res->has_header("Content-Range"));
  5367. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5368. EXPECT_EQ(std::string("bcdefg"), res->body);
  5369. }
  5370. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5371. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5374. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ(true, res->has_header("Content-Range"));
  5376. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5377. EXPECT_EQ(std::string("efg"), res->body);
  5378. }
  5379. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5380. auto res =
  5381. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5384. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5385. EXPECT_EQ(false, res->has_header("Content-Range"));
  5386. EXPECT_EQ(0U, res->body.size());
  5387. }
  5388. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5389. // Only a 206 is served as a partial representation. Under any other status
  5390. // `apply_ranges()` reported the full content length, so the body must match
  5391. // that header, and the content provider must never be asked for an offset
  5392. // outside the representation.
  5393. auto check = [&](int status, const char *range) {
  5394. auto path =
  5395. std::string("/streamed-with-range?status=") + std::to_string(status);
  5396. auto ctx = path + " Range: " + range;
  5397. auto res = cli_.Get(path, Headers{{"Range", range}});
  5398. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5399. EXPECT_EQ(status, res->status) << ctx;
  5400. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5402. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5403. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5404. };
  5405. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5406. check(403, "bytes=3-5");
  5407. // The offset is far past the representation.
  5408. check(403, "bytes=100000-100200");
  5409. // `first_pos` is still -1 here, and the bounds asserts in
  5410. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5411. check(403, "bytes=-3");
  5412. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5413. // multipart branch would have written one that is empty.
  5414. check(403, "bytes=1-2, 4-5");
  5415. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5416. // covers the whole representation.
  5417. check(200, "bytes=3-5");
  5418. check(200, "bytes=1-2, 4-5");
  5419. }
  5420. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5421. auto res =
  5422. cli_.Get("/streamed-with-range",
  5423. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5424. "92233720368547758079223372036854775807"}});
  5425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5427. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ(false, res->has_header("Content-Range"));
  5429. EXPECT_EQ(0U, res->body.size());
  5430. }
  5431. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5432. auto res = cli_.Get(
  5433. "/with-range",
  5434. Headers{{"Range",
  5435. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5436. {"Accept-Encoding", ""}});
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5439. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5440. EXPECT_EQ(true, res->has_header("Content-Range"));
  5441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5442. EXPECT_EQ(std::string("abcdefg"), res->body);
  5443. }
  5444. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5445. auto res = cli_.Get("/with-range", Headers{
  5446. {"Range", "bytes=0-"},
  5447. {"Accept-Encoding", ""},
  5448. });
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(true, res->has_header("Content-Range"));
  5453. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5454. EXPECT_EQ(std::string("abcdefg"), res->body);
  5455. }
  5456. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5457. auto res = cli_.Get("/streamed-with-range",
  5458. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5461. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ(false, res->has_header("Content-Range"));
  5463. EXPECT_EQ(267U, res->body.size());
  5464. // Check that both range contents are present
  5465. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5466. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5467. // Check that Content-Range headers are present for both ranges
  5468. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5469. std::string::npos);
  5470. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5471. std::string::npos);
  5472. }
  5473. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5474. Ranges ranges;
  5475. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5476. ranges.emplace_back(0, -1);
  5477. }
  5478. auto res = cli_.Get("/streamed-with-range?error",
  5479. Headers{{make_range_header(ranges)}});
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5482. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5483. EXPECT_EQ(false, res->has_header("Content-Range"));
  5484. EXPECT_EQ(0U, res->body.size());
  5485. }
  5486. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5487. auto res = cli_.Get("/streamed-with-range",
  5488. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5491. EXPECT_EQ(5U, res->body.size());
  5492. // Check that overlapping ranges are coalesced into a single range
  5493. EXPECT_EQ("bcdef", res->body);
  5494. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5495. // Should be single range, not multipart
  5496. EXPECT_TRUE(res->has_header("Content-Range"));
  5497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5498. }
  5499. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5500. auto res = cli_.Get("/streamed-with-range",
  5501. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5504. EXPECT_EQ(268U, res->body.size());
  5505. // Check that both range contents are present
  5506. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5507. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5508. // Check that Content-Range headers are present for both ranges
  5509. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5510. std::string::npos);
  5511. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5512. std::string::npos);
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(269U, res->body.size());
  5520. // Check that both duplicate range contents are present
  5521. size_t first_abc = res->body.find("abc\r\n");
  5522. EXPECT_TRUE(first_abc != std::string::npos);
  5523. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5524. EXPECT_TRUE(second_abc != std::string::npos);
  5525. // Check that Content-Range headers are present for both ranges
  5526. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5527. EXPECT_TRUE(first_range != std::string::npos);
  5528. size_t second_range =
  5529. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5530. EXPECT_TRUE(second_range != std::string::npos);
  5531. }
  5532. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5533. auto res =
  5534. cli_.Get("/streamed-with-range?error",
  5535. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5538. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ(false, res->has_header("Content-Range"));
  5540. EXPECT_EQ(0U, res->body.size());
  5541. }
  5542. TEST_F(ServerTest, GetStreamedEndless) {
  5543. uint64_t offset = 0;
  5544. auto res = cli_.Get("/streamed-cancel",
  5545. [&](const char * /*data*/, uint64_t data_length) {
  5546. if (offset < 100) {
  5547. offset += data_length;
  5548. return true;
  5549. }
  5550. return false;
  5551. });
  5552. ASSERT_TRUE(!res);
  5553. EXPECT_EQ(Error::Canceled, res.error());
  5554. }
  5555. TEST_F(ServerTest, ClientStop) {
  5556. std::atomic_size_t count{4};
  5557. std::vector<std::thread> threads;
  5558. for (auto i = count.load(); i != 0; --i) {
  5559. threads.emplace_back([&]() {
  5560. auto res = cli_.Get("/streamed-cancel",
  5561. [&](const char *, uint64_t) { return true; });
  5562. --count;
  5563. ASSERT_TRUE(!res);
  5564. EXPECT_TRUE(res.error() == Error::Canceled ||
  5565. res.error() == Error::Read || res.error() == Error::Write);
  5566. });
  5567. }
  5568. std::this_thread::sleep_for(std::chrono::seconds(2));
  5569. while (count != 0) {
  5570. cli_.stop();
  5571. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5572. }
  5573. for (auto &t : threads) {
  5574. t.join();
  5575. }
  5576. }
  5577. TEST_F(ServerTest, GetWithRange1) {
  5578. auto res = cli_.Get("/with-range", Headers{
  5579. make_range_header({{3, 5}}),
  5580. {"Accept-Encoding", ""},
  5581. });
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5584. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ(true, res->has_header("Content-Range"));
  5586. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5587. EXPECT_EQ(std::string("def"), res->body);
  5588. }
  5589. TEST_F(ServerTest, GetWithRange2) {
  5590. auto res = cli_.Get("/with-range", Headers{
  5591. make_range_header({{1, -1}}),
  5592. {"Accept-Encoding", ""},
  5593. });
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5596. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5597. EXPECT_EQ(true, res->has_header("Content-Range"));
  5598. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5599. EXPECT_EQ(std::string("bcdefg"), res->body);
  5600. }
  5601. TEST_F(ServerTest, GetWithRange3) {
  5602. auto res = cli_.Get("/with-range", Headers{
  5603. make_range_header({{0, 0}}),
  5604. {"Accept-Encoding", ""},
  5605. });
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5608. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5609. EXPECT_EQ(true, res->has_header("Content-Range"));
  5610. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5611. EXPECT_EQ(std::string("a"), res->body);
  5612. }
  5613. TEST_F(ServerTest, GetWithRange4) {
  5614. auto res = cli_.Get("/with-range", Headers{
  5615. make_range_header({{-1, 2}}),
  5616. {"Accept-Encoding", ""},
  5617. });
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5620. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5621. EXPECT_EQ(true, res->has_header("Content-Range"));
  5622. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5623. EXPECT_EQ(std::string("fg"), res->body);
  5624. }
  5625. TEST_F(ServerTest, GetWithRange5) {
  5626. auto res = cli_.Get("/with-range", Headers{
  5627. make_range_header({{0, 5}}),
  5628. {"Accept-Encoding", ""},
  5629. });
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ(true, res->has_header("Content-Range"));
  5634. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5635. EXPECT_EQ(std::string("abcdef"), res->body);
  5636. }
  5637. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5638. auto res =
  5639. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5641. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5642. }
  5643. TEST_F(ServerTest, GetWithRangeMultipart) {
  5644. auto res =
  5645. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5648. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5649. EXPECT_EQ(false, res->has_header("Content-Range"));
  5650. EXPECT_EQ(267U, res->body.size());
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5653. auto res = cli_.Get("/with-range",
  5654. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5659. auto res = cli_.Get("/with-range-customized-response",
  5660. Headers{{make_range_header({{1, 2}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5663. EXPECT_EQ(true, res->has_header("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(JSON_DATA, res->body);
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5668. auto res = cli_.Get("/with-range-customized-response",
  5669. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5672. EXPECT_EQ(true, res->has_header("Content-Length"));
  5673. EXPECT_EQ(false, res->has_header("Content-Range"));
  5674. EXPECT_EQ(JSON_DATA, res->body);
  5675. }
  5676. TEST_F(ServerTest, Issue1772) {
  5677. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5680. }
  5681. TEST_F(ServerTest, Issue609) {
  5682. auto res = cli_.Delete("/issue609");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ(std::string("ok"), res->body);
  5686. }
  5687. TEST_F(ServerTest, GetStreamedChunked) {
  5688. auto res = cli_.Get("/streamed-chunked");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ(std::string("123456789"), res->body);
  5692. }
  5693. TEST_F(ServerTest, GetStreamedChunked2) {
  5694. auto res = cli_.Get("/streamed-chunked2");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. EXPECT_EQ(StatusCode::OK_200, res->status);
  5697. EXPECT_EQ(std::string("123456789"), res->body);
  5698. }
  5699. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5700. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ(std::string("123456789"), res->body);
  5704. EXPECT_TRUE(res->has_header("Trailer"));
  5705. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5706. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5707. // Trailers are now stored separately from headers (security fix)
  5708. EXPECT_EQ(2U, res->trailers.size());
  5709. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5710. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5711. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5712. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5713. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5714. // Verify trailers are NOT in headers (security verification)
  5715. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5716. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5717. }
  5718. TEST_F(ServerTest, LargeChunkedPost) {
  5719. Request req;
  5720. req.method = "POST";
  5721. req.path = "/large-chunked";
  5722. std::string host_and_port;
  5723. host_and_port += HOST;
  5724. host_and_port += ":";
  5725. host_and_port += std::to_string(PORT);
  5726. req.headers.emplace("Host", host_and_port.c_str());
  5727. req.headers.emplace("Accept", "*/*");
  5728. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5729. req.headers.emplace("Content-Type", "text/plain");
  5730. req.headers.emplace("Content-Length", "0");
  5731. req.headers.emplace("Transfer-Encoding", "chunked");
  5732. std::string long_string(30 * 1024u, 'a');
  5733. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5734. // Attempt to make a large enough post to exceed OS buffers, to test that
  5735. // the server handles short reads if the full chunk data isn't available.
  5736. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5737. auto res = std::make_shared<Response>();
  5738. auto error = Error::Success;
  5739. auto ret = cli_.send(req, *res, error);
  5740. ASSERT_TRUE(ret);
  5741. EXPECT_EQ(StatusCode::OK_200, res->status);
  5742. }
  5743. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5744. auto res = cli_.Get("/remote_addr");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5748. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5749. }
  5750. TEST_F(ServerTest, GetMethodLocalAddr) {
  5751. auto res = cli_.Get("/local_addr");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::OK_200, res->status);
  5754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5755. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5756. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5757. }
  5758. TEST_F(ServerTest, HTTPResponseSplitting) {
  5759. auto res = cli_.Get("/http_response_splitting");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. }
  5763. TEST_F(ServerTest, SlowRequest) {
  5764. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5765. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5766. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5767. }
  5768. #if 0
  5769. TEST_F(ServerTest, SlowPost) {
  5770. char buffer[64 * 1024];
  5771. memset(buffer, 0x42, sizeof(buffer));
  5772. auto res = cli_.Post(
  5773. "/slowpost", 64 * 1024 * 1024,
  5774. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5775. auto ret = sink.write(buffer, sizeof(buffer));
  5776. EXPECT_TRUE(ret);
  5777. return true;
  5778. },
  5779. "text/plain");
  5780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5781. EXPECT_EQ(StatusCode::OK_200, res->status);
  5782. }
  5783. TEST_F(ServerTest, SlowPostFail) {
  5784. char buffer[64 * 1024];
  5785. memset(buffer, 0x42, sizeof(buffer));
  5786. cli_.set_write_timeout(std::chrono::seconds(0));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. sink.write(buffer, sizeof(buffer));
  5791. return true;
  5792. },
  5793. "text/plain");
  5794. ASSERT_TRUE(!res);
  5795. EXPECT_EQ(Error::Write, res.error());
  5796. }
  5797. #endif
  5798. TEST_F(ServerTest, Put) {
  5799. auto res = cli_.Put("/put", "PUT", "text/plain");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. EXPECT_EQ("PUT", res->body);
  5803. }
  5804. TEST_F(ServerTest, PutWithContentProvider) {
  5805. auto res = cli_.Put(
  5806. "/put", 3,
  5807. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5808. sink.os << "PUT";
  5809. return true;
  5810. },
  5811. "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. EXPECT_EQ("PUT", res->body);
  5815. }
  5816. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5817. auto res = cli_.Post(
  5818. "/post", 42,
  5819. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5820. return false;
  5821. },
  5822. "text/plain");
  5823. ASSERT_TRUE(!res);
  5824. EXPECT_EQ(Error::Canceled, res.error());
  5825. }
  5826. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5827. auto res = cli_.Put(
  5828. "/put",
  5829. [](size_t /*offset*/, DataSink &sink) {
  5830. sink.os << "PUT";
  5831. sink.done();
  5832. return true;
  5833. },
  5834. "text/plain");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("PUT", res->body);
  5838. }
  5839. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5840. auto res = cli_.Post(
  5841. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5842. "text/plain");
  5843. ASSERT_TRUE(!res);
  5844. EXPECT_EQ(Error::Canceled, res.error());
  5845. }
  5846. TEST_F(ServerTest, PostLoopBack) {
  5847. std::string body;
  5848. auto res = cli_.Post(
  5849. "/post-loopback", 9,
  5850. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5851. EXPECT_EQ(9u, length);
  5852. sink.write("123", 3);
  5853. sink.write("456", 3);
  5854. sink.write("789", 3);
  5855. return true;
  5856. },
  5857. "text/plain",
  5858. [&body](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. EXPECT_EQ("123456789", body);
  5865. }
  5866. TEST_F(ServerTest, PutLoopBack) {
  5867. std::string body;
  5868. auto res = cli_.Put(
  5869. "/put-loopback", 9,
  5870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5871. EXPECT_EQ(9u, length);
  5872. sink.write("123", 3);
  5873. sink.write("456", 3);
  5874. sink.write("789", 3);
  5875. return true;
  5876. },
  5877. "text/plain",
  5878. [&body](const char *data, size_t data_length) {
  5879. body.append(data, data_length);
  5880. return true;
  5881. });
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("123456789", body);
  5885. }
  5886. TEST_F(ServerTest, PatchLoopBack) {
  5887. std::string body;
  5888. auto res = cli_.Patch(
  5889. "/patch-loopback", 9,
  5890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5891. EXPECT_EQ(9u, length);
  5892. sink.write("123", 3);
  5893. sink.write("456", 3);
  5894. sink.write("789", 3);
  5895. return true;
  5896. },
  5897. "text/plain",
  5898. [&body](const char *data, size_t data_length) {
  5899. body.append(data, data_length);
  5900. return true;
  5901. });
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("123456789", body);
  5905. }
  5906. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5907. std::string body;
  5908. auto res = cli_.Post(
  5909. "/post-loopback",
  5910. [](size_t /*offset*/, DataSink &sink) {
  5911. sink.write("123", 3);
  5912. sink.write("456", 3);
  5913. sink.write("789", 3);
  5914. sink.done();
  5915. return true;
  5916. },
  5917. "text/plain",
  5918. [&body](const char *data, size_t data_length) {
  5919. body.append(data, data_length);
  5920. return true;
  5921. });
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. EXPECT_EQ("123456789", body);
  5925. }
  5926. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5927. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5928. cli_.set_compress(true);
  5929. auto res = cli_.Put(
  5930. "/put", 3,
  5931. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5932. sink.os << "PUT";
  5933. return true;
  5934. },
  5935. "text/plain");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. EXPECT_EQ("PUT", res->body);
  5939. }
  5940. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5941. cli_.set_compress(true);
  5942. auto res = cli_.Post(
  5943. "/post", 42,
  5944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5945. return false;
  5946. },
  5947. "text/plain");
  5948. ASSERT_TRUE(!res);
  5949. EXPECT_EQ(Error::Canceled, res.error());
  5950. }
  5951. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5952. cli_.set_compress(true);
  5953. auto res = cli_.Put(
  5954. "/put",
  5955. [](size_t /*offset*/, DataSink &sink) {
  5956. sink.os << "PUT";
  5957. sink.done();
  5958. return true;
  5959. },
  5960. "text/plain");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("PUT", res->body);
  5964. }
  5965. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5966. cli_.set_compress(true);
  5967. auto res = cli_.Post(
  5968. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5969. "text/plain");
  5970. ASSERT_TRUE(!res);
  5971. EXPECT_EQ(Error::Canceled, res.error());
  5972. }
  5973. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5974. cli_.set_compress(true);
  5975. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ(LARGE_DATA, res->body);
  5979. }
  5980. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5981. #ifdef CPPHTTPLIB_SSL_ENABLED
  5982. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5983. Client cli(s.c_str());
  5984. cli.enable_server_certificate_verification(false);
  5985. #else
  5986. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5987. Client cli(s.c_str());
  5988. #endif
  5989. cli.set_compress(true);
  5990. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ(LARGE_DATA, res->body);
  5994. // The compressed size should be less than a 10th of the original. May vary
  5995. // depending on the zlib library.
  5996. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5997. static_cast<uint64_t>(10 * 1024 * 1024));
  5998. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5999. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6000. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6001. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6002. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6003. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6004. #endif
  6005. }
  6006. TEST_F(ServerTest, PutContentWithDeflate) {
  6007. cli_.set_compress(false);
  6008. Headers headers;
  6009. headers.emplace("Content-Encoding", "deflate");
  6010. // PUT in deflate format:
  6011. auto res = cli_.Put("/put", headers,
  6012. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ("PUT", res->body);
  6016. }
  6017. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6018. Headers headers;
  6019. headers.emplace("Accept-Encoding", "gzip, deflate");
  6020. auto res = cli_.Get("/streamed-chunked", headers);
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. EXPECT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ(std::string("123456789"), res->body);
  6024. }
  6025. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6026. Headers headers;
  6027. headers.emplace("Accept-Encoding", "gzip, deflate");
  6028. auto res = cli_.Get("/streamed-chunked2", headers);
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. EXPECT_EQ(std::string("123456789"), res->body);
  6032. }
  6033. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6034. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. }
  6038. TEST(GzipDecompressor, ChunkedDecompression) {
  6039. std::string data;
  6040. for (size_t i = 0; i < 32 * 1024; ++i) {
  6041. data.push_back(static_cast<char>('a' + i % 26));
  6042. }
  6043. std::string compressed_data;
  6044. {
  6045. httplib::detail::gzip_compressor compressor;
  6046. bool result = compressor.compress(
  6047. data.data(), data.size(),
  6048. /*last=*/true,
  6049. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6050. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6051. compressed_data_size);
  6052. return true;
  6053. });
  6054. ASSERT_TRUE(result);
  6055. }
  6056. std::string decompressed_data;
  6057. {
  6058. httplib::detail::gzip_decompressor decompressor;
  6059. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6060. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6061. size_t chunk_size = 130;
  6062. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6063. chunk_begin += chunk_size) {
  6064. size_t current_chunk_size =
  6065. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6066. bool result = decompressor.decompress(
  6067. compressed_data.data() + chunk_begin, current_chunk_size,
  6068. [&](const char *decompressed_data_chunk,
  6069. size_t decompressed_data_chunk_size) {
  6070. decompressed_data.insert(decompressed_data.size(),
  6071. decompressed_data_chunk,
  6072. decompressed_data_chunk_size);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(result);
  6076. }
  6077. }
  6078. ASSERT_EQ(data, decompressed_data);
  6079. }
  6080. TEST(GzipDecompressor, DeflateDecompression) {
  6081. std::string original_text = "Raw deflate without gzip";
  6082. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6083. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6084. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6085. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6086. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6087. std::string decompressed_data;
  6088. {
  6089. httplib::detail::gzip_decompressor decompressor;
  6090. bool result = decompressor.decompress(
  6091. compressed_data.data(), compressed_data.size(),
  6092. [&](const char *decompressed_data_chunk,
  6093. size_t decompressed_data_chunk_size) {
  6094. decompressed_data.insert(decompressed_data.size(),
  6095. decompressed_data_chunk,
  6096. decompressed_data_chunk_size);
  6097. return true;
  6098. });
  6099. ASSERT_TRUE(result);
  6100. }
  6101. ASSERT_EQ(original_text, decompressed_data);
  6102. }
  6103. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6104. std::string original_text = "Raw deflate without gzip";
  6105. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6106. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6107. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6108. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6109. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6110. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6111. std::string decompressed_data;
  6112. {
  6113. httplib::detail::gzip_decompressor decompressor;
  6114. bool result = decompressor.decompress(
  6115. compressed_data.data(), compressed_data.size(),
  6116. [&](const char *decompressed_data_chunk,
  6117. size_t decompressed_data_chunk_size) {
  6118. decompressed_data.insert(decompressed_data.size(),
  6119. decompressed_data_chunk,
  6120. decompressed_data_chunk_size);
  6121. return true;
  6122. });
  6123. ASSERT_TRUE(result);
  6124. }
  6125. ASSERT_EQ(original_text, decompressed_data);
  6126. }
  6127. #endif
  6128. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6129. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6130. Headers headers;
  6131. headers.emplace("Accept-Encoding", "br");
  6132. auto res = cli_.Get("/streamed-chunked", headers);
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. EXPECT_EQ(std::string("123456789"), res->body);
  6136. }
  6137. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "br");
  6140. auto res = cli_.Get("/streamed-chunked2", headers);
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::OK_200, res->status);
  6143. EXPECT_EQ(std::string("123456789"), res->body);
  6144. }
  6145. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6146. cli_.set_compress(true);
  6147. auto res = cli_.Put(
  6148. "/put", 3,
  6149. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6150. sink.os << "PUT";
  6151. return true;
  6152. },
  6153. "text/plain");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ("PUT", res->body);
  6157. }
  6158. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6159. cli_.set_compress(true);
  6160. auto res = cli_.Put(
  6161. "/put",
  6162. [](size_t /*offset*/, DataSink &sink) {
  6163. sink.os << "PUT";
  6164. sink.done();
  6165. return true;
  6166. },
  6167. "text/plain");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. EXPECT_EQ("PUT", res->body);
  6171. }
  6172. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6173. cli_.set_compress(true);
  6174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. EXPECT_EQ(LARGE_DATA, res->body);
  6178. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6179. }
  6180. #endif
  6181. TEST_F(ServerTest, Patch) {
  6182. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PATCH", res->body);
  6186. }
  6187. TEST_F(ServerTest, Delete) {
  6188. auto res = cli_.Delete("/delete");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. EXPECT_EQ("DELETE", res->body);
  6192. }
  6193. TEST_F(ServerTest, DeleteContentReceiver) {
  6194. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6196. EXPECT_EQ(StatusCode::OK_200, res->status);
  6197. EXPECT_EQ("content", res->body);
  6198. }
  6199. TEST_F(ServerTest, Options) {
  6200. auto res = cli_.Options("*");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6204. EXPECT_TRUE(res->body.empty());
  6205. }
  6206. TEST_F(ServerTest, URL) {
  6207. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. }
  6211. TEST_F(ServerTest, ArrayParam) {
  6212. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, ArrayParamValues) {
  6217. auto res =
  6218. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. }
  6222. TEST_F(ServerTest, NoMultipleHeaders) {
  6223. Headers headers = {{"Content-Length", "5"}};
  6224. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6225. "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::OK_200, res->status);
  6228. }
  6229. TEST_F(ServerTest, PostContentReceiver) {
  6230. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ("content", res->body);
  6234. }
  6235. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6236. UploadFormDataItems items = {
  6237. {"text1", "text default", "", ""},
  6238. {"text2", "aωb", "", ""},
  6239. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6240. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6241. {"file3", "", "", "application/octet-stream"},
  6242. };
  6243. auto res = cli_.Post("/content_receiver", items);
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. }
  6247. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6248. UploadFormDataItems items = {
  6249. {"text1", "text default", "", ""},
  6250. {"text2", "aωb", "", ""},
  6251. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6252. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6253. {"file3", "", "", "application/octet-stream"},
  6254. };
  6255. auto boundary = std::string("+++++");
  6256. std::string body;
  6257. for (const auto &item : items) {
  6258. body += "--" + boundary + "\r\n";
  6259. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6260. if (!item.filename.empty()) {
  6261. body += "; filename=\"" + item.filename + "\"";
  6262. }
  6263. body += "\r\n";
  6264. if (!item.content_type.empty()) {
  6265. body += "Content-Type: " + item.content_type + "\r\n";
  6266. }
  6267. body += "\r\n";
  6268. body += item.content + "\r\n";
  6269. }
  6270. body += "--" + boundary + "--\r\n";
  6271. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6272. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST(MultipartFormDataTest, FieldEscaping) {
  6277. Server svr;
  6278. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6279. const ContentReader &content_reader) {
  6280. ASSERT_TRUE(req.is_multipart_form_data());
  6281. std::vector<FormData> received;
  6282. content_reader(
  6283. [&](const FormData &file) {
  6284. received.push_back(file);
  6285. return true;
  6286. },
  6287. [&](const char *data, size_t data_length) {
  6288. received.back().content.append(data, data_length);
  6289. return true;
  6290. });
  6291. // '"', CR and LF in names and filenames are escaped following the
  6292. // WHATWG HTML standard, so each part still parses as a single part
  6293. // with no injected headers. Content types get CR/LF escaped too,
  6294. // while '"' (legal there, e.g. quoted charset) is preserved.
  6295. ASSERT_EQ(4U, received.size());
  6296. EXPECT_EQ("na%22me", received[0].name);
  6297. EXPECT_EQ("quoted name", received[0].content);
  6298. EXPECT_EQ("file", received[1].name);
  6299. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6300. received[1].filename);
  6301. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6302. EXPECT_EQ("injected", received[1].content);
  6303. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6304. EXPECT_EQ("my%22file.txt", received[2].filename);
  6305. EXPECT_EQ("cr lf name", received[2].content);
  6306. EXPECT_EQ("typed", received[3].name);
  6307. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6308. received[3].content_type);
  6309. EXPECT_EQ("typed content", received[3].content);
  6310. });
  6311. auto port = svr.bind_to_any_port("localhost");
  6312. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6313. auto se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. t.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client cli("localhost", port);
  6320. UploadFormDataItems items = {
  6321. {"na\"me", "quoted name", "", ""},
  6322. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6323. "application/octet-stream"},
  6324. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6325. {"typed", "typed content", "",
  6326. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6327. };
  6328. auto res = cli.Post("/post", items);
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. }
  6332. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6333. const UploadFormDataItems items = {
  6334. {"name1", "Content 1", "", ""},
  6335. {"name2", "Content 2", "file2.txt", "text/plain"},
  6336. };
  6337. Server svr;
  6338. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6339. const ContentReader &content_reader) {
  6340. ASSERT_TRUE(req.is_multipart_form_data());
  6341. std::vector<FormData> received;
  6342. content_reader(
  6343. [&](const FormData &file) {
  6344. received.push_back(file);
  6345. return true;
  6346. },
  6347. [&](const char *data, size_t data_length) {
  6348. received.back().content.append(data, data_length);
  6349. return true;
  6350. });
  6351. ASSERT_EQ(2U, received.size());
  6352. EXPECT_EQ("name1", received[0].name);
  6353. EXPECT_EQ("Content 1", received[0].content);
  6354. EXPECT_EQ("name2", received[1].name);
  6355. EXPECT_EQ("Content 2", received[1].content);
  6356. EXPECT_EQ("file2.txt", received[1].filename);
  6357. EXPECT_EQ("text/plain", received[1].content_type);
  6358. });
  6359. auto port = svr.bind_to_any_port("localhost");
  6360. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6361. auto se = detail::scope_exit([&] {
  6362. svr.stop();
  6363. t.join();
  6364. ASSERT_FALSE(svr.is_running());
  6365. });
  6366. svr.wait_until_ready();
  6367. Client cli("localhost", port);
  6368. // Whole-body serialization with a generated boundary
  6369. {
  6370. MultipartFormDataWriter writer;
  6371. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6372. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6373. writer.content_type());
  6374. auto body = writer.serialize(items);
  6375. EXPECT_EQ(body.size(), writer.content_length(items));
  6376. auto res = cli.Post("/post", body, writer.content_type());
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. }
  6380. // Per-part framing with a custom boundary via a content provider
  6381. {
  6382. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6383. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6384. MultipartFormDataWriter writer("custom-boundary_123");
  6385. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6386. std::string body;
  6387. for (const auto &item : items) {
  6388. body += writer.item_begin(item);
  6389. body += item.content;
  6390. body += MultipartFormDataWriter::item_end();
  6391. }
  6392. body += writer.finish();
  6393. EXPECT_EQ(body.size(), writer.content_length(items));
  6394. auto res = cli.Post(
  6395. "/post", body.size(),
  6396. [&](size_t offset, size_t length, DataSink &sink) {
  6397. sink.write(body.data() + offset, length);
  6398. return true;
  6399. },
  6400. writer.content_type());
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::OK_200, res->status);
  6403. }
  6404. }
  6405. TEST_F(ServerTest, PostContentReceiverGzip) {
  6406. cli_.set_compress(true);
  6407. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. ASSERT_EQ(StatusCode::OK_200, res->status);
  6410. ASSERT_EQ("content", res->body);
  6411. }
  6412. TEST_F(ServerTest, PutContentReceiver) {
  6413. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. ASSERT_EQ(StatusCode::OK_200, res->status);
  6416. ASSERT_EQ("content", res->body);
  6417. }
  6418. TEST_F(ServerTest, PatchContentReceiver) {
  6419. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. ASSERT_EQ("content", res->body);
  6423. }
  6424. template <typename ClientType>
  6425. void TestWithHeadersAndContentReceiver(
  6426. ClientType &cli,
  6427. std::function<Result(ClientType &, const std::string &, const Headers &,
  6428. const std::string &, const std::string &,
  6429. ContentReceiver, DownloadProgress)>
  6430. request_func) {
  6431. Headers headers;
  6432. headers.emplace("X-Custom-Header", "test-value");
  6433. std::string received_body;
  6434. auto res = request_func(
  6435. cli, "/content_receiver", headers, "content", "application/json",
  6436. [&](const char *data, size_t data_length) {
  6437. received_body.append(data, data_length);
  6438. return true;
  6439. },
  6440. nullptr);
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("content", received_body);
  6444. }
  6445. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6446. #ifdef CPPHTTPLIB_SSL_ENABLED
  6447. using ClientT = SSLClient;
  6448. #else
  6449. using ClientT = Client;
  6450. #endif
  6451. TestWithHeadersAndContentReceiver<ClientT>(
  6452. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6453. const std::string &body, const std::string &content_type,
  6454. ContentReceiver receiver, DownloadProgress progress) {
  6455. return cli.Post(path, headers, body, content_type, receiver, progress);
  6456. });
  6457. }
  6458. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6459. #ifdef CPPHTTPLIB_SSL_ENABLED
  6460. using ClientT = SSLClient;
  6461. #else
  6462. using ClientT = Client;
  6463. #endif
  6464. TestWithHeadersAndContentReceiver<ClientT>(
  6465. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6466. const std::string &body, const std::string &content_type,
  6467. ContentReceiver receiver, DownloadProgress progress) {
  6468. return cli.Put(path, headers, body, content_type, receiver, progress);
  6469. });
  6470. }
  6471. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6472. #ifdef CPPHTTPLIB_SSL_ENABLED
  6473. using ClientT = SSLClient;
  6474. #else
  6475. using ClientT = Client;
  6476. #endif
  6477. TestWithHeadersAndContentReceiver<ClientT>(
  6478. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6479. const std::string &body, const std::string &content_type,
  6480. ContentReceiver receiver, DownloadProgress progress) {
  6481. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6482. });
  6483. }
  6484. template <typename ClientType>
  6485. void TestWithHeadersAndContentReceiverWithProgress(
  6486. ClientType &cli,
  6487. std::function<Result(ClientType &, const std::string &, const Headers &,
  6488. const std::string &, const std::string &,
  6489. ContentReceiver, DownloadProgress)>
  6490. request_func) {
  6491. Headers headers;
  6492. headers.emplace("X-Test-Header", "progress-test");
  6493. std::string received_body;
  6494. auto progress_called = false;
  6495. auto res = request_func(
  6496. cli, "/content_receiver", headers, "content", "text/plain",
  6497. [&](const char *data, size_t data_length) {
  6498. received_body.append(data, data_length);
  6499. return true;
  6500. },
  6501. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6502. progress_called = true;
  6503. return true;
  6504. });
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ("content", received_body);
  6508. EXPECT_TRUE(progress_called);
  6509. }
  6510. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6511. #ifdef CPPHTTPLIB_SSL_ENABLED
  6512. using ClientT = SSLClient;
  6513. #else
  6514. using ClientT = Client;
  6515. #endif
  6516. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6517. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6518. const std::string &body, const std::string &content_type,
  6519. ContentReceiver receiver, DownloadProgress progress) {
  6520. return cli.Post(path, headers, body, content_type, receiver, progress);
  6521. });
  6522. }
  6523. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6524. #ifdef CPPHTTPLIB_SSL_ENABLED
  6525. using ClientT = SSLClient;
  6526. #else
  6527. using ClientT = Client;
  6528. #endif
  6529. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6531. const std::string &body, const std::string &content_type,
  6532. ContentReceiver receiver, DownloadProgress progress) {
  6533. return cli.Put(path, headers, body, content_type, receiver, progress);
  6534. });
  6535. }
  6536. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6537. #ifdef CPPHTTPLIB_SSL_ENABLED
  6538. using ClientT = SSLClient;
  6539. #else
  6540. using ClientT = Client;
  6541. #endif
  6542. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6544. const std::string &body, const std::string &content_type,
  6545. ContentReceiver receiver, DownloadProgress progress) {
  6546. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6547. });
  6548. }
  6549. template <typename ClientType>
  6550. void TestWithHeadersAndContentReceiverError(
  6551. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6552. const Headers &, const std::string &,
  6553. const std::string &, ContentReceiver)>
  6554. request_func) {
  6555. Headers headers;
  6556. headers.emplace("X-Error-Test", "true");
  6557. std::string received_body;
  6558. auto receiver_failed = false;
  6559. auto res =
  6560. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6561. [&](const char *data, size_t data_length) {
  6562. received_body.append(data, data_length);
  6563. receiver_failed = true;
  6564. return false;
  6565. });
  6566. ASSERT_FALSE(res);
  6567. EXPECT_TRUE(receiver_failed);
  6568. }
  6569. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6570. #ifdef CPPHTTPLIB_SSL_ENABLED
  6571. using ClientT = SSLClient;
  6572. #else
  6573. using ClientT = Client;
  6574. #endif
  6575. TestWithHeadersAndContentReceiverError<ClientT>(
  6576. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6577. const std::string &body, const std::string &content_type,
  6578. ContentReceiver receiver) {
  6579. return cli.Post(path, headers, body, content_type, receiver);
  6580. });
  6581. }
  6582. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6583. #ifdef CPPHTTPLIB_SSL_ENABLED
  6584. using ClientT = SSLClient;
  6585. #else
  6586. using ClientT = Client;
  6587. #endif
  6588. TestWithHeadersAndContentReceiverError<ClientT>(
  6589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6590. const std::string &body, const std::string &content_type,
  6591. ContentReceiver receiver) {
  6592. return cli.Put(path, headers, body, content_type, receiver);
  6593. });
  6594. }
  6595. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6596. #ifdef CPPHTTPLIB_SSL_ENABLED
  6597. using ClientT = SSLClient;
  6598. #else
  6599. using ClientT = Client;
  6600. #endif
  6601. TestWithHeadersAndContentReceiverError<ClientT>(
  6602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6603. const std::string &body, const std::string &content_type,
  6604. ContentReceiver receiver) {
  6605. return cli.Patch(path, headers, body, content_type, receiver);
  6606. });
  6607. }
  6608. TEST_F(ServerTest, PostQueryStringAndBody) {
  6609. auto res =
  6610. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. TEST_F(ServerTest, HTTP2Magic) {
  6615. Request req;
  6616. req.method = "PRI";
  6617. req.path = "*";
  6618. req.body = "SM";
  6619. auto res = std::make_shared<Response>();
  6620. auto error = Error::Success;
  6621. auto ret = cli_.send(req, *res, error);
  6622. ASSERT_TRUE(ret);
  6623. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6624. }
  6625. TEST_F(ServerTest, KeepAlive) {
  6626. auto res = cli_.Get("/hi");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6630. EXPECT_EQ("Hello World!", res->body);
  6631. res = cli_.Get("/hi");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6635. EXPECT_EQ("Hello World!", res->body);
  6636. res = cli_.Get("/hi");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6640. EXPECT_EQ("Hello World!", res->body);
  6641. res = cli_.Get("/not-exist");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6644. res = cli_.Post("/empty", "", "text/plain");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6648. EXPECT_EQ("empty", res->body);
  6649. EXPECT_EQ("close", res->get_header_value("Connection"));
  6650. res = cli_.Post(
  6651. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6652. "text/plain");
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6656. EXPECT_EQ("empty", res->body);
  6657. cli_.set_keep_alive(false);
  6658. res = cli_.Get("/last-request");
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ("close", res->get_header_value("Connection"));
  6662. }
  6663. TEST_F(ServerTest, TooManyRedirect) {
  6664. cli_.set_follow_location(true);
  6665. auto res = cli_.Get("/redirect/0");
  6666. ASSERT_TRUE(!res);
  6667. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6668. }
  6669. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6670. Request req;
  6671. req.method = "FOOBAR";
  6672. req.path = "/hi";
  6673. cli_.set_keep_alive(true);
  6674. auto res = cli_.send(req);
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6677. EXPECT_EQ("close", res->get_header_value("Connection"));
  6678. EXPECT_FALSE(cli_.is_socket_open());
  6679. }
  6680. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6682. TEST_F(ServerTest, Gzip) {
  6683. Headers headers;
  6684. headers.emplace("Accept-Encoding", "gzip, deflate");
  6685. auto res = cli_.Get("/compress", headers);
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6689. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6690. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6691. "7890123456789012345678901234567890",
  6692. res->body);
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6696. Headers headers;
  6697. headers.emplace("Accept-Encoding", "gzip, deflate");
  6698. auto res = cli_.Get("/compress-with-charset", headers);
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6701. EXPECT_EQ("application/json; charset=utf-8",
  6702. res->get_header_value("Content-Type"));
  6703. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6704. "7890123456789012345678901234567890",
  6705. res->body);
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. }
  6708. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6709. Headers headers;
  6710. headers.emplace("Accept-Encoding", "");
  6711. auto res = cli_.Get("/compress", headers);
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6717. "7890123456789012345678901234567890",
  6718. res->body);
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. }
  6721. TEST_F(ServerTest, GzipWithContentReceiver) {
  6722. Headers headers;
  6723. headers.emplace("Accept-Encoding", "gzip, deflate");
  6724. std::string body;
  6725. auto res = cli_.Get("/compress", headers,
  6726. [&](const char *data, uint64_t data_length) {
  6727. EXPECT_EQ(100U, data_length);
  6728. body.append(data, data_length);
  6729. return true;
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6734. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6735. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6736. "7890123456789012345678901234567890",
  6737. body);
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. }
  6740. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6741. Headers headers;
  6742. headers.emplace("Accept-Encoding", "gzip, deflate");
  6743. cli_.set_decompress(false);
  6744. auto res = cli_.Get("/compress", headers);
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6748. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6749. EXPECT_EQ(33U, res->body.size());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. }
  6752. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6753. Headers headers;
  6754. headers.emplace("Accept-Encoding", "");
  6755. std::string body;
  6756. auto res = cli_.Get("/compress", headers,
  6757. [&](const char *data, uint64_t data_length) {
  6758. EXPECT_EQ(100U, data_length);
  6759. body.append(data, data_length);
  6760. return true;
  6761. });
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6767. "7890123456789012345678901234567890",
  6768. body);
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. }
  6771. TEST_F(ServerTest, NoGzip) {
  6772. Headers headers;
  6773. headers.emplace("Accept-Encoding", "gzip, deflate");
  6774. auto res = cli_.Get("/nocompress", headers);
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6777. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6778. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6779. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6780. "7890123456789012345678901234567890",
  6781. res->body);
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. }
  6784. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6785. Headers headers;
  6786. headers.emplace("Accept-Encoding", "gzip, deflate");
  6787. std::string body;
  6788. auto res = cli_.Get("/nocompress", headers,
  6789. [&](const char *data, uint64_t data_length) {
  6790. EXPECT_EQ(100U, data_length);
  6791. body.append(data, data_length);
  6792. return true;
  6793. });
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6796. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6797. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6799. "7890123456789012345678901234567890",
  6800. body);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, MultipartFormDataGzip) {
  6804. UploadFormDataItems items = {
  6805. {"key1", "test", "", ""},
  6806. {"key2", "--abcdefg123", "", ""},
  6807. };
  6808. cli_.set_compress(true);
  6809. auto res = cli_.Post("/compress-multipart", items);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. #endif
  6814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6815. TEST_F(ServerTest, Brotli) {
  6816. Headers headers;
  6817. headers.emplace("Accept-Encoding", "br");
  6818. auto res = cli_.Get("/compress", headers);
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6822. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6823. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6824. "7890123456789012345678901234567890",
  6825. res->body);
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6830. TEST_F(ServerTest, Zstd) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "zstd");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6839. "7890123456789012345678901234567890",
  6840. res->body);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6844. Headers headers;
  6845. headers.emplace("Accept-Encoding", "");
  6846. auto res = cli_.Get("/compress", headers);
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6850. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6852. "7890123456789012345678901234567890",
  6853. res->body);
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. }
  6856. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6857. Headers headers;
  6858. headers.emplace("Accept-Encoding", "zstd");
  6859. std::string body;
  6860. auto res = cli_.Get("/compress", headers,
  6861. [&](const char *data, uint64_t data_length) {
  6862. EXPECT_EQ(100U, data_length);
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6870. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6871. "7890123456789012345678901234567890",
  6872. body);
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. }
  6875. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "zstd");
  6878. cli_.set_decompress(false);
  6879. auto res = cli_.Get("/compress", headers);
  6880. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6881. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6882. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6883. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6887. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. ASSERT_EQ(26U, res->body.size());
  6890. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6891. 0);
  6892. }
  6893. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6894. Headers headers;
  6895. headers.emplace("Accept-Encoding", "");
  6896. std::string body;
  6897. auto res = cli_.Get("/compress", headers,
  6898. [&](const char *data, uint64_t data_length) {
  6899. EXPECT_EQ(100U, data_length);
  6900. body.append(data, data_length);
  6901. return true;
  6902. });
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6906. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6907. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6908. "7890123456789012345678901234567890",
  6909. body);
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, NoZstd) {
  6913. Headers headers;
  6914. headers.emplace("Accept-Encoding", "zstd");
  6915. auto res = cli_.Get("/nocompress", headers);
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6918. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6921. "7890123456789012345678901234567890",
  6922. res->body);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. }
  6925. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6926. Headers headers;
  6927. headers.emplace("Accept-Encoding", "zstd");
  6928. std::string body;
  6929. auto res = cli_.Get("/nocompress", headers,
  6930. [&](const char *data, uint64_t data_length) {
  6931. EXPECT_EQ(100U, data_length);
  6932. body.append(data, data_length);
  6933. return true;
  6934. });
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6937. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6938. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6940. "7890123456789012345678901234567890",
  6941. body);
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. }
  6944. // TODO: How to enable zstd ??
  6945. TEST_F(ServerTest, MultipartFormDataZstd) {
  6946. UploadFormDataItems items = {
  6947. {"key1", "test", "", ""},
  6948. {"key2", "--abcdefg123", "", ""},
  6949. };
  6950. Headers headers;
  6951. headers.emplace("Accept-Encoding", "zstd");
  6952. cli_.set_compress(true);
  6953. auto res = cli_.Post("/compress-multipart", headers, items);
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. }
  6957. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6958. Headers headers;
  6959. headers.emplace("Accept-Encoding", "zstd");
  6960. cli_.set_compress(true);
  6961. auto res = cli_.Put(
  6962. "/put", headers, 3,
  6963. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6964. sink.os << "PUT";
  6965. return true;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("PUT", res->body);
  6971. }
  6972. // Pre-compression logging tests
  6973. TEST_F(ServerTest, PreCompressionLogging) {
  6974. // Test data for compression (matches the actual /compress endpoint content)
  6975. const std::string test_content =
  6976. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6977. "3456789012345678901234567890";
  6978. // Variables to capture logging data
  6979. std::string pre_compression_body;
  6980. std::string pre_compression_content_type;
  6981. std::string pre_compression_content_encoding;
  6982. std::string post_compression_body;
  6983. std::string post_compression_content_type;
  6984. std::string post_compression_content_encoding;
  6985. // Set up pre-compression logger
  6986. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6987. const Response &res) {
  6988. pre_compression_body = res.body;
  6989. pre_compression_content_type = res.get_header_value("Content-Type");
  6990. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6991. });
  6992. // Set up post-compression logger
  6993. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6994. post_compression_body = res.body;
  6995. post_compression_content_type = res.get_header_value("Content-Type");
  6996. post_compression_content_encoding =
  6997. res.get_header_value("Content-Encoding");
  6998. });
  6999. // Test with gzip compression
  7000. Headers headers;
  7001. headers.emplace("Accept-Encoding", "gzip");
  7002. auto res = cli_.Get("/compress", headers);
  7003. // Verify response was compressed
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7007. // Verify pre-compression logger captured uncompressed content
  7008. EXPECT_EQ(test_content, pre_compression_body);
  7009. EXPECT_EQ("text/plain", pre_compression_content_type);
  7010. EXPECT_TRUE(pre_compression_content_encoding
  7011. .empty()); // No encoding header before compression
  7012. // Verify post-compression logger captured compressed content
  7013. EXPECT_NE(test_content,
  7014. post_compression_body); // Should be different after compression
  7015. EXPECT_EQ("text/plain", post_compression_content_type);
  7016. EXPECT_EQ("gzip", post_compression_content_encoding);
  7017. // Verify compressed content is smaller
  7018. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7019. }
  7020. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7021. const std::string test_content =
  7022. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7023. "3456789012345678901234567890";
  7024. std::string pre_compression_body;
  7025. std::string post_compression_body;
  7026. svr_.set_pre_compression_logger(
  7027. [&](const Request & /*req*/, const Response &res) {
  7028. pre_compression_body = res.body;
  7029. });
  7030. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7031. post_compression_body = res.body;
  7032. });
  7033. Headers headers;
  7034. headers.emplace("Accept-Encoding", "br");
  7035. auto res = cli_.Get("/compress", headers);
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7039. // Verify pre-compression content is uncompressed
  7040. EXPECT_EQ(test_content, pre_compression_body);
  7041. // Verify post-compression content is compressed
  7042. EXPECT_NE(test_content, post_compression_body);
  7043. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7044. }
  7045. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7046. const std::string test_content =
  7047. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7048. "3456789012345678901234567890";
  7049. std::string pre_compression_body;
  7050. std::string post_compression_body;
  7051. svr_.set_pre_compression_logger(
  7052. [&](const Request & /*req*/, const Response &res) {
  7053. pre_compression_body = res.body;
  7054. });
  7055. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7056. post_compression_body = res.body;
  7057. });
  7058. // Request without compression (use /nocompress endpoint)
  7059. Headers headers;
  7060. auto res = cli_.Get("/nocompress", headers);
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7064. // Pre-compression logger should not be called when no compression is applied
  7065. EXPECT_TRUE(
  7066. pre_compression_body.empty()); // Pre-compression logger not called
  7067. EXPECT_EQ(
  7068. test_content,
  7069. post_compression_body); // Post-compression logger captures final content
  7070. }
  7071. TEST_F(ServerTest, LoggerSeesContentLength) {
  7072. size_t logged_content_length = 0;
  7073. std::string logged_content_length_header;
  7074. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7075. logged_content_length = res.content_length_;
  7076. logged_content_length_header = res.get_header_value("Content-Length");
  7077. });
  7078. auto res = cli_.Get("/nocompress");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ(res->body.size(), logged_content_length);
  7082. EXPECT_EQ(std::to_string(logged_content_length),
  7083. logged_content_length_header);
  7084. }
  7085. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7086. const std::string test_content =
  7087. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7088. "3456789012345678901234567890";
  7089. std::string pre_compression_body;
  7090. bool pre_logger_called = false;
  7091. // Set only pre-compression logger
  7092. svr_.set_pre_compression_logger(
  7093. [&](const Request & /*req*/, const Response &res) {
  7094. pre_compression_body = res.body;
  7095. pre_logger_called = true;
  7096. });
  7097. Headers headers;
  7098. headers.emplace("Accept-Encoding", "gzip");
  7099. auto res = cli_.Get("/compress", headers);
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::OK_200, res->status);
  7102. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7103. // Verify pre-compression logger was called
  7104. EXPECT_TRUE(pre_logger_called);
  7105. EXPECT_EQ(test_content, pre_compression_body);
  7106. }
  7107. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7108. {
  7109. // Test with Expect: 100-continue header - success case
  7110. // Server returns 100 Continue, client sends body, server returns 200 OK
  7111. Request req;
  7112. req.method = "POST";
  7113. req.path = "/post-large";
  7114. req.set_header("Expect", "100-continue");
  7115. req.body = LARGE_DATA;
  7116. Response res;
  7117. auto error = Error::Success;
  7118. cli_.set_keep_alive(true);
  7119. auto ret = cli_.send(req, res, error);
  7120. EXPECT_TRUE(ret);
  7121. EXPECT_EQ(StatusCode::OK_200, res.status);
  7122. EXPECT_EQ(LARGE_DATA, res.body);
  7123. }
  7124. {
  7125. // Test with Expect: 100-continue header - error case
  7126. // Client should not send the body when server returns an error
  7127. Request req;
  7128. req.method = "POST";
  7129. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7130. req.set_header("Expect", "100-continue");
  7131. req.body = LARGE_DATA;
  7132. Response res;
  7133. auto error = Error::Success;
  7134. auto start = std::chrono::high_resolution_clock::now();
  7135. cli_.set_keep_alive(true);
  7136. auto ret = cli_.send(req, res, error);
  7137. auto end = std::chrono::high_resolution_clock::now();
  7138. auto elapsed =
  7139. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7140. .count();
  7141. // With Expect: 100-continue, request completes successfully but with error
  7142. EXPECT_TRUE(ret);
  7143. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7144. EXPECT_EQ("close", res.get_header_value("Connection"));
  7145. EXPECT_FALSE(cli_.is_socket_open());
  7146. EXPECT_LE(elapsed, 2000);
  7147. }
  7148. {
  7149. // Send an extra GET request to ensure error recovery without hanging
  7150. Request req;
  7151. req.method = "GET";
  7152. req.path = "/hi";
  7153. auto start = std::chrono::high_resolution_clock::now();
  7154. auto res = cli_.send(req);
  7155. auto end = std::chrono::high_resolution_clock::now();
  7156. auto elapsed =
  7157. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7158. .count();
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. EXPECT_EQ("Hello World!", res->body);
  7162. EXPECT_LE(elapsed, 500);
  7163. }
  7164. }
  7165. TEST(ZstdDecompressor, ChunkedDecompression) {
  7166. std::string data;
  7167. for (size_t i = 0; i < 32 * 1024; ++i) {
  7168. data.push_back(static_cast<char>('a' + i % 26));
  7169. }
  7170. std::string compressed_data;
  7171. {
  7172. httplib::detail::zstd_compressor compressor;
  7173. bool result = compressor.compress(
  7174. data.data(), data.size(),
  7175. /*last=*/true,
  7176. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7177. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7178. compressed_data_size);
  7179. return true;
  7180. });
  7181. ASSERT_TRUE(result);
  7182. }
  7183. std::string decompressed_data;
  7184. {
  7185. httplib::detail::zstd_decompressor decompressor;
  7186. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7187. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7188. size_t chunk_size = 130;
  7189. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7190. chunk_begin += chunk_size) {
  7191. size_t current_chunk_size =
  7192. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7193. bool result = decompressor.decompress(
  7194. compressed_data.data() + chunk_begin, current_chunk_size,
  7195. [&](const char *decompressed_data_chunk,
  7196. size_t decompressed_data_chunk_size) {
  7197. decompressed_data.insert(decompressed_data.size(),
  7198. decompressed_data_chunk,
  7199. decompressed_data_chunk_size);
  7200. return true;
  7201. });
  7202. ASSERT_TRUE(result);
  7203. }
  7204. }
  7205. ASSERT_EQ(data, decompressed_data);
  7206. }
  7207. TEST(ZstdDecompressor, Decompress) {
  7208. std::string original_text = "Compressed with ZSTD";
  7209. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7210. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7211. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7212. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7213. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7214. std::string decompressed_data;
  7215. {
  7216. httplib::detail::zstd_decompressor decompressor;
  7217. bool result = decompressor.decompress(
  7218. compressed_data.data(), compressed_data.size(),
  7219. [&](const char *decompressed_data_chunk,
  7220. size_t decompressed_data_chunk_size) {
  7221. decompressed_data.insert(decompressed_data.size(),
  7222. decompressed_data_chunk,
  7223. decompressed_data_chunk_size);
  7224. return true;
  7225. });
  7226. ASSERT_TRUE(result);
  7227. }
  7228. ASSERT_EQ(original_text, decompressed_data);
  7229. }
  7230. #endif
  7231. // Sends a raw request to a server listening at HOST:PORT.
  7232. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7233. std::string *resp = nullptr, int port = PORT) {
  7234. auto error = Error::Success;
  7235. auto client_sock = detail::create_client_socket(
  7236. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7237. /*connection_timeout_sec=*/5, 0,
  7238. /*read_timeout_sec=*/5, 0,
  7239. /*write_timeout_sec=*/5, 0, std::string(), error);
  7240. if (client_sock == INVALID_SOCKET) { return false; }
  7241. auto ret = detail::process_client_socket(
  7242. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7243. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7244. if (req.size() !=
  7245. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7246. return false;
  7247. }
  7248. char buf[512];
  7249. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7250. while (line_reader.getline()) {
  7251. if (resp) { *resp += line_reader.ptr(); }
  7252. }
  7253. return true;
  7254. });
  7255. detail::close_socket(client_sock);
  7256. return ret;
  7257. }
  7258. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7259. Server svr;
  7260. std::string header_value;
  7261. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7262. header_value = req.get_header_value("foo");
  7263. res.set_content("ok", "text/plain");
  7264. });
  7265. thread t = thread([&] { svr.listen(HOST, PORT); });
  7266. auto se = detail::scope_exit([&] {
  7267. svr.stop();
  7268. t.join();
  7269. ASSERT_FALSE(svr.is_running());
  7270. });
  7271. svr.wait_until_ready();
  7272. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7273. // like characters are not treated the same - use vertical tab and escape.
  7274. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7275. "foo: \t \v bar \x1B\t \r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. std::string res;
  7279. ASSERT_TRUE(send_request(5, req, &res));
  7280. EXPECT_EQ(header_value, "");
  7281. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7282. }
  7283. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7284. Server svr;
  7285. std::string received;
  7286. svr.Get("/order", [&](const Request &req, Response &res) {
  7287. received = entries_to_string(req.headers);
  7288. res.set_content("ok", "text/plain");
  7289. });
  7290. auto port = svr.bind_to_any_port(HOST);
  7291. thread t = thread([&] { svr.listen_after_bind(); });
  7292. auto se = detail::scope_exit([&] {
  7293. svr.stop();
  7294. t.join();
  7295. ASSERT_FALSE(svr.is_running());
  7296. });
  7297. svr.wait_until_ready();
  7298. const std::string req = "GET /order HTTP/1.1\r\n"
  7299. "X-First: 1\r\n"
  7300. "X-Dup: a\r\n"
  7301. "X-Second: 2\r\n"
  7302. "X-Dup: b\r\n"
  7303. "Connection: close\r\n"
  7304. "\r\n";
  7305. std::string res;
  7306. ASSERT_TRUE(send_request(5, req, &res, port));
  7307. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7308. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7309. }
  7310. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7311. Server svr;
  7312. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7313. res.set_header("Set-Cookie", "first=1");
  7314. res.set_header("X-Between", "y");
  7315. res.set_header("Set-Cookie", "second=2");
  7316. res.set_content("ok", "text/plain");
  7317. });
  7318. auto port = svr.bind_to_any_port(HOST);
  7319. thread t = thread([&] { svr.listen_after_bind(); });
  7320. auto se = detail::scope_exit([&] {
  7321. svr.stop();
  7322. t.join();
  7323. ASSERT_FALSE(svr.is_running());
  7324. });
  7325. svr.wait_until_ready();
  7326. Client cli(HOST, port);
  7327. auto res = cli.Get("/cookies");
  7328. ASSERT_TRUE(res);
  7329. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7330. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7331. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7332. }
  7333. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7334. Server svr;
  7335. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7336. auto i = new int(0);
  7337. res.set_header("Trailer", "X-Safe, X-Reflected");
  7338. res.set_chunked_content_provider(
  7339. "text/plain",
  7340. [i](size_t /*offset*/, DataSink &sink) {
  7341. if (*i == 0) {
  7342. sink.os << "body";
  7343. } else {
  7344. Headers trailer;
  7345. // A valid trailer that must survive.
  7346. trailer.emplace("X-Safe", "safe");
  7347. // Attacker-controlled value carrying CR/LF (response splitting).
  7348. trailer.emplace("X-Reflected",
  7349. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7350. // Attacker-controlled name carrying CR/LF.
  7351. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7352. sink.done_with_trailer(trailer);
  7353. }
  7354. (*i)++;
  7355. return true;
  7356. },
  7357. [i](bool /*success*/) { delete i; });
  7358. });
  7359. thread t = thread([&] { svr.listen(HOST, PORT); });
  7360. auto se = detail::scope_exit([&] {
  7361. svr.stop();
  7362. t.join();
  7363. ASSERT_FALSE(svr.is_running());
  7364. });
  7365. svr.wait_until_ready();
  7366. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7367. "Host: " + HOST +
  7368. "\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. std::string res;
  7372. ASSERT_TRUE(send_request(5, req, &res));
  7373. // The injected fields must not appear anywhere in the raw response.
  7374. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7375. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7376. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7377. // Invalid trailers are dropped entirely, matching set_header().
  7378. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7379. // The valid trailer still passes through.
  7380. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7381. }
  7382. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7383. Server svr;
  7384. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7385. // res.headers is a public field an application can populate directly,
  7386. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7387. // A valid header that must survive.
  7388. res.headers.emplace("X-Safe", "safe");
  7389. // Attacker-controlled value carrying CR/LF (response splitting).
  7390. res.headers.emplace("X-Reflected",
  7391. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7392. // Attacker-controlled name carrying CR/LF.
  7393. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7394. res.set_content("body", "text/plain");
  7395. });
  7396. thread t = thread([&] { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. ASSERT_FALSE(svr.is_running());
  7401. });
  7402. svr.wait_until_ready();
  7403. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7404. "Host: " + HOST +
  7405. "\r\n"
  7406. "Connection: close\r\n"
  7407. "\r\n";
  7408. std::string res;
  7409. ASSERT_TRUE(send_request(5, req, &res));
  7410. // The injected fields must not appear anywhere in the raw response.
  7411. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7412. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7413. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7414. // Invalid headers are dropped entirely, matching set_header().
  7415. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7416. // The valid header still passes through.
  7417. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7418. }
  7419. // Forward declaration: in split builds split.py strips `inline` and moves the
  7420. // definition into httplib.cc, so detail::write_request_line is not visible from
  7421. // the public httplib.h. Re-declaring it here lets the tests link against the
  7422. // symbol in both header-only and split builds.
  7423. namespace httplib {
  7424. namespace detail {
  7425. ssize_t write_request_line(Stream &strm, const std::string &method,
  7426. const std::string &path);
  7427. } // namespace detail
  7428. } // namespace httplib
  7429. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7430. // A well-formed target is written verbatim.
  7431. {
  7432. detail::BufferStream strm;
  7433. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7434. EXPECT_GT(n, 0);
  7435. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7436. }
  7437. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7438. // otherwise it splits the request line and injects a header or a whole
  7439. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7440. // when path encoding is disabled.
  7441. const std::string evil_targets[] = {
  7442. "/a\r\nInjected: pwned",
  7443. "/a\rInjected",
  7444. "/a\nInjected",
  7445. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7446. };
  7447. for (const auto &evil : evil_targets) {
  7448. detail::BufferStream strm;
  7449. auto n = detail::write_request_line(strm, "GET", evil);
  7450. EXPECT_LT(n, 0);
  7451. EXPECT_TRUE(strm.get_buffer().empty());
  7452. }
  7453. }
  7454. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7455. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7456. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7457. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7458. // client must fail cleanly with Error::Write instead of putting a
  7459. // request-line-less, header-injecting request on the wire.
  7460. Server svr;
  7461. svr.Get("/a", [](const Request &, Response &res) {
  7462. res.set_content("ok", "text/plain");
  7463. });
  7464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. thread.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. {
  7472. Client cli(HOST, PORT);
  7473. cli.set_path_encode(false);
  7474. // The request is rejected before anything is written, so the connection
  7475. // stays silent and the subsequent response read would otherwise block for
  7476. // the full default read timeout. Shorten it -- the assertion is on the
  7477. // error, not the timeout.
  7478. cli.set_read_timeout(1, 0);
  7479. auto res = cli.Get("/a\r\nInjected: pwned");
  7480. EXPECT_FALSE(res);
  7481. EXPECT_EQ(Error::Write, res.error());
  7482. }
  7483. }
  7484. // Sends a raw request and verifies that there isn't a crash or exception.
  7485. static void test_raw_request(const std::string &req,
  7486. std::string *out = nullptr) {
  7487. Server svr;
  7488. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7489. res.set_content("ok", "text/plain");
  7490. });
  7491. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7492. res.set_content("ok", "text/plain");
  7493. });
  7494. svr.Get("/header_field_value_check",
  7495. [&](const Request & /*req*/, Response &res) {
  7496. res.set_content("ok", "text/plain");
  7497. });
  7498. // Server read timeout must be longer than the client read timeout for the
  7499. // bug to reproduce, probably to force the server to process a request
  7500. // without a trailing blank line.
  7501. const time_t client_read_timeout_sec = 1;
  7502. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7503. bool listen_thread_ok = false;
  7504. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7505. auto se = detail::scope_exit([&] {
  7506. svr.stop();
  7507. t.join();
  7508. ASSERT_FALSE(svr.is_running());
  7509. EXPECT_TRUE(listen_thread_ok);
  7510. });
  7511. svr.wait_until_ready();
  7512. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7513. }
  7514. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7515. // A certain header line causes an exception if the header property is parsed
  7516. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7517. test_raw_request(
  7518. "GET /hi HTTP/1.1\r\n"
  7519. " : "
  7520. " "
  7521. " ");
  7522. }
  7523. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7524. // A certain header line causes an exception if the header property *name* is
  7525. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7526. // greedy matcher and requires backtracking when there are a lot of ":"
  7527. // characters.
  7528. // This occurs with libc++ but not libstdc++.
  7529. test_raw_request(
  7530. "GET /hi HTTP/1.1\r\n"
  7531. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7532. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7533. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7534. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7535. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7536. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7537. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7538. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7539. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7540. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7541. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7542. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7543. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7544. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7545. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7546. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7547. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7548. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7549. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7550. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7551. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7552. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7553. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7554. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7555. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7556. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7557. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7558. "&&&%%%");
  7559. }
  7560. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7561. // Make sure this doesn't crash the server.
  7562. // In a previous version of the header line regex, the "\r" rendered the line
  7563. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7564. // a new position where the leading white space ended and the field value
  7565. // began.
  7566. // The crash occurs with libc++ but not libstdc++.
  7567. test_raw_request("GET /hi HTTP/1.1\r\n"
  7568. "a:" +
  7569. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7570. "\r\n"
  7571. "\r\n");
  7572. }
  7573. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7574. std::string out;
  7575. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7576. "Content-Type: text/plain\r\n"
  7577. "Transfer-Encoding: chunked\r\n"
  7578. "\r\n"
  7579. "nothex\r\n",
  7580. &out);
  7581. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7582. }
  7583. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7584. std::string out;
  7585. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7586. "Content-Type: text/plain\r\n"
  7587. "Transfer-Encoding: chunked\r\n"
  7588. "\r\n"
  7589. "3\r\n"
  7590. "xyz\r\n"
  7591. "NaN\r\n",
  7592. &out);
  7593. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7594. }
  7595. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7596. std::string out;
  7597. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7598. "Content-Type: text/plain\r\n"
  7599. "Transfer-Encoding: chunked\r\n"
  7600. "\r\n"
  7601. // Length is too large for 64 bits.
  7602. "1ffffffffffffffff\r\n"
  7603. "xyz\r\n",
  7604. &out);
  7605. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7606. }
  7607. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7608. test_raw_request("GET /hi HTTP/1.1\r\n"
  7609. "Content-Type: text/plain\r\n\r");
  7610. }
  7611. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7612. std::string out;
  7613. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7614. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7615. }
  7616. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7617. Server svr;
  7618. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7619. EXPECT_TRUE(!req.remote_addr.empty());
  7620. });
  7621. thread t = thread([&] { svr.listen(HOST, PORT); });
  7622. auto se = detail::scope_exit([&] {
  7623. svr.stop();
  7624. t.join();
  7625. ASSERT_FALSE(svr.is_running());
  7626. });
  7627. svr.wait_until_ready();
  7628. // Send an invalid request line to trigger Bad Request
  7629. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7630. std::string out;
  7631. ASSERT_TRUE(send_request(5, bad_req, &out));
  7632. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7633. }
  7634. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7635. std::string out;
  7636. std::string request(
  7637. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7638. test_raw_request(request, &out);
  7639. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7640. }
  7641. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7642. std::string out;
  7643. std::string request(
  7644. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7645. test_raw_request(request, &out);
  7646. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7647. }
  7648. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7649. std::string out;
  7650. std::string request(
  7651. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7652. test_raw_request(request, &out);
  7653. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7654. }
  7655. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7656. std::string out;
  7657. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7658. "Test: \r\n\r\n",
  7659. &out);
  7660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7661. }
  7662. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7663. Server svr;
  7664. std::string x_custom;
  7665. std::string cookie;
  7666. std::string xff;
  7667. std::string x_unicode;
  7668. std::string x_iis;
  7669. svr.Get("/check", [&](const Request &req, Response &res) {
  7670. x_custom = req.get_header_value("X-Custom");
  7671. cookie = req.get_header_value("Cookie");
  7672. xff = req.get_header_value("X-Forwarded-For");
  7673. x_unicode = req.get_header_value("X-Unicode");
  7674. x_iis = req.get_header_value("X-IIS");
  7675. res.set_content("ok", "text/plain");
  7676. });
  7677. thread t = thread([&] { svr.listen(HOST, PORT); });
  7678. auto se = detail::scope_exit([&] {
  7679. svr.stop();
  7680. t.join();
  7681. ASSERT_FALSE(svr.is_running());
  7682. });
  7683. svr.wait_until_ready();
  7684. const std::string req = "GET /check HTTP/1.1\r\n"
  7685. "Host: localhost\r\n"
  7686. "X-Custom: a%0D%0AInjected: b\r\n"
  7687. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7688. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7689. "X-Unicode: %E3%81%82\r\n"
  7690. "X-IIS: %u00E9\r\n"
  7691. "Connection: close\r\n"
  7692. "\r\n";
  7693. std::string res;
  7694. ASSERT_TRUE(send_request(5, req, &res));
  7695. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7696. // Every value must be returned verbatim (wire form), with no decoding.
  7697. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7698. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7699. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7700. EXPECT_EQ("%E3%81%82", x_unicode);
  7701. EXPECT_EQ("%u00E9", x_iis);
  7702. }
  7703. // Applications that previously relied on automatic percent-decoding can
  7704. // reproduce the old behavior by explicitly calling decode_path_component()
  7705. // or, for RFC 3986 conformance, decode_uri_component().
  7706. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7707. Server svr;
  7708. std::string decoded;
  7709. svr.Get("/check", [&](const Request &req, Response &res) {
  7710. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7711. res.set_content("ok", "text/plain");
  7712. });
  7713. thread t = thread([&] { svr.listen(HOST, PORT); });
  7714. auto se = detail::scope_exit([&] {
  7715. svr.stop();
  7716. t.join();
  7717. ASSERT_FALSE(svr.is_running());
  7718. });
  7719. svr.wait_until_ready();
  7720. const std::string req = "GET /check HTTP/1.1\r\n"
  7721. "Host: localhost\r\n"
  7722. "X-Custom: hello%20world\r\n"
  7723. "Connection: close\r\n"
  7724. "\r\n";
  7725. std::string res;
  7726. ASSERT_TRUE(send_request(5, req, &res));
  7727. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7728. EXPECT_EQ("hello world", decoded);
  7729. }
  7730. // Regression test for #2033. Browsers send Referer values that include
  7731. // percent-encoded characters such as %0A inside the URL. Decoding the
  7732. // header value would either trip the post-decode CR/LF/NUL guard (the
  7733. // original bug, returning 400) or, after that guard was relaxed, silently
  7734. // store a literal LF — both unacceptable. The wire form must round-trip.
  7735. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7736. Server svr;
  7737. std::string referer;
  7738. svr.Get("/check", [&](const Request &req, Response &res) {
  7739. referer = req.get_header_value("Referer");
  7740. res.set_content("ok", "text/plain");
  7741. });
  7742. thread t = thread([&] { svr.listen(HOST, PORT); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. t.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. const std::string req = "GET /check HTTP/1.1\r\n"
  7750. "Host: localhost\r\n"
  7751. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7752. "Connection: close\r\n"
  7753. "\r\n";
  7754. std::string res;
  7755. ASSERT_TRUE(send_request(5, req, &res));
  7756. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7757. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7758. }
  7759. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7760. Server svr;
  7761. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7762. res.set_header("Cache-Control", "no-cache");
  7763. res.set_chunked_content_provider(
  7764. "text/event-stream", [](size_t offset, DataSink &sink) {
  7765. std::string s = "data:";
  7766. s += std::to_string(offset);
  7767. s += "\n\n";
  7768. auto ret = sink.write(s.data(), s.size());
  7769. EXPECT_TRUE(ret);
  7770. std::this_thread::sleep_for(std::chrono::seconds(1));
  7771. return true;
  7772. });
  7773. });
  7774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7775. svr.wait_until_ready();
  7776. Client client(HOST, PORT);
  7777. const Headers headers = {{"Accept", "text/event-stream"}};
  7778. auto get_thread = std::thread([&client, &headers]() {
  7779. auto res = client.Get(
  7780. "/events", headers,
  7781. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7782. });
  7783. auto se = detail::scope_exit([&] {
  7784. svr.stop();
  7785. get_thread.join();
  7786. listen_thread.join();
  7787. ASSERT_FALSE(svr.is_running());
  7788. });
  7789. // Give GET time to get a few messages.
  7790. std::this_thread::sleep_for(std::chrono::seconds(2));
  7791. }
  7792. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7793. httplib::Server svr;
  7794. svr.Post("/hi",
  7795. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7796. res.status = StatusCode::OK_200;
  7797. });
  7798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7799. svr.wait_until_ready();
  7800. Client cli(HOST, PORT);
  7801. auto res = cli.Post("/hi", "data", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. svr.stop();
  7805. thread.join();
  7806. ASSERT_FALSE(svr.is_running());
  7807. res = cli.Post("/hi", "data", "text/plain");
  7808. ASSERT_FALSE(res);
  7809. }
  7810. TEST(ServerStopTest, ListenFailure) {
  7811. Server svr;
  7812. auto t = thread([&]() {
  7813. auto ret = svr.listen("????", PORT);
  7814. EXPECT_FALSE(ret);
  7815. });
  7816. svr.wait_until_ready();
  7817. svr.stop();
  7818. t.join();
  7819. }
  7820. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7821. TEST(ServerStopTest, Decommision) {
  7822. Server svr;
  7823. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7824. for (int i = 0; i < 4; i++) {
  7825. auto is_even = !(i % 2);
  7826. std::thread t{[&] {
  7827. try {
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7829. if (is_even) {
  7830. throw std::runtime_error("Some thing that happens to go wrong.");
  7831. }
  7832. svr.listen(HOST, PORT);
  7833. } catch (...) { svr.decommission(); }
  7834. }};
  7835. svr.wait_until_ready();
  7836. // Server is up
  7837. {
  7838. Client cli(HOST, PORT);
  7839. auto res = cli.Get("/hi");
  7840. if (is_even) {
  7841. EXPECT_FALSE(res);
  7842. } else {
  7843. EXPECT_TRUE(res);
  7844. EXPECT_EQ("hi...", res->body);
  7845. }
  7846. }
  7847. svr.stop();
  7848. t.join();
  7849. // Server is down...
  7850. {
  7851. Client cli(HOST, PORT);
  7852. auto res = cli.Get("/hi");
  7853. EXPECT_FALSE(res);
  7854. }
  7855. }
  7856. }
  7857. #endif
  7858. // Helper function for string body upload progress tests
  7859. template <typename SetupHandler, typename ClientCall>
  7860. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7861. ClientCall &&client_call,
  7862. const string &body) {
  7863. Server svr;
  7864. setup_handler(svr);
  7865. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7866. auto se = detail::scope_exit([&] {
  7867. svr.stop();
  7868. t.join();
  7869. });
  7870. svr.wait_until_ready();
  7871. Client cli(HOST, PORT);
  7872. vector<uint64_t> progress_values;
  7873. bool progress_called = false;
  7874. auto res =
  7875. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7876. progress_values.push_back(current);
  7877. progress_called = true;
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(200, res->status);
  7882. EXPECT_TRUE(progress_called);
  7883. }
  7884. TEST(UploadProgressTest, PostStringBodyBasic) {
  7885. TestStringBodyUploadProgress(
  7886. [](Server &svr) {
  7887. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7888. res.set_content("received", "text/plain");
  7889. });
  7890. },
  7891. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7892. return cli.Post("/test", body, "text/plain", progress_callback);
  7893. },
  7894. "test data for upload progress");
  7895. }
  7896. TEST(UploadProgressTest, PutStringBodyBasic) {
  7897. TestStringBodyUploadProgress(
  7898. [](Server &svr) {
  7899. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7900. res.set_content("put received", "text/plain");
  7901. });
  7902. },
  7903. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7904. return cli.Put("/test", body, "text/plain", progress_callback);
  7905. },
  7906. "put test data for upload progress");
  7907. }
  7908. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7909. TestStringBodyUploadProgress(
  7910. [](Server &svr) {
  7911. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7912. res.set_content("patch received", "text/plain");
  7913. });
  7914. },
  7915. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7916. return cli.Patch("/test", body, "text/plain", progress_callback);
  7917. },
  7918. "patch test data for upload progress");
  7919. }
  7920. // Helper function for content provider upload progress tests
  7921. template <typename SetupHandler, typename ClientCall>
  7922. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7923. ClientCall &&client_call) {
  7924. Server svr;
  7925. setup_handler(svr);
  7926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. t.join();
  7930. });
  7931. svr.wait_until_ready();
  7932. Client cli(HOST, PORT);
  7933. vector<uint64_t> progress_values;
  7934. auto res =
  7935. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7936. progress_values.push_back(current);
  7937. return true;
  7938. });
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(200, res->status);
  7941. EXPECT_FALSE(progress_values.empty());
  7942. }
  7943. TEST(UploadProgressTest, PostContentProviderProgress) {
  7944. TestContentProviderUploadProgress(
  7945. [](Server &svr) {
  7946. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7947. res.set_content("provider received", "text/plain");
  7948. });
  7949. },
  7950. [](Client &cli, UploadProgress progress_callback) {
  7951. return cli.Post(
  7952. "/test", 10,
  7953. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7954. sink.os << "test data";
  7955. return true;
  7956. },
  7957. "text/plain", progress_callback);
  7958. });
  7959. }
  7960. // Helper function for multipart upload progress tests
  7961. template <typename SetupHandler, typename ClientCall>
  7962. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7963. ClientCall &&client_call,
  7964. const string &endpoint) {
  7965. Server svr;
  7966. setup_handler(svr);
  7967. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. t.join();
  7971. });
  7972. svr.wait_until_ready();
  7973. Client cli(HOST, PORT);
  7974. vector<uint64_t> progress_values;
  7975. UploadFormDataItems items = {
  7976. {"field1", "value1", "", ""},
  7977. {"field2", "longer value for progress tracking test", "", ""},
  7978. {"file1", "file content data for upload progress", "test.txt",
  7979. "text/plain"}};
  7980. auto res = client_call(cli, endpoint, items,
  7981. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7982. progress_values.push_back(current);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(200, res->status);
  7987. EXPECT_FALSE(progress_values.empty());
  7988. }
  7989. TEST(UploadProgressTest, PostMultipartProgress) {
  7990. TestMultipartUploadProgress(
  7991. [](Server &svr) {
  7992. svr.Post("/multipart", [](const Request &req, Response &res) {
  7993. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7994. res.set_content("multipart received", "text/plain");
  7995. });
  7996. },
  7997. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7998. UploadProgress progress_callback) {
  7999. return cli.Post(endpoint, items, progress_callback);
  8000. },
  8001. "/multipart");
  8002. }
  8003. // Helper function for basic download progress tests
  8004. template <typename SetupHandler, typename ClientCall>
  8005. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8006. ClientCall &&client_call, const string &endpoint,
  8007. size_t expected_content_size) {
  8008. Server svr;
  8009. setup_handler(svr);
  8010. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8011. auto se = detail::scope_exit([&] {
  8012. svr.stop();
  8013. t.join();
  8014. });
  8015. svr.wait_until_ready();
  8016. Client cli(HOST, PORT);
  8017. vector<uint64_t> progress_values;
  8018. auto res = client_call(cli, endpoint,
  8019. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8020. progress_values.push_back(current);
  8021. return true;
  8022. });
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(200, res->status);
  8025. EXPECT_FALSE(progress_values.empty());
  8026. EXPECT_EQ(expected_content_size, res->body.size());
  8027. }
  8028. TEST(DownloadProgressTest, GetBasic) {
  8029. TestBasicDownloadProgress(
  8030. [](Server &svr) {
  8031. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8032. string content(1000, 'D');
  8033. res.set_content(content, "text/plain");
  8034. });
  8035. },
  8036. [](Client &cli, const string &endpoint,
  8037. DownloadProgress progress_callback) {
  8038. return cli.Get(endpoint, progress_callback);
  8039. },
  8040. "/download", 1000u);
  8041. }
  8042. // Helper function for content receiver download progress tests
  8043. template <typename SetupHandler, typename ClientCall>
  8044. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8045. ClientCall &&client_call,
  8046. const string &endpoint,
  8047. size_t expected_content_size) {
  8048. Server svr;
  8049. setup_handler(svr);
  8050. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8051. auto se = detail::scope_exit([&] {
  8052. svr.stop();
  8053. t.join();
  8054. });
  8055. svr.wait_until_ready();
  8056. Client cli(HOST, PORT);
  8057. vector<uint64_t> progress_values;
  8058. string received_body;
  8059. auto res = client_call(
  8060. cli, endpoint,
  8061. [&](const char *data, size_t data_length) -> bool {
  8062. received_body.append(data, data_length);
  8063. return true;
  8064. },
  8065. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8066. progress_values.push_back(current);
  8067. return true;
  8068. });
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ(200, res->status);
  8071. EXPECT_FALSE(progress_values.empty());
  8072. EXPECT_EQ(expected_content_size, received_body.size());
  8073. EXPECT_TRUE(res->body.empty());
  8074. }
  8075. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8076. TestContentReceiverDownloadProgress(
  8077. [](Server &svr) {
  8078. svr.Get("/download-receiver",
  8079. [](const Request & /*req*/, Response &res) {
  8080. string content(2000, 'R');
  8081. res.set_content(content, "text/plain");
  8082. });
  8083. },
  8084. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8085. DownloadProgress progress_callback) {
  8086. return cli.Get(endpoint, content_receiver, progress_callback);
  8087. },
  8088. "/download-receiver", 2000u);
  8089. }
  8090. TEST(StreamingTest, NoContentLengthStreaming) {
  8091. Server svr;
  8092. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8093. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8094. if (offset < 6) {
  8095. sink.os << (offset < 3 ? "a" : "b");
  8096. } else {
  8097. sink.done();
  8098. }
  8099. return true;
  8100. });
  8101. });
  8102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8103. auto listen_se = detail::scope_exit([&] {
  8104. svr.stop();
  8105. listen_thread.join();
  8106. ASSERT_FALSE(svr.is_running());
  8107. });
  8108. svr.wait_until_ready();
  8109. Client client(HOST, PORT);
  8110. auto get_thread = std::thread([&client]() {
  8111. std::string s;
  8112. auto res =
  8113. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8114. s += std::string(data, len);
  8115. return true;
  8116. });
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ(StatusCode::OK_200, res->status);
  8119. EXPECT_EQ("aaabbb", s);
  8120. });
  8121. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8122. // Give GET time to get a few messages.
  8123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8124. }
  8125. TEST(MountTest, Unmount) {
  8126. Server svr;
  8127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8128. auto se = detail::scope_exit([&] {
  8129. svr.stop();
  8130. listen_thread.join();
  8131. ASSERT_FALSE(svr.is_running());
  8132. });
  8133. svr.wait_until_ready();
  8134. Client cli("localhost", PORT);
  8135. svr.set_mount_point("/mount2", "./www2");
  8136. auto res = cli.Get("/");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8139. res = cli.Get("/mount2/dir/test.html");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. svr.set_mount_point("/", "./www");
  8143. res = cli.Get("/dir/");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. svr.remove_mount_point("/");
  8147. res = cli.Get("/dir/");
  8148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8150. svr.remove_mount_point("/mount2");
  8151. res = cli.Get("/mount2/dir/test.html");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. }
  8155. TEST(MountTest, PathSegmentBoundary) {
  8156. Server svr;
  8157. svr.set_mount_point("/mount2", "./www2");
  8158. svr.set_mount_point("/", "./www");
  8159. auto port = svr.bind_to_any_port(HOST);
  8160. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8161. auto se = detail::scope_exit([&] {
  8162. svr.stop();
  8163. listen_thread.join();
  8164. ASSERT_FALSE(svr.is_running());
  8165. });
  8166. svr.wait_until_ready();
  8167. Client cli(HOST, port);
  8168. auto res = cli.Get("/mount2/dir/test.html");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. // "/mount2" must not match part-way through a path segment.
  8172. res = cli.Get("/mount2dir/test.html");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8175. // A mount point ending in '/' keeps matching every path below it.
  8176. res = cli.Get("/dir/test.html");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST(MountTest, Redicect) {
  8181. Server svr;
  8182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8183. auto se = detail::scope_exit([&] {
  8184. svr.stop();
  8185. listen_thread.join();
  8186. ASSERT_FALSE(svr.is_running());
  8187. });
  8188. svr.set_mount_point("/", "./www");
  8189. svr.wait_until_ready();
  8190. Client cli("localhost", PORT);
  8191. auto res = cli.Get("/dir/");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. res = cli.Get("/dir");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8197. res = cli.Get("/file");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. res = cli.Get("/file/");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8203. cli.set_follow_location(true);
  8204. res = cli.Get("/dir");
  8205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8206. EXPECT_EQ(StatusCode::OK_200, res->status);
  8207. }
  8208. TEST(MountTest, MultibytesPathName) {
  8209. Server svr;
  8210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8211. auto se = detail::scope_exit([&] {
  8212. svr.stop();
  8213. listen_thread.join();
  8214. ASSERT_FALSE(svr.is_running());
  8215. });
  8216. svr.set_mount_point("/", "./www");
  8217. svr.wait_until_ready();
  8218. Client cli("localhost", PORT);
  8219. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8223. }
  8224. #ifdef _WIN32
  8225. // Issue #2435: mmap::open() must succeed even when another handle holds
  8226. // the file open for writing (e.g. an active log file).
  8227. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8228. const char *path = "mmap_concurrent_writer_test.txt";
  8229. const char *content = "hello";
  8230. {
  8231. std::ofstream f(path, std::ios::binary);
  8232. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8233. }
  8234. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8235. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8236. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8237. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8238. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8239. detail::mmap m(path);
  8240. ASSERT_TRUE(m.is_open());
  8241. EXPECT_EQ(strlen(content), m.size());
  8242. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8243. }
  8244. #endif
  8245. #ifndef _WIN32
  8246. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8247. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8248. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8249. TEST(MmapTest, FailedMappingIsNotOpen) {
  8250. const char *path = "./mmap_failed_mapping_test_dir";
  8251. ASSERT_EQ(0, ::mkdir(path, 0755));
  8252. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8253. detail::mmap m(path);
  8254. EXPECT_FALSE(m.is_open());
  8255. EXPECT_EQ(0U, m.size());
  8256. EXPECT_NE(static_cast<const void *>(m.data()),
  8257. static_cast<const void *>(MAP_FAILED));
  8258. }
  8259. #endif
  8260. TEST(KeepAliveTest, ReadTimeout) {
  8261. Server svr;
  8262. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8263. std::this_thread::sleep_for(std::chrono::seconds(2));
  8264. res.set_content("a", "text/plain");
  8265. });
  8266. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8267. res.set_content("b", "text/plain");
  8268. });
  8269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8270. auto se = detail::scope_exit([&] {
  8271. svr.stop();
  8272. listen_thread.join();
  8273. ASSERT_FALSE(svr.is_running());
  8274. });
  8275. svr.wait_until_ready();
  8276. Client cli("localhost", PORT);
  8277. cli.set_keep_alive(true);
  8278. cli.set_read_timeout(std::chrono::seconds(1));
  8279. auto resa = cli.Get("/a");
  8280. ASSERT_FALSE(resa);
  8281. EXPECT_EQ(Error::Read, resa.error());
  8282. auto resb = cli.Get("/b");
  8283. ASSERT_TRUE(resb);
  8284. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8285. EXPECT_EQ("b", resb->body);
  8286. }
  8287. TEST(KeepAliveTest, MaxCount) {
  8288. size_t keep_alive_max_count = 3;
  8289. Server svr;
  8290. svr.set_keep_alive_max_count(keep_alive_max_count);
  8291. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8292. res.set_content("Hello World!", "text/plain");
  8293. });
  8294. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. listen_thread.join();
  8298. ASSERT_FALSE(svr.is_running());
  8299. });
  8300. svr.wait_until_ready();
  8301. Client cli(HOST, PORT);
  8302. cli.set_keep_alive(true);
  8303. for (size_t i = 0; i < 5; i++) {
  8304. auto result = cli.Get("/hi");
  8305. ASSERT_TRUE(result);
  8306. EXPECT_EQ(StatusCode::OK_200, result->status);
  8307. if (i == keep_alive_max_count - 1) {
  8308. EXPECT_EQ("close", result->get_header_value("Connection"));
  8309. } else {
  8310. EXPECT_FALSE(result->has_header("Connection"));
  8311. }
  8312. }
  8313. }
  8314. TEST(KeepAliveTest, Issue1041) {
  8315. Server svr;
  8316. svr.set_keep_alive_timeout(3);
  8317. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8318. res.set_content("Hello World!", "text/plain");
  8319. });
  8320. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8321. auto se = detail::scope_exit([&] {
  8322. svr.stop();
  8323. listen_thread.join();
  8324. ASSERT_FALSE(svr.is_running());
  8325. });
  8326. svr.wait_until_ready();
  8327. Client cli(HOST, PORT);
  8328. cli.set_keep_alive(true);
  8329. auto result = cli.Get("/hi");
  8330. ASSERT_TRUE(result);
  8331. EXPECT_EQ(StatusCode::OK_200, result->status);
  8332. std::this_thread::sleep_for(std::chrono::seconds(5));
  8333. result = cli.Get("/hi");
  8334. ASSERT_TRUE(result);
  8335. EXPECT_EQ(StatusCode::OK_200, result->status);
  8336. }
  8337. TEST(KeepAliveTest, Issue1959) {
  8338. Server svr;
  8339. svr.set_keep_alive_timeout(5);
  8340. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8341. res.set_content("a", "text/plain");
  8342. });
  8343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8344. auto se = detail::scope_exit([&] {
  8345. if (!svr.is_running()) return;
  8346. svr.stop();
  8347. listen_thread.join();
  8348. ASSERT_FALSE(svr.is_running());
  8349. });
  8350. svr.wait_until_ready();
  8351. Client cli("localhost", PORT);
  8352. cli.set_keep_alive(true);
  8353. using namespace std::chrono;
  8354. auto start = steady_clock::now();
  8355. cli.Get("/a");
  8356. svr.stop();
  8357. listen_thread.join();
  8358. auto end = steady_clock::now();
  8359. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8360. EXPECT_LT(elapsed, 5000);
  8361. }
  8362. #ifdef CPPHTTPLIB_SSL_ENABLED
  8363. TEST(KeepAliveTest, SSLClientReconnection) {
  8364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8365. ASSERT_TRUE(svr.is_valid());
  8366. svr.set_keep_alive_timeout(1);
  8367. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8368. res.set_content("Hello World!", "text/plain");
  8369. });
  8370. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8371. auto se = detail::scope_exit([&] {
  8372. svr.stop();
  8373. listen_thread.join();
  8374. ASSERT_FALSE(svr.is_running());
  8375. });
  8376. svr.wait_until_ready();
  8377. SSLClient cli(HOST, PORT);
  8378. cli.enable_server_certificate_verification(false);
  8379. cli.set_keep_alive(true);
  8380. auto result = cli.Get("/hi");
  8381. ASSERT_TRUE(result);
  8382. EXPECT_EQ(StatusCode::OK_200, result->status);
  8383. result = cli.Get("/hi");
  8384. ASSERT_TRUE(result);
  8385. EXPECT_EQ(StatusCode::OK_200, result->status);
  8386. std::this_thread::sleep_for(std::chrono::seconds(2));
  8387. // Recoonect
  8388. result = cli.Get("/hi");
  8389. ASSERT_TRUE(result);
  8390. EXPECT_EQ(StatusCode::OK_200, result->status);
  8391. result = cli.Get("/hi");
  8392. ASSERT_TRUE(result);
  8393. EXPECT_EQ(StatusCode::OK_200, result->status);
  8394. }
  8395. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8397. ASSERT_TRUE(svr.is_valid());
  8398. svr.set_keep_alive_timeout(1);
  8399. std::string content = "reconnect";
  8400. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8401. res.set_content("Hello World!", "text/plain");
  8402. });
  8403. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8404. auto se = detail::scope_exit([&] {
  8405. svr.stop();
  8406. listen_thread.join();
  8407. ASSERT_FALSE(svr.is_running());
  8408. });
  8409. svr.wait_until_ready();
  8410. SSLClient cli(HOST, PORT);
  8411. cli.enable_server_certificate_verification(false);
  8412. cli.set_keep_alive(true);
  8413. auto result = cli.Post(
  8414. "/hi", content.size(),
  8415. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8416. sink.write(content.c_str(), content.size());
  8417. return true;
  8418. },
  8419. "text/plain");
  8420. ASSERT_TRUE(result);
  8421. EXPECT_EQ(200, result->status);
  8422. std::this_thread::sleep_for(std::chrono::seconds(2));
  8423. // Recoonect
  8424. result = cli.Post(
  8425. "/hi", content.size(),
  8426. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8427. sink.write(content.c_str(), content.size());
  8428. return true;
  8429. },
  8430. "text/plain");
  8431. ASSERT_TRUE(result);
  8432. EXPECT_EQ(200, result->status);
  8433. result = cli.Post(
  8434. "/hi", content.size(),
  8435. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8436. sink.write(content.c_str(), content.size());
  8437. return true;
  8438. },
  8439. "text/plain");
  8440. ASSERT_TRUE(result);
  8441. EXPECT_EQ(200, result->status);
  8442. }
  8443. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8444. using namespace httplib::tls;
  8445. {
  8446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8447. ASSERT_TRUE(svr.is_valid());
  8448. svr.Get("/sni", [&](const Request &req, Response &res) {
  8449. std::string expected = req.sni();
  8450. EXPECT_EQ(expected, req.get_param_value("expected"));
  8451. res.set_content("ok", "text/plain");
  8452. });
  8453. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8454. auto se = detail::scope_exit([&] {
  8455. svr.stop();
  8456. listen_thread.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. svr.wait_until_ready();
  8460. {
  8461. SSLClient cli("localhost", PORT);
  8462. cli.enable_server_certificate_verification(false);
  8463. auto res = cli.Get("/sni?expected=localhost");
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. }
  8466. {
  8467. SSLClient cli("::1", PORT);
  8468. cli.enable_server_certificate_verification(false);
  8469. auto res = cli.Get("/sni?expected=");
  8470. // NOTE: This may fail if the server is listening on IPv4 only
  8471. // (e.g., when localhost resolves to 127.0.0.1 only)
  8472. if (res) {
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. } else {
  8475. EXPECT_EQ(Error::Connection, res.error());
  8476. }
  8477. }
  8478. }
  8479. }
  8480. #endif
  8481. TEST(ClientProblemDetectionTest, ContentProvider) {
  8482. Server svr;
  8483. size_t content_length = 1024 * 1024;
  8484. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8485. res.set_content_provider(
  8486. content_length, "text/plain",
  8487. [&](size_t offset, size_t length, DataSink &sink) {
  8488. auto out_len = std::min(length, static_cast<size_t>(1024));
  8489. std::string out(out_len, '@');
  8490. sink.write(out.data(), out_len);
  8491. return offset < 4096;
  8492. },
  8493. [](bool success) { ASSERT_FALSE(success); });
  8494. });
  8495. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8496. res.set_content_provider(
  8497. 0, "text/plain",
  8498. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8499. EXPECT_TRUE(false);
  8500. return true;
  8501. },
  8502. [](bool success) { ASSERT_FALSE(success); });
  8503. });
  8504. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. listen_thread.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. });
  8510. svr.wait_until_ready();
  8511. Client cli("localhost", PORT);
  8512. {
  8513. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8514. size_t /*data_length*/) { return false; });
  8515. ASSERT_FALSE(res);
  8516. }
  8517. {
  8518. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8519. size_t /*data_length*/) { return false; });
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. }
  8522. }
  8523. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8524. Server svr;
  8525. svr.set_error_handler([](Request const &, Response &res) -> void {
  8526. res.set_chunked_content_provider(
  8527. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8528. sink.os << "hello";
  8529. sink.os << "world";
  8530. sink.done();
  8531. return true;
  8532. });
  8533. });
  8534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8535. auto se = detail::scope_exit([&] {
  8536. svr.stop();
  8537. listen_thread.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. Client cli("localhost", PORT);
  8542. auto res = cli.Get("/");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8545. EXPECT_EQ("helloworld", res->body);
  8546. }
  8547. TEST(LongPollingTest, ClientCloseDetection) {
  8548. Server svr;
  8549. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8550. res.set_chunked_content_provider(
  8551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8552. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8553. sink.os << "hello";
  8554. auto count = 10;
  8555. while (count > 0 && sink.is_writable()) {
  8556. this_thread::sleep_for(chrono::milliseconds(10));
  8557. count--;
  8558. }
  8559. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8560. return true;
  8561. });
  8562. });
  8563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8564. auto se = detail::scope_exit([&] {
  8565. svr.stop();
  8566. listen_thread.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. Client cli("localhost", PORT);
  8571. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8572. EXPECT_EQ("hello", string(data, data_length));
  8573. return false; // close the socket immediately.
  8574. });
  8575. ASSERT_FALSE(res);
  8576. }
  8577. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8578. Server svr;
  8579. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8580. res.set_chunked_content_provider(
  8581. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8582. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8583. sink.os << "hello";
  8584. EXPECT_TRUE(sink.os.good());
  8585. // Wait for the client to close the connection
  8586. auto count = 10;
  8587. while (count > 0 && sink.is_writable()) {
  8588. this_thread::sleep_for(chrono::milliseconds(10));
  8589. count--;
  8590. }
  8591. // After client disconnect, write repeatedly until the socket
  8592. // write actually fails (small writes may be absorbed by the
  8593. // kernel buffer)
  8594. std::string chunk(1024, 'x');
  8595. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8596. sink.os << chunk;
  8597. }
  8598. EXPECT_TRUE(sink.os.fail());
  8599. return true;
  8600. });
  8601. });
  8602. auto port = svr.bind_to_any_port("localhost");
  8603. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. listen_thread.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. Client cli("localhost", port);
  8611. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8612. EXPECT_EQ("hello", string(data, data_length));
  8613. return false; // close the socket immediately.
  8614. });
  8615. ASSERT_FALSE(res);
  8616. }
  8617. TEST(GetWithParametersTest, GetWithParameters) {
  8618. Server svr;
  8619. svr.Get("/", [&](const Request &req, Response &) {
  8620. EXPECT_EQ("world", req.get_param_value("hello"));
  8621. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8622. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8623. });
  8624. svr.Get("/params", [&](const Request &req, Response &) {
  8625. EXPECT_EQ("world", req.get_param_value("hello"));
  8626. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8627. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8628. });
  8629. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8630. EXPECT_EQ("resource-id", req.matches[1]);
  8631. EXPECT_EQ("foo", req.get_param_value("param1"));
  8632. EXPECT_EQ("bar", req.get_param_value("param2"));
  8633. });
  8634. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("user-id", req.path_params.at("id"));
  8636. EXPECT_EQ("foo", req.get_param_value("param1"));
  8637. EXPECT_EQ("bar", req.get_param_value("param2"));
  8638. });
  8639. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. listen_thread.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. });
  8645. svr.wait_until_ready();
  8646. {
  8647. Client cli(HOST, PORT);
  8648. Params params;
  8649. params.emplace("hello", "world");
  8650. params.emplace("hello2", "world2");
  8651. params.emplace("hello3", "world3");
  8652. auto res = cli.Get("/", params, Headers{});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. }
  8656. {
  8657. Client cli(HOST, PORT);
  8658. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. {
  8663. Client cli(HOST, PORT);
  8664. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. }
  8668. {
  8669. Client cli(HOST, PORT);
  8670. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(StatusCode::OK_200, res->status);
  8673. }
  8674. }
  8675. TEST(GetWithParametersTest, GetWithParameters2) {
  8676. Server svr;
  8677. svr.Get("/", [&](const Request &req, Response &res) {
  8678. auto text = req.get_param_value("hello");
  8679. res.set_content(text, "text/plain");
  8680. });
  8681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8682. auto se = detail::scope_exit([&] {
  8683. svr.stop();
  8684. listen_thread.join();
  8685. ASSERT_FALSE(svr.is_running());
  8686. });
  8687. svr.wait_until_ready();
  8688. Client cli("localhost", PORT);
  8689. Params params;
  8690. params.emplace("hello", "world");
  8691. std::string body;
  8692. auto res = cli.Get("/", params, Headers{},
  8693. [&](const char *data, size_t data_length) {
  8694. body.append(data, data_length);
  8695. return true;
  8696. });
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ(StatusCode::OK_200, res->status);
  8699. EXPECT_EQ("world", body);
  8700. }
  8701. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8702. Server svr;
  8703. svr.Get("/search", [&](const Request &req, Response &res) {
  8704. auto q = req.get_param_value("q");
  8705. res.set_content(q, "text/plain");
  8706. });
  8707. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8708. auto se = detail::scope_exit([&] {
  8709. svr.stop();
  8710. listen_thread.join();
  8711. ASSERT_FALSE(svr.is_running());
  8712. });
  8713. svr.wait_until_ready();
  8714. Client cli("localhost", PORT);
  8715. // Verify that Get(path, params) works without requiring Headers argument
  8716. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::OK_200, res->status);
  8719. EXPECT_EQ("cpp-httplib", res->body);
  8720. }
  8721. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8722. auto host = "httpbingo.org";
  8723. auto path = std::string{"/range/32"};
  8724. #ifdef CPPHTTPLIB_SSL_ENABLED
  8725. SSLClient cli(host);
  8726. #else
  8727. Client cli(host);
  8728. #endif
  8729. cli.set_default_headers({make_range_header({{1, 10}})});
  8730. cli.set_connection_timeout(5);
  8731. {
  8732. auto res = cli.Get(path);
  8733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8734. EXPECT_EQ("bcdefghijk", res->body);
  8735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8736. }
  8737. {
  8738. auto res = cli.Get(path);
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ("bcdefghijk", res->body);
  8741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8742. }
  8743. }
  8744. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8745. Server svr;
  8746. svr.set_default_headers({{"Hello", "World"}});
  8747. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. listen_thread.join();
  8754. ASSERT_FALSE(svr.is_running());
  8755. });
  8756. svr.wait_until_ready();
  8757. Client cli("localhost", PORT);
  8758. auto res = cli.Get("/");
  8759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8760. EXPECT_EQ(StatusCode::OK_200, res->status);
  8761. EXPECT_EQ("ok", res->body);
  8762. EXPECT_EQ("World", res->get_header_value("Hello"));
  8763. }
  8764. #ifdef CPPHTTPLIB_SSL_ENABLED
  8765. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8767. ASSERT_TRUE(svr.is_valid());
  8768. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8769. std::this_thread::sleep_for(std::chrono::seconds(2));
  8770. res.set_content("a", "text/plain");
  8771. });
  8772. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8773. res.set_content("b", "text/plain");
  8774. });
  8775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8776. auto se = detail::scope_exit([&] {
  8777. svr.stop();
  8778. listen_thread.join();
  8779. ASSERT_FALSE(svr.is_running());
  8780. });
  8781. svr.wait_until_ready();
  8782. SSLClient cli("localhost", PORT);
  8783. cli.enable_server_certificate_verification(false);
  8784. cli.set_keep_alive(true);
  8785. cli.set_read_timeout(std::chrono::seconds(1));
  8786. auto resa = cli.Get("/a");
  8787. ASSERT_TRUE(!resa);
  8788. EXPECT_EQ(Error::Read, resa.error());
  8789. auto resb = cli.Get("/b");
  8790. ASSERT_TRUE(resb);
  8791. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8792. EXPECT_EQ("b", resb->body);
  8793. }
  8794. #endif
  8795. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8796. protected:
  8797. ServerTestWithAI_PASSIVE()
  8798. : cli_(HOST, PORT)
  8799. #ifdef CPPHTTPLIB_SSL_ENABLED
  8800. ,
  8801. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8802. #endif
  8803. {
  8804. #ifdef CPPHTTPLIB_SSL_ENABLED
  8805. cli_.enable_server_certificate_verification(false);
  8806. #endif
  8807. }
  8808. virtual void SetUp() {
  8809. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8810. res.set_content("Hello World!", "text/plain");
  8811. });
  8812. t_ = thread(
  8813. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8814. svr_.wait_until_ready();
  8815. }
  8816. virtual void TearDown() {
  8817. svr_.stop();
  8818. t_.join();
  8819. }
  8820. #ifdef CPPHTTPLIB_SSL_ENABLED
  8821. SSLClient cli_;
  8822. SSLServer svr_;
  8823. #else
  8824. Client cli_;
  8825. Server svr_;
  8826. #endif
  8827. thread t_;
  8828. };
  8829. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8830. auto res = cli_.Get("/hi");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8834. EXPECT_EQ("Hello World!", res->body);
  8835. }
  8836. class ServerUpDownTest : public ::testing::Test {
  8837. protected:
  8838. ServerUpDownTest() : cli_(HOST, PORT) {}
  8839. virtual void SetUp() {
  8840. t_ = thread([&]() {
  8841. svr_.bind_to_any_port(HOST);
  8842. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8843. ASSERT_TRUE(svr_.listen_after_bind());
  8844. });
  8845. svr_.wait_until_ready();
  8846. }
  8847. virtual void TearDown() {
  8848. svr_.stop();
  8849. t_.join();
  8850. }
  8851. Client cli_;
  8852. Server svr_;
  8853. thread t_;
  8854. };
  8855. TEST_F(ServerUpDownTest, QuickStartStop) {
  8856. // Should not crash, especially when run with
  8857. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8858. }
  8859. class PayloadMaxLengthTest : public ::testing::Test {
  8860. protected:
  8861. PayloadMaxLengthTest()
  8862. : cli_(HOST, PORT)
  8863. #ifdef CPPHTTPLIB_SSL_ENABLED
  8864. ,
  8865. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8866. #endif
  8867. {
  8868. #ifdef CPPHTTPLIB_SSL_ENABLED
  8869. cli_.enable_server_certificate_verification(false);
  8870. #endif
  8871. }
  8872. virtual void SetUp() {
  8873. svr_.set_payload_max_length(8);
  8874. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8875. res.set_content("test", "text/plain");
  8876. });
  8877. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8878. svr_.wait_until_ready();
  8879. }
  8880. virtual void TearDown() {
  8881. svr_.stop();
  8882. t_.join();
  8883. }
  8884. #ifdef CPPHTTPLIB_SSL_ENABLED
  8885. SSLClient cli_;
  8886. SSLServer svr_;
  8887. #else
  8888. Client cli_;
  8889. Server svr_;
  8890. #endif
  8891. thread t_;
  8892. };
  8893. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8894. auto res = cli_.Post("/test", "123456789", "text/plain");
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8897. res = cli_.Post("/test", "12345678", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8902. // Test chunked encoding with payload exceeding the 8-byte limit
  8903. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8904. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8907. }
  8908. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8909. // Test chunked encoding with payload within the 8-byte limit
  8910. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8911. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. }
  8915. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8916. // Test using send_request to send chunked data exceeding payload limit
  8917. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8918. "Host: " +
  8919. std::string(HOST) + ":" + std::to_string(PORT) +
  8920. "\r\n"
  8921. "Transfer-Encoding: chunked\r\n"
  8922. "Connection: close\r\n"
  8923. "\r\n"
  8924. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8925. "0123456789\r\n"
  8926. "0\r\n" // End chunk
  8927. "\r\n";
  8928. std::string response;
  8929. bool result = send_request(1, chunked_request, &response);
  8930. if (!result) {
  8931. // If send_request fails, it might be because the server closed the
  8932. // connection due to payload limit enforcement, which is acceptable
  8933. SUCCEED()
  8934. << "Server rejected oversized chunked request (connection closed)";
  8935. } else {
  8936. // If we got a response, check if it's an error response or connection was
  8937. // closed early Short response length indicates connection was closed due to
  8938. // payload limit
  8939. if (response.length() <= 10) {
  8940. SUCCEED() << "Server closed connection for oversized chunked request";
  8941. } else {
  8942. // Check for error status codes
  8943. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8944. response.find("Payload Too Large") != std::string::npos ||
  8945. response.find("400") != std::string::npos);
  8946. }
  8947. }
  8948. }
  8949. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8950. // Test request without Content-Length header exceeding payload limit
  8951. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8952. "Host: " +
  8953. std::string(HOST) + ":" +
  8954. std::to_string(PORT) +
  8955. "\r\n"
  8956. "Connection: close\r\n"
  8957. "\r\n";
  8958. // Add payload exceeding the 8-byte limit
  8959. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8960. request_without_content_length += large_payload;
  8961. std::string response;
  8962. bool result = send_request(1, request_without_content_length, &response);
  8963. if (!result) {
  8964. // If send_request fails, server likely closed connection due to payload
  8965. // limit
  8966. SUCCEED() << "Server rejected oversized request without Content-Length "
  8967. "(connection closed)";
  8968. } else {
  8969. // Check if server responded with error or closed connection early
  8970. if (response.length() <= 10) {
  8971. SUCCEED() << "Server closed connection for oversized request without "
  8972. "Content-Length";
  8973. } else {
  8974. // Check for error status codes
  8975. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8976. response.find("Payload Too Large") != std::string::npos ||
  8977. response.find("400") != std::string::npos);
  8978. }
  8979. }
  8980. }
  8981. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8982. // Test request without Content-Length header within payload limit
  8983. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8984. "Host: " +
  8985. std::string(HOST) + ":" +
  8986. std::to_string(PORT) +
  8987. "\r\n"
  8988. "Connection: close\r\n"
  8989. "\r\n";
  8990. // Add payload within the 8-byte limit
  8991. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8992. request_without_content_length += small_payload;
  8993. std::string response;
  8994. bool result = send_request(1, request_without_content_length, &response);
  8995. // For requests without Content-Length, the server may have different behavior
  8996. // The key is that it should not reject due to payload limit for small
  8997. // payloads
  8998. if (result) {
  8999. // Check for any HTTP response (success or error, but not connection closed)
  9000. if (response.length() > 10) {
  9001. SUCCEED()
  9002. << "Server processed request without Content-Length within limit";
  9003. } else {
  9004. // Short response might indicate connection closed, which is acceptable
  9005. SUCCEED() << "Server closed connection for request without "
  9006. "Content-Length (acceptable behavior)";
  9007. }
  9008. } else {
  9009. // Connection failure might be due to protocol requirements
  9010. SUCCEED() << "Connection issue with request without Content-Length "
  9011. "(environment-specific)";
  9012. }
  9013. }
  9014. class LargePayloadMaxLengthTest : public ::testing::Test {
  9015. protected:
  9016. LargePayloadMaxLengthTest()
  9017. : cli_(HOST, PORT)
  9018. #ifdef CPPHTTPLIB_SSL_ENABLED
  9019. ,
  9020. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9021. #endif
  9022. {
  9023. #ifdef CPPHTTPLIB_SSL_ENABLED
  9024. cli_.enable_server_certificate_verification(false);
  9025. #endif
  9026. }
  9027. virtual void SetUp() {
  9028. // Set 10MB payload limit
  9029. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9030. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9031. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9032. res.set_content("Large payload test", "text/plain");
  9033. });
  9034. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9035. svr_.wait_until_ready();
  9036. }
  9037. virtual void TearDown() {
  9038. svr_.stop();
  9039. t_.join();
  9040. }
  9041. #ifdef CPPHTTPLIB_SSL_ENABLED
  9042. SSLClient cli_;
  9043. SSLServer svr_;
  9044. #else
  9045. Client cli_;
  9046. Server svr_;
  9047. #endif
  9048. thread t_;
  9049. };
  9050. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9051. // Test chunked encoding with payload within 10MB limit
  9052. std::string medium_payload(5 * 1024 * 1024,
  9053. 'A'); // 5MB payload, within 10MB limit
  9054. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9059. // Test chunked encoding with payload exceeding 10MB limit
  9060. std::string large_payload(12 * 1024 * 1024,
  9061. 'B'); // 12MB payload, exceeds 10MB limit
  9062. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9063. // Server may either return 413 or close the connection
  9064. if (res) {
  9065. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9066. } else {
  9067. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9068. }
  9069. }
  9070. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9071. // Test request without Content-Length header within 10MB limit
  9072. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9073. "Host: " +
  9074. std::string(HOST) + ":" +
  9075. std::to_string(PORT) +
  9076. "\r\n"
  9077. "Connection: close\r\n"
  9078. "\r\n";
  9079. // Add 1MB payload (within 10MB limit)
  9080. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9081. request_without_content_length += medium_payload;
  9082. std::string response;
  9083. bool result = send_request(5, request_without_content_length, &response);
  9084. if (result) {
  9085. // Should get a proper HTTP response for payloads within limit
  9086. if (response.length() > 10) {
  9087. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9088. "10MB limit";
  9089. } else {
  9090. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9091. "Content-Length)";
  9092. }
  9093. } else {
  9094. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9095. }
  9096. }
  9097. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9098. // Test request without Content-Length header exceeding 10MB limit
  9099. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9100. "Host: " +
  9101. std::string(HOST) + ":" +
  9102. std::to_string(PORT) +
  9103. "\r\n"
  9104. "Connection: close\r\n"
  9105. "\r\n";
  9106. // Add 12MB payload (exceeds 10MB limit)
  9107. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9108. request_without_content_length += large_payload;
  9109. std::string response;
  9110. bool result = send_request(10, request_without_content_length, &response);
  9111. if (!result) {
  9112. // Server should close connection due to payload limit
  9113. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9114. "(connection closed)";
  9115. } else {
  9116. // Check for error response
  9117. if (response.length() <= 10) {
  9118. SUCCEED()
  9119. << "Server closed connection for 12MB request exceeding 10MB limit";
  9120. } else {
  9121. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9122. response.find("Payload Too Large") != std::string::npos ||
  9123. response.find("400") != std::string::npos);
  9124. }
  9125. }
  9126. }
  9127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9128. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9129. // path.
  9130. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9131. Server svr;
  9132. const size_t LIMIT = 64 * 1024; // 64KB
  9133. svr.set_payload_max_length(LIMIT);
  9134. size_t total = 0;
  9135. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9136. const ContentReader &content_reader) {
  9137. content_reader([&](const char * /*data*/, size_t len) {
  9138. total += len;
  9139. return true;
  9140. });
  9141. res.status = 200;
  9142. res.set_content("stream_ok", "text/plain");
  9143. });
  9144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9145. auto se = detail::scope_exit([&] {
  9146. svr.stop();
  9147. thread.join();
  9148. ASSERT_FALSE(svr.is_running());
  9149. });
  9150. svr.wait_until_ready();
  9151. // Prepare 256KB raw data and gzip-compress it
  9152. std::string raw(256 * 1024, 'A');
  9153. std::string gz;
  9154. {
  9155. z_stream zs{};
  9156. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9157. Z_DEFAULT_STRATEGY);
  9158. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9159. zs.avail_in = static_cast<uInt>(raw.size());
  9160. char outbuf[4096];
  9161. int ret;
  9162. do {
  9163. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9164. zs.avail_out = sizeof(outbuf);
  9165. ret = deflate(&zs, Z_FINISH);
  9166. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9167. } while (ret != Z_STREAM_END);
  9168. deflateEnd(&zs);
  9169. }
  9170. Client cli(HOST, PORT);
  9171. cli.set_connection_timeout(std::chrono::seconds(5));
  9172. Headers headers = {{"Content-Encoding", "gzip"}};
  9173. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9174. "application/octet-stream");
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. // Server must reject oversized decompressed payloads with 413.
  9177. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9178. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9179. EXPECT_LE(total, LIMIT);
  9180. }
  9181. #endif
  9182. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9183. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9184. // the payload must be passed through untouched instead of being rejected.
  9185. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9186. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9187. Server svr;
  9188. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9189. res.set_content(body, "image/jpeg");
  9190. res.set_header("Content-Encoding", "UTF-8");
  9191. });
  9192. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9193. res.set_content(body, "image/jpeg");
  9194. res.set_header("Content-Encoding", "identity");
  9195. });
  9196. svr.Post("/echo", [](const Request &req, Response &res) {
  9197. res.set_content(req.body, "image/jpeg");
  9198. });
  9199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9200. auto se = detail::scope_exit([&] {
  9201. svr.stop();
  9202. t.join();
  9203. ASSERT_FALSE(svr.is_running());
  9204. });
  9205. svr.wait_until_ready();
  9206. Client cli(HOST, PORT);
  9207. {
  9208. auto res = cli.Get("/image");
  9209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9210. EXPECT_EQ(StatusCode::OK_200, res->status);
  9211. EXPECT_EQ(body, res->body);
  9212. }
  9213. {
  9214. auto res = cli.Get("/identity");
  9215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9216. EXPECT_EQ(StatusCode::OK_200, res->status);
  9217. EXPECT_EQ(body, res->body);
  9218. }
  9219. {
  9220. // The same applies to a request body reaching the server.
  9221. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9222. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9224. EXPECT_EQ(StatusCode::OK_200, res->status);
  9225. EXPECT_EQ(body, res->body);
  9226. }
  9227. }
  9228. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9229. // gzip-encoded response even when the build has no zlib support.
  9230. static const char GZIPPED_HELLO_WORLD[] = {
  9231. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9232. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9233. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9234. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9235. // A content coding cpp-httplib recognizes but was not built with must be
  9236. // reported as such. Handing the still-compressed payload back to the caller
  9237. // would silently corrupt it.
  9238. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9239. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9240. Server svr;
  9241. // "image/jpeg" keeps the server from applying a content coding of its own,
  9242. // so the hand-crafted Content-Encoding below survives.
  9243. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9244. res.set_content(gzipped, "image/jpeg");
  9245. res.set_header("Content-Encoding", "gzip");
  9246. });
  9247. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9248. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9249. res.set_content(gzipped, "image/jpeg");
  9250. res.set_header("Content-Encoding", "GZIP");
  9251. });
  9252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9253. auto se = detail::scope_exit([&] {
  9254. svr.stop();
  9255. t.join();
  9256. ASSERT_FALSE(svr.is_running());
  9257. });
  9258. svr.wait_until_ready();
  9259. Client cli(HOST, PORT);
  9260. {
  9261. auto res = cli.Get("/gzipped");
  9262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9264. EXPECT_EQ("Hello World!", res->body);
  9265. #else
  9266. ASSERT_FALSE(res);
  9267. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9268. #endif
  9269. }
  9270. {
  9271. // open_stream() must behave the same way.
  9272. auto handle = cli.open_stream("GET", "/gzipped");
  9273. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9274. ASSERT_TRUE(handle.is_valid());
  9275. std::string received;
  9276. char buf[256];
  9277. ssize_t n;
  9278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9279. received.append(buf, static_cast<size_t>(n));
  9280. }
  9281. EXPECT_EQ("Hello World!", received);
  9282. #else
  9283. EXPECT_FALSE(handle.is_valid());
  9284. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9285. #endif
  9286. }
  9287. {
  9288. // A differently-cased coding must not be mistaken for an unknown one, or
  9289. // the body would be handed back still compressed.
  9290. auto res = cli.Get("/gzipped-uppercase");
  9291. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9293. EXPECT_EQ("Hello World!", res->body);
  9294. #else
  9295. ASSERT_FALSE(res);
  9296. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9297. #endif
  9298. }
  9299. }
  9300. // Regression test for DoS vulnerability: a malicious server sending a response
  9301. // without Content-Length header must not cause unbounded memory consumption on
  9302. // the client side. The client should stop reading after a reasonable limit,
  9303. // similar to the server-side set_payload_max_length protection.
  9304. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9305. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9306. #ifndef _WIN32
  9307. signal(SIGPIPE, SIG_IGN);
  9308. #endif
  9309. auto server_thread = std::thread([] {
  9310. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9311. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9312. default_socket_options(srv);
  9313. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9314. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9315. sockaddr_in addr{};
  9316. addr.sin_family = AF_INET;
  9317. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9318. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9319. int opt = 1;
  9320. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9321. #ifdef _WIN32
  9322. reinterpret_cast<const char *>(&opt),
  9323. #else
  9324. &opt,
  9325. #endif
  9326. sizeof(opt));
  9327. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9328. ::listen(srv, 1);
  9329. sockaddr_in cli_addr{};
  9330. socklen_t cli_len = sizeof(cli_addr);
  9331. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9332. if (cli != INVALID_SOCKET) {
  9333. char buf[4096];
  9334. ::recv(cli, buf, sizeof(buf), 0);
  9335. // Malicious response: no Content-Length, no chunked encoding
  9336. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9337. "Connection: close\r\n"
  9338. "\r\n";
  9339. ::send(cli,
  9340. #ifdef _WIN32
  9341. static_cast<const char *>(response_header.c_str()),
  9342. static_cast<int>(response_header.size()),
  9343. #else
  9344. response_header.c_str(), response_header.size(),
  9345. #endif
  9346. 0);
  9347. // Send 10MB of data
  9348. std::string chunk(64 * 1024, 'A');
  9349. size_t total_sent = 0;
  9350. while (total_sent < MALICIOUS_DATA_SIZE) {
  9351. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9352. auto sent = ::send(cli,
  9353. #ifdef _WIN32
  9354. static_cast<const char *>(chunk.c_str()),
  9355. static_cast<int>(to_send),
  9356. #else
  9357. chunk.c_str(), to_send,
  9358. #endif
  9359. 0);
  9360. if (sent <= 0) break;
  9361. total_sent += static_cast<size_t>(sent);
  9362. }
  9363. detail::close_socket(cli);
  9364. }
  9365. detail::close_socket(srv);
  9366. });
  9367. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9368. size_t total_read = 0;
  9369. {
  9370. Client cli("127.0.0.1", PORT + 2);
  9371. cli.set_read_timeout(5, 0);
  9372. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9373. auto stream = cli.open_stream("GET", "/malicious");
  9374. ASSERT_TRUE(stream.is_valid());
  9375. char buffer[64 * 1024];
  9376. ssize_t n;
  9377. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9378. total_read += static_cast<size_t>(n);
  9379. }
  9380. } // StreamHandle and Client destroyed here, closing the socket
  9381. server_thread.join();
  9382. // With set_payload_max_length, the client must stop reading before consuming
  9383. // all 10MB. The read loop should be cut off at or near the configured limit.
  9384. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9385. << "Client read " << total_read << " bytes, exceeding the configured "
  9386. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9387. }
  9388. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9389. // the entire response body without truncation.
  9390. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9391. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9392. #ifndef _WIN32
  9393. signal(SIGPIPE, SIG_IGN);
  9394. #endif
  9395. auto server_thread = std::thread([] {
  9396. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9397. default_socket_options(srv);
  9398. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9399. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9400. sockaddr_in addr{};
  9401. addr.sin_family = AF_INET;
  9402. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9403. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9404. int opt = 1;
  9405. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9406. #ifdef _WIN32
  9407. reinterpret_cast<const char *>(&opt),
  9408. #else
  9409. &opt,
  9410. #endif
  9411. sizeof(opt));
  9412. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9413. ::listen(srv, 1);
  9414. sockaddr_in cli_addr{};
  9415. socklen_t cli_len = sizeof(cli_addr);
  9416. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9417. if (cli != INVALID_SOCKET) {
  9418. char buf[4096];
  9419. ::recv(cli, buf, sizeof(buf), 0);
  9420. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9421. "Connection: close\r\n"
  9422. "\r\n";
  9423. ::send(cli,
  9424. #ifdef _WIN32
  9425. static_cast<const char *>(response_header.c_str()),
  9426. static_cast<int>(response_header.size()),
  9427. #else
  9428. response_header.c_str(), response_header.size(),
  9429. #endif
  9430. 0);
  9431. std::string chunk(64 * 1024, 'A');
  9432. size_t total_sent = 0;
  9433. while (total_sent < DATA_SIZE) {
  9434. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9435. auto sent = ::send(cli,
  9436. #ifdef _WIN32
  9437. static_cast<const char *>(chunk.c_str()),
  9438. static_cast<int>(to_send),
  9439. #else
  9440. chunk.c_str(), to_send,
  9441. #endif
  9442. 0);
  9443. if (sent <= 0) break;
  9444. total_sent += static_cast<size_t>(sent);
  9445. }
  9446. #ifdef _WIN32
  9447. ::shutdown(cli, SD_SEND);
  9448. #else
  9449. ::shutdown(cli, SHUT_WR);
  9450. #endif
  9451. // Drain until the client closes its end, ensuring all data is delivered
  9452. char drain[1024];
  9453. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9454. detail::close_socket(cli);
  9455. }
  9456. detail::close_socket(srv);
  9457. });
  9458. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9459. size_t total_read = 0;
  9460. {
  9461. Client cli("127.0.0.1", PORT + 2);
  9462. cli.set_read_timeout(5, 0);
  9463. cli.set_payload_max_length(0); // 0 means no limit
  9464. auto stream = cli.open_stream("GET", "/data");
  9465. ASSERT_TRUE(stream.is_valid());
  9466. char buffer[64 * 1024];
  9467. ssize_t n;
  9468. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9469. total_read += static_cast<size_t>(n);
  9470. }
  9471. }
  9472. server_thread.join();
  9473. EXPECT_EQ(total_read, DATA_SIZE)
  9474. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9475. << " bytes without truncation, but only read " << total_read << " bytes.";
  9476. }
  9477. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9478. // enormous Content-Length must not cause the client to pre-allocate a huge
  9479. // response body buffer. The reservation is capped at payload_max_length_, and
  9480. // the read itself fails when the body exceeds the limit.
  9481. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9482. #ifndef _WIN32
  9483. signal(SIGPIPE, SIG_IGN);
  9484. #endif
  9485. auto server_thread = std::thread([] {
  9486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9487. default_socket_options(srv);
  9488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9489. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9490. sockaddr_in addr{};
  9491. addr.sin_family = AF_INET;
  9492. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9493. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9494. int opt = 1;
  9495. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9496. #ifdef _WIN32
  9497. reinterpret_cast<const char *>(&opt),
  9498. #else
  9499. &opt,
  9500. #endif
  9501. sizeof(opt));
  9502. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9503. ::listen(srv, 1);
  9504. sockaddr_in cli_addr{};
  9505. socklen_t cli_len = sizeof(cli_addr);
  9506. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9507. if (cli != INVALID_SOCKET) {
  9508. char buf[4096];
  9509. ::recv(cli, buf, sizeof(buf), 0);
  9510. // Malicious response: claim a 20GB body but send only a tiny payload.
  9511. std::string response = "HTTP/1.1 200 OK\r\n"
  9512. "Content-Length: 20000000000\r\n"
  9513. "\r\n"
  9514. "abc";
  9515. ::send(cli,
  9516. #ifdef _WIN32
  9517. static_cast<const char *>(response.c_str()),
  9518. static_cast<int>(response.size()),
  9519. #else
  9520. response.c_str(), response.size(),
  9521. #endif
  9522. 0);
  9523. detail::close_socket(cli);
  9524. }
  9525. detail::close_socket(srv);
  9526. });
  9527. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9528. {
  9529. Client cli("127.0.0.1", PORT + 2);
  9530. cli.set_read_timeout(5, 0);
  9531. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9532. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9533. // (server claims more bytes than payload_max_length permits), but it must
  9534. // not exhaust memory before getting there.
  9535. auto res = cli.Get("/malicious");
  9536. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9537. }
  9538. server_thread.join();
  9539. }
  9540. // Verify that content_receiver bypasses the default payload_max_length,
  9541. // allowing streaming downloads larger than 100MB without requiring an explicit
  9542. // set_payload_max_length call.
  9543. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9544. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9545. #ifndef _WIN32
  9546. signal(SIGPIPE, SIG_IGN);
  9547. #endif
  9548. auto server_thread = std::thread([] {
  9549. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9550. default_socket_options(srv);
  9551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9552. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9553. sockaddr_in addr{};
  9554. addr.sin_family = AF_INET;
  9555. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9556. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9557. int opt = 1;
  9558. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9559. #ifdef _WIN32
  9560. reinterpret_cast<const char *>(&opt),
  9561. #else
  9562. &opt,
  9563. #endif
  9564. sizeof(opt));
  9565. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9566. ::listen(srv, 1);
  9567. sockaddr_in cli_addr{};
  9568. socklen_t cli_len = sizeof(cli_addr);
  9569. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9570. if (cli != INVALID_SOCKET) {
  9571. char buf[4096];
  9572. ::recv(cli, buf, sizeof(buf), 0);
  9573. // Response with Content-Length larger than default 100MB limit
  9574. auto content_length = std::to_string(DATA_SIZE);
  9575. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9576. "Content-Length: " +
  9577. content_length +
  9578. "\r\n"
  9579. "Connection: close\r\n"
  9580. "\r\n";
  9581. ::send(cli,
  9582. #ifdef _WIN32
  9583. static_cast<const char *>(response_header.c_str()),
  9584. static_cast<int>(response_header.size()),
  9585. #else
  9586. response_header.c_str(), response_header.size(),
  9587. #endif
  9588. 0);
  9589. std::string chunk(64 * 1024, 'A');
  9590. size_t total_sent = 0;
  9591. while (total_sent < DATA_SIZE) {
  9592. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9593. auto sent = ::send(cli,
  9594. #ifdef _WIN32
  9595. static_cast<const char *>(chunk.c_str()),
  9596. static_cast<int>(to_send),
  9597. #else
  9598. chunk.c_str(), to_send,
  9599. #endif
  9600. 0);
  9601. if (sent <= 0) break;
  9602. total_sent += static_cast<size_t>(sent);
  9603. }
  9604. detail::close_socket(cli);
  9605. }
  9606. detail::close_socket(srv);
  9607. });
  9608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9609. size_t total_received = 0;
  9610. {
  9611. Client cli("127.0.0.1", PORT + 2);
  9612. cli.set_read_timeout(10, 0);
  9613. // Do NOT call set_payload_max_length — use the default 100MB limit
  9614. auto res =
  9615. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9616. total_received += data_length;
  9617. return true;
  9618. });
  9619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9620. EXPECT_EQ(StatusCode::OK_200, res->status);
  9621. }
  9622. server_thread.join();
  9623. EXPECT_EQ(total_received, DATA_SIZE)
  9624. << "With content_receiver, the client should read all " << DATA_SIZE
  9625. << " bytes despite the default 100MB payload_max_length, but only read "
  9626. << total_received << " bytes.";
  9627. }
  9628. // Verify that an explicit set_payload_max_length smaller than the response is
  9629. // enforced even when a content_receiver is used.
  9630. TEST(ClientVulnerabilityTest,
  9631. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9632. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9633. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9634. #ifndef _WIN32
  9635. signal(SIGPIPE, SIG_IGN);
  9636. #endif
  9637. auto server_thread = std::thread([] {
  9638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9639. default_socket_options(srv);
  9640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9642. sockaddr_in addr{};
  9643. addr.sin_family = AF_INET;
  9644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9646. int opt = 1;
  9647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9648. #ifdef _WIN32
  9649. reinterpret_cast<const char *>(&opt),
  9650. #else
  9651. &opt,
  9652. #endif
  9653. sizeof(opt));
  9654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9655. ::listen(srv, 1);
  9656. sockaddr_in cli_addr{};
  9657. socklen_t cli_len = sizeof(cli_addr);
  9658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9659. if (cli != INVALID_SOCKET) {
  9660. char buf[4096];
  9661. ::recv(cli, buf, sizeof(buf), 0);
  9662. auto content_length = std::to_string(DATA_SIZE);
  9663. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9664. "Content-Length: " +
  9665. content_length +
  9666. "\r\n"
  9667. "Connection: close\r\n"
  9668. "\r\n";
  9669. ::send(cli,
  9670. #ifdef _WIN32
  9671. static_cast<const char *>(response_header.c_str()),
  9672. static_cast<int>(response_header.size()),
  9673. #else
  9674. response_header.c_str(), response_header.size(),
  9675. #endif
  9676. 0);
  9677. std::string chunk(64 * 1024, 'A');
  9678. size_t total_sent = 0;
  9679. while (total_sent < DATA_SIZE) {
  9680. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9681. auto sent = ::send(cli,
  9682. #ifdef _WIN32
  9683. static_cast<const char *>(chunk.c_str()),
  9684. static_cast<int>(to_send),
  9685. #else
  9686. chunk.c_str(), to_send,
  9687. #endif
  9688. 0);
  9689. if (sent <= 0) break;
  9690. total_sent += static_cast<size_t>(sent);
  9691. }
  9692. detail::close_socket(cli);
  9693. }
  9694. detail::close_socket(srv);
  9695. });
  9696. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9697. size_t total_received = 0;
  9698. {
  9699. Client cli("127.0.0.1", PORT + 2);
  9700. cli.set_read_timeout(10, 0);
  9701. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9702. auto res =
  9703. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9704. total_received += data_length;
  9705. return true;
  9706. });
  9707. // Should fail because 200MB exceeds the explicit 150MB limit
  9708. EXPECT_FALSE(res);
  9709. }
  9710. server_thread.join();
  9711. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9712. << "Client with content_receiver should respect the explicit "
  9713. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9714. << total_received << " bytes.";
  9715. }
  9716. // Verify that an explicit set_payload_max_length larger than the response
  9717. // allows the content_receiver to read all data successfully.
  9718. TEST(ClientVulnerabilityTest,
  9719. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9720. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9721. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9722. #ifndef _WIN32
  9723. signal(SIGPIPE, SIG_IGN);
  9724. #endif
  9725. auto server_thread = std::thread([] {
  9726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9727. default_socket_options(srv);
  9728. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9730. sockaddr_in addr{};
  9731. addr.sin_family = AF_INET;
  9732. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9734. int opt = 1;
  9735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9736. #ifdef _WIN32
  9737. reinterpret_cast<const char *>(&opt),
  9738. #else
  9739. &opt,
  9740. #endif
  9741. sizeof(opt));
  9742. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9743. ::listen(srv, 1);
  9744. sockaddr_in cli_addr{};
  9745. socklen_t cli_len = sizeof(cli_addr);
  9746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9747. if (cli != INVALID_SOCKET) {
  9748. char buf[4096];
  9749. ::recv(cli, buf, sizeof(buf), 0);
  9750. auto content_length = std::to_string(DATA_SIZE);
  9751. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9752. "Content-Length: " +
  9753. content_length +
  9754. "\r\n"
  9755. "Connection: close\r\n"
  9756. "\r\n";
  9757. ::send(cli,
  9758. #ifdef _WIN32
  9759. static_cast<const char *>(response_header.c_str()),
  9760. static_cast<int>(response_header.size()),
  9761. #else
  9762. response_header.c_str(), response_header.size(),
  9763. #endif
  9764. 0);
  9765. std::string chunk(64 * 1024, 'A');
  9766. size_t total_sent = 0;
  9767. while (total_sent < DATA_SIZE) {
  9768. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9769. auto sent = ::send(cli,
  9770. #ifdef _WIN32
  9771. static_cast<const char *>(chunk.c_str()),
  9772. static_cast<int>(to_send),
  9773. #else
  9774. chunk.c_str(), to_send,
  9775. #endif
  9776. 0);
  9777. if (sent <= 0) break;
  9778. total_sent += static_cast<size_t>(sent);
  9779. }
  9780. #ifdef _WIN32
  9781. ::shutdown(cli, SD_SEND);
  9782. #else
  9783. ::shutdown(cli, SHUT_WR);
  9784. #endif
  9785. char drain[1024];
  9786. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9787. detail::close_socket(cli);
  9788. }
  9789. detail::close_socket(srv);
  9790. });
  9791. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9792. size_t total_received = 0;
  9793. {
  9794. Client cli("127.0.0.1", PORT + 2);
  9795. cli.set_read_timeout(10, 0);
  9796. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9797. auto res =
  9798. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9799. total_received += data_length;
  9800. return true;
  9801. });
  9802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9803. EXPECT_EQ(StatusCode::OK_200, res->status);
  9804. }
  9805. server_thread.join();
  9806. EXPECT_EQ(total_received, DATA_SIZE)
  9807. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9808. << " bytes (larger than " << DATA_SIZE
  9809. << " bytes response), content_receiver should read all data, but only "
  9810. "read "
  9811. << total_received << " bytes.";
  9812. }
  9813. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9814. // Regression test for "zip bomb" attack on the client side: a malicious server
  9815. // sends a small gzip-compressed response that decompresses to a huge payload.
  9816. // The client must enforce payload_max_length on the decompressed size.
  9817. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9818. constexpr size_t DECOMPRESSED_SIZE =
  9819. 10 * 1024 * 1024; // 10MB after decompression
  9820. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9821. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9822. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9823. std::string compressed;
  9824. {
  9825. httplib::detail::gzip_compressor compressor;
  9826. bool ok =
  9827. compressor.compress(uncompressed.data(), uncompressed.size(),
  9828. /*last=*/true, [&](const char *buf, size_t len) {
  9829. compressed.append(buf, len);
  9830. return true;
  9831. });
  9832. ASSERT_TRUE(ok);
  9833. }
  9834. // Sanity: compressed data should be much smaller than the decompressed size
  9835. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9836. #ifndef _WIN32
  9837. signal(SIGPIPE, SIG_IGN);
  9838. #endif
  9839. // Set up the listening socket in the main thread so the server is guaranteed
  9840. // to be ready before the client connects (eliminates race condition).
  9841. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9842. default_socket_options(srv);
  9843. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9844. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9845. sockaddr_in addr{};
  9846. addr.sin_family = AF_INET;
  9847. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9848. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9849. int opt = 1;
  9850. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9851. #ifdef _WIN32
  9852. reinterpret_cast<const char *>(&opt),
  9853. #else
  9854. &opt,
  9855. #endif
  9856. sizeof(opt));
  9857. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9858. ASSERT_EQ(0, ::listen(srv, 1));
  9859. auto server_thread = std::thread([&compressed, srv] {
  9860. sockaddr_in cli_addr{};
  9861. socklen_t cli_len = sizeof(cli_addr);
  9862. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9863. if (cli != INVALID_SOCKET) {
  9864. // Read the full HTTP request (until \r\n\r\n)
  9865. char buf[4096];
  9866. size_t total = 0;
  9867. while (total < sizeof(buf)) {
  9868. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9869. if (n <= 0) break;
  9870. total += static_cast<size_t>(n);
  9871. // Check for end of headers
  9872. if (total >= 4) {
  9873. std::string req(buf, total);
  9874. if (req.find("\r\n\r\n") != std::string::npos) break;
  9875. }
  9876. }
  9877. // Malicious response: gzip-compressed body, no Content-Length
  9878. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9879. "Content-Encoding: gzip\r\n"
  9880. "Connection: close\r\n"
  9881. "\r\n";
  9882. ::send(cli,
  9883. #ifdef _WIN32
  9884. static_cast<const char *>(response_header.c_str()),
  9885. static_cast<int>(response_header.size()),
  9886. #else
  9887. response_header.c_str(), response_header.size(),
  9888. #endif
  9889. 0);
  9890. // Send the compressed payload (small on the wire, huge when decompressed)
  9891. size_t total_sent = 0;
  9892. while (total_sent < compressed.size()) {
  9893. auto to_send = std::min(compressed.size() - total_sent,
  9894. static_cast<size_t>(64 * 1024));
  9895. auto sent =
  9896. ::send(cli,
  9897. #ifdef _WIN32
  9898. static_cast<const char *>(compressed.c_str() + total_sent),
  9899. static_cast<int>(to_send),
  9900. #else
  9901. compressed.c_str() + total_sent, to_send,
  9902. #endif
  9903. 0);
  9904. if (sent <= 0) break;
  9905. total_sent += static_cast<size_t>(sent);
  9906. }
  9907. detail::close_socket(cli);
  9908. }
  9909. });
  9910. auto se = detail::scope_exit([&] {
  9911. detail::close_socket(srv);
  9912. server_thread.join();
  9913. });
  9914. size_t total_decompressed = 0;
  9915. {
  9916. Client cli("127.0.0.1", PORT + 3);
  9917. cli.set_read_timeout(5, 0);
  9918. cli.set_decompress(true);
  9919. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9920. auto stream = cli.open_stream("GET", "/zipbomb");
  9921. ASSERT_TRUE(stream.is_valid());
  9922. char buffer[64 * 1024];
  9923. ssize_t n;
  9924. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9925. total_decompressed += static_cast<size_t>(n);
  9926. }
  9927. }
  9928. // The decompressed size must be capped by payload_max_length. Without
  9929. // protection, the client would decompress the full 10MB from a tiny
  9930. // compressed payload, enabling a zip bomb DoS attack.
  9931. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9932. << "Client decompressed " << total_decompressed
  9933. << " bytes from a gzip response. The decompressed size should be "
  9934. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9935. }
  9936. #endif
  9937. TEST(HostAndPortPropertiesTest, NoSSL) {
  9938. httplib::Client cli("www.google.com", 1234);
  9939. ASSERT_EQ("www.google.com", cli.host());
  9940. ASSERT_EQ(1234, cli.port());
  9941. }
  9942. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9943. httplib::Client cli("www.google.com:1234");
  9944. ASSERT_EQ("www.google.com", cli.host());
  9945. ASSERT_EQ(1234, cli.port());
  9946. }
  9947. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9948. // Port number that overflows int — should not crash, client becomes invalid
  9949. httplib::Client cli("http://www.google.com:99999999999999999999");
  9950. ASSERT_FALSE(cli.is_valid());
  9951. }
  9952. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9953. // Port 99999 exceeds valid range (1-65535) — should not crash
  9954. httplib::Client cli("http://www.google.com:99999");
  9955. ASSERT_FALSE(cli.is_valid());
  9956. }
  9957. #ifdef CPPHTTPLIB_SSL_ENABLED
  9958. TEST(HostAndPortPropertiesTest, SSL) {
  9959. httplib::SSLClient cli("www.google.com");
  9960. ASSERT_EQ("www.google.com", cli.host());
  9961. ASSERT_EQ(443, cli.port());
  9962. }
  9963. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9964. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9965. std::string cert;
  9966. read_file(CA_CERT_FILE, cert);
  9967. httplib::SSLClient httplib_client("www.google.com");
  9968. // Load CA store first time
  9969. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9970. // Load CA store second time (update)
  9971. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9972. // Verify client is still valid and can make connections
  9973. httplib_client.enable_server_certificate_verification(true);
  9974. auto res = httplib_client.Get("/");
  9975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9976. // Google may return 200 or 301 depending on various factors
  9977. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9978. res->status == StatusCode::MovedPermanently_301);
  9979. }
  9980. TEST(SSLClientTest, ServerNameIndication_Online) {
  9981. auto host = "httpbingo.org";
  9982. auto path = std::string{"/get"};
  9983. SSLClient cli(host, 443);
  9984. auto res = cli.Get(path);
  9985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9986. ASSERT_EQ(StatusCode::OK_200, res->status);
  9987. }
  9988. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9989. // Use a site that will cause SSL verification failure due to self-signed cert
  9990. SSLClient cli("self-signed.badssl.com", 443);
  9991. cli.enable_server_certificate_verification(true);
  9992. auto res = cli.Get("/");
  9993. ASSERT_TRUE(!res);
  9994. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9995. // Verify backend error is captured for SSLServerVerification
  9996. // This occurs when certificate verification fails
  9997. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9998. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9999. EXPECT_NE(0UL, res.ssl_backend_error());
  10000. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10001. // For OpenSSL, ssl_error is 0 for verification errors
  10002. EXPECT_EQ(0, res.ssl_error());
  10003. #if !defined(_WIN32) || \
  10004. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10005. // On non-Windows or when Windows Schannel is disabled, the error comes
  10006. // from OpenSSL's verification
  10007. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10008. res.ssl_backend_error());
  10009. #endif
  10010. #endif
  10011. }
  10012. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10013. // Use a site where hostname doesn't match the certificate
  10014. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10015. SSLClient cli("wrong.host.badssl.com", 443);
  10016. cli.enable_server_certificate_verification(true);
  10017. cli.enable_server_hostname_verification(true);
  10018. auto res = cli.Get("/");
  10019. ASSERT_TRUE(!res);
  10020. // The error type depends on when hostname verification occurs:
  10021. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  10022. // - Mbed TLS: SSLServerVerification (during handshake)
  10023. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  10024. res.error() == Error::SSLServerVerification);
  10025. // Verify backend error is captured for hostname verification failure
  10026. EXPECT_NE(0UL, res.ssl_backend_error());
  10027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10028. // For OpenSSL, ssl_error is 0 for verification errors
  10029. EXPECT_EQ(0, res.ssl_error());
  10030. #if !defined(_WIN32) || \
  10031. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10032. // On non-Windows or when Windows Schannel is disabled, the error comes
  10033. // from OpenSSL's hostname verification
  10034. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10035. res.ssl_backend_error());
  10036. #endif
  10037. #endif
  10038. }
  10039. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10040. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10041. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10042. SSLClient cli("www.google.com", 443);
  10043. cli.enable_server_certificate_verification(true);
  10044. auto res = cli.Get("/");
  10045. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10046. }
  10047. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10048. SSLClient cli("www.google.com", 443);
  10049. cli.enable_server_certificate_verification(true);
  10050. cli.enable_windows_certificate_verification(false);
  10051. auto res = cli.Get("/");
  10052. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10053. }
  10054. #endif
  10055. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10056. Client cli("https://google.com");
  10057. auto res = cli.Get("/");
  10058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10059. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10060. }
  10061. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10062. SSLClient cli("google.com");
  10063. cli.set_ca_cert_path(CA_CERT_FILE);
  10064. auto res = cli.Get("/");
  10065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10066. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10067. }
  10068. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10069. SSLClient cli("google.com");
  10070. cli.enable_server_certificate_verification(true);
  10071. cli.set_ca_cert_path("hello");
  10072. auto res = cli.Get("/");
  10073. ASSERT_TRUE(!res);
  10074. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10075. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10076. // should be set
  10077. EXPECT_EQ(0, res.ssl_error());
  10078. // Verify backend error is captured for SSLLoadingCerts
  10079. // This error occurs when loading CA certificates fails
  10080. EXPECT_NE(0UL, res.ssl_backend_error());
  10081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10082. // OpenSSL specific error codes:
  10083. // > openssl errstr 0x80000002
  10084. // error:80000002:system library::No such file or directory
  10085. // > openssl errstr 0xA000126
  10086. // error:0A000126:SSL routines::unexpected eof while reading
  10087. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10088. res.ssl_backend_error() == 0xA000126);
  10089. #endif
  10090. }
  10091. TEST(SSLClientTest, ServerCertificateVerification4) {
  10092. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10093. ASSERT_TRUE(svr.is_valid());
  10094. svr.Get("/test", [&](const Request &, Response &res) {
  10095. res.set_content("test", "text/plain");
  10096. svr.stop();
  10097. ASSERT_TRUE(true);
  10098. });
  10099. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10100. auto se = detail::scope_exit([&] {
  10101. t.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. SSLClient cli("127.0.0.1", PORT);
  10106. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10107. cli.enable_server_certificate_verification(true);
  10108. cli.set_connection_timeout(30);
  10109. auto res = cli.Get("/test");
  10110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10111. ASSERT_EQ(StatusCode::OK_200, res->status);
  10112. }
  10113. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10114. std::string cert;
  10115. read_file(CA_CERT_FILE, cert);
  10116. SSLClient cli("google.com");
  10117. cli.load_ca_cert_store(cert.data(), cert.size());
  10118. const auto res = cli.Get("/");
  10119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10120. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10121. }
  10122. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10123. // clang-format off
  10124. static constexpr char cert[] =
  10125. "GlobalSign Root CA\n"
  10126. "==================\n"
  10127. "-----BEGIN CERTIFICATE-----\n"
  10128. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10129. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10130. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10131. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10132. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10133. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10134. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10135. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10136. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10137. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10138. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10139. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10140. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10141. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10142. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10143. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10144. "-----END CERTIFICATE-----\n";
  10145. // clang-format on
  10146. SSLClient cli("google.com");
  10147. cli.load_ca_cert_store(cert, sizeof(cert));
  10148. const auto res = cli.Get("/");
  10149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10150. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10151. }
  10152. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10153. SSLClient cli("www.youtube.com");
  10154. cli.set_ca_cert_path(CA_CERT_FILE);
  10155. cli.enable_server_certificate_verification(true);
  10156. cli.set_follow_location(true);
  10157. auto res = cli.Get("/");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. ASSERT_EQ(StatusCode::OK_200, res->status);
  10160. }
  10161. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10162. SSLClient cli("wWw.YouTube.Com");
  10163. cli.set_ca_cert_path(CA_CERT_FILE);
  10164. cli.enable_server_certificate_verification(true);
  10165. cli.enable_server_hostname_verification(true);
  10166. cli.set_follow_location(true);
  10167. auto res = cli.Get("/");
  10168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10169. ASSERT_EQ(StatusCode::OK_200, res->status);
  10170. }
  10171. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10172. SSLClient cli("gOoGlE.COm");
  10173. cli.enable_server_certificate_verification(true);
  10174. cli.enable_server_hostname_verification(true);
  10175. cli.set_follow_location(true);
  10176. auto res = cli.Get("/");
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. ASSERT_EQ(StatusCode::OK_200, res->status);
  10179. }
  10180. TEST(SSLClientTest, Issue2004_Online) {
  10181. Client client("https://google.com");
  10182. client.set_follow_location(true);
  10183. auto res = client.Get("/");
  10184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10185. ASSERT_EQ(StatusCode::OK_200, res->status);
  10186. auto body = res->body;
  10187. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10188. }
  10189. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10190. // Create SSLClient with invalid cert/key to make is_valid() return false
  10191. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10192. "nonexistent_key.pem");
  10193. // is_valid() should be false due to cert loading failure
  10194. ASSERT_FALSE(cli.is_valid());
  10195. auto res = cli.Get("/");
  10196. ASSERT_FALSE(res);
  10197. EXPECT_EQ(Error::SSLConnection, res.error());
  10198. }
  10199. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10200. // Test for Issue #2251: SSL error not properly reported when client cert
  10201. // and key paths are swapped or mismatched
  10202. // This simulates the scenario where user accidentally swaps the cert and key
  10203. // files
  10204. // Using client cert file as private key and vice versa (completely wrong)
  10205. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10206. // Should fail validation due to cert/key mismatch
  10207. ASSERT_FALSE(cli.is_valid());
  10208. // Attempt to make a request should fail with proper error
  10209. auto res = cli.Get("/");
  10210. ASSERT_FALSE(res);
  10211. EXPECT_EQ(Error::SSLConnection, res.error());
  10212. // SSL error should be recorded in the Result object (this is the key fix for
  10213. // Issue #2251)
  10214. auto backend_error = res.ssl_backend_error();
  10215. EXPECT_NE(0u, backend_error);
  10216. }
  10217. // Tests cert/key mismatch detection at the TLS context level
  10218. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10219. // Test that using mismatched cert/key causes connection failure.
  10220. // We verify this at the SSLClient level rather than through internal
  10221. // TLS API functions.
  10222. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10223. cli.enable_server_certificate_verification(false);
  10224. cli.set_connection_timeout(2);
  10225. // The mismatch should cause a connection or handshake error
  10226. auto res = cli.Get("/test");
  10227. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10228. // Either way, the request should fail
  10229. EXPECT_FALSE(res);
  10230. }
  10231. #endif
  10232. #if 0
  10233. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10234. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10235. ASSERT_TRUE(cli != nullptr);
  10236. cli->set_address_family(AF_INET6);
  10237. cli->set_interface("en0");
  10238. auto res = cli->Get("/get");
  10239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10240. ASSERT_EQ(StatusCode::OK_200, res->status);
  10241. }
  10242. #endif
  10243. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10244. #ifdef CPPHTTPLIB_SSL_ENABLED
  10245. void ClientCertPresent(
  10246. const std::string &client_cert_file,
  10247. const std::string &client_private_key_file,
  10248. const std::string &client_encrypted_private_key_pass = std::string()) {
  10249. using namespace httplib::tls;
  10250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10251. CLIENT_CA_CERT_DIR);
  10252. ASSERT_TRUE(svr.is_valid());
  10253. svr.Get("/test", [&](const Request &req, Response &res) {
  10254. res.set_content("test", "text/plain");
  10255. auto cert = req.peer_cert();
  10256. ASSERT_TRUE(static_cast<bool>(cert));
  10257. std::string common_name = cert.subject_cn();
  10258. EXPECT_EQ("Common Name", common_name);
  10259. });
  10260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. t.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10268. client_encrypted_private_key_pass);
  10269. cli.enable_server_certificate_verification(false);
  10270. cli.set_connection_timeout(30);
  10271. auto res = cli.Get("/test");
  10272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10273. ASSERT_EQ(StatusCode::OK_200, res->status);
  10274. }
  10275. TEST(SSLClientServerTest, ClientCertPresent) {
  10276. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10277. }
  10278. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10279. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10280. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10281. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10282. }
  10283. // PEM memory-based constructor tests (works with all TLS backends)
  10284. void PemMemoryClientCertPresent(
  10285. const std::string &client_cert_file,
  10286. const std::string &client_private_key_file,
  10287. const std::string &client_encrypted_private_key_pass = std::string()) {
  10288. // Read PEM files into memory
  10289. std::string server_cert_pem, server_key_pem;
  10290. std::string client_ca_pem;
  10291. std::string client_cert_pem, client_key_pem;
  10292. read_file(SERVER_CERT_FILE, server_cert_pem);
  10293. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10294. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10295. read_file(client_cert_file, client_cert_pem);
  10296. read_file(client_private_key_file, client_key_pem);
  10297. // Create server with PEM memory
  10298. SSLServer::PemMemory server_pem = {
  10299. server_cert_pem.c_str(),
  10300. server_cert_pem.size(),
  10301. server_key_pem.c_str(),
  10302. server_key_pem.size(),
  10303. client_ca_pem.c_str(),
  10304. client_ca_pem.size(),
  10305. nullptr // no password for server key
  10306. };
  10307. SSLServer svr(server_pem);
  10308. ASSERT_TRUE(svr.is_valid());
  10309. svr.Get("/test", [&](const Request &, Response &res) {
  10310. res.set_content("test", "text/plain");
  10311. });
  10312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10313. auto se = detail::scope_exit([&] {
  10314. svr.stop();
  10315. t.join();
  10316. ASSERT_FALSE(svr.is_running());
  10317. });
  10318. svr.wait_until_ready();
  10319. // Create client with PEM memory
  10320. const char *password = client_encrypted_private_key_pass.empty()
  10321. ? nullptr
  10322. : client_encrypted_private_key_pass.c_str();
  10323. SSLClient::PemMemory client_pem = {
  10324. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10325. client_key_pem.size(), password};
  10326. SSLClient cli(HOST, PORT, client_pem);
  10327. cli.enable_server_certificate_verification(false);
  10328. cli.set_connection_timeout(30);
  10329. auto res = cli.Get("/test");
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. ASSERT_EQ(StatusCode::OK_200, res->status);
  10332. }
  10333. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10334. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10335. }
  10336. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10337. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10338. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10339. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10340. }
  10341. TEST(SSLClientServerTest, ClientCertMissing) {
  10342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10343. CLIENT_CA_CERT_DIR);
  10344. ASSERT_TRUE(svr.is_valid());
  10345. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. ASSERT_FALSE(svr.is_running());
  10351. });
  10352. svr.wait_until_ready();
  10353. SSLClient cli(HOST, PORT);
  10354. cli.set_connection_timeout(30);
  10355. auto res = cli.Get("/test");
  10356. ASSERT_TRUE(!res);
  10357. // When client cert is missing and server requires it, connection fails
  10358. // Error type depends on backend implementation
  10359. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10360. res.error() == Error::SSLConnection);
  10361. // Verify backend error is captured
  10362. // Note: This test may have different error codes depending on the exact
  10363. // verification failure
  10364. EXPECT_NE(0UL, res.ssl_backend_error());
  10365. }
  10366. TEST(SSLClientServerTest, TrustDirOptional) {
  10367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10368. ASSERT_TRUE(svr.is_valid());
  10369. svr.Get("/test", [&](const Request &, Response &res) {
  10370. res.set_content("test", "text/plain");
  10371. });
  10372. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. t.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10380. cli.enable_server_certificate_verification(false);
  10381. cli.set_connection_timeout(30);
  10382. auto res = cli.Get("/test");
  10383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10384. ASSERT_EQ(StatusCode::OK_200, res->status);
  10385. }
  10386. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10387. class NoListenSSLServer : public SSLServer {
  10388. public:
  10389. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10390. const char *client_ca_cert_file_path,
  10391. const char *client_ca_cert_dir_path = nullptr)
  10392. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10393. client_ca_cert_dir_path),
  10394. stop_(false) {}
  10395. std::atomic_bool stop_;
  10396. private:
  10397. bool process_and_close_socket(socket_t /*sock*/) override {
  10398. // Don't create SSL context
  10399. while (!stop_.load()) {
  10400. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10401. }
  10402. return true;
  10403. }
  10404. };
  10405. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10406. CLIENT_CA_CERT_FILE);
  10407. ASSERT_TRUE(svr.is_valid());
  10408. svr.Get("/test", [&](const Request &, Response &res) {
  10409. res.set_content("test", "text/plain");
  10410. });
  10411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10412. auto se = detail::scope_exit([&] {
  10413. svr.stop_ = true;
  10414. svr.stop();
  10415. t.join();
  10416. ASSERT_FALSE(svr.is_running());
  10417. });
  10418. svr.wait_until_ready();
  10419. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10420. cli.enable_server_certificate_verification(false);
  10421. cli.set_connection_timeout(1);
  10422. auto res = cli.Get("/test");
  10423. ASSERT_TRUE(!res);
  10424. EXPECT_EQ(Error::SSLConnection, res.error());
  10425. // Timeout results in WantRead error code (maps to backend-specific value)
  10426. EXPECT_NE(0, res.ssl_error());
  10427. }
  10428. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10429. // Test SSLServer with client certificate verification using the standard
  10430. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10432. CLIENT_CA_CERT_DIR);
  10433. ASSERT_TRUE(svr.is_valid());
  10434. svr.Get("/test", [&](const Request &req, Response &res) {
  10435. res.set_content("test", "text/plain");
  10436. auto cert = req.peer_cert();
  10437. ASSERT_TRUE(static_cast<bool>(cert));
  10438. auto common_name = cert.subject_cn();
  10439. EXPECT_EQ("Common Name", common_name);
  10440. });
  10441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10442. auto se = detail::scope_exit([&] {
  10443. svr.stop();
  10444. t.join();
  10445. ASSERT_FALSE(svr.is_running());
  10446. });
  10447. svr.wait_until_ready();
  10448. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10449. cli.enable_server_certificate_verification(false);
  10450. cli.set_connection_timeout(30);
  10451. auto res = cli.Get("/test");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. ASSERT_EQ(StatusCode::OK_200, res->status);
  10454. }
  10455. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10456. // Verifies that wildcard matching and exact matching work consistently
  10457. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10458. using namespace httplib::tls;
  10459. // We need a running server to test against
  10460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10461. ASSERT_TRUE(svr.is_valid());
  10462. svr.Get("/test", [](const Request &, Response &res) {
  10463. res.set_content("ok", "text/plain");
  10464. });
  10465. thread t([&]() { svr.listen(HOST, PORT); });
  10466. auto se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. t.join();
  10469. });
  10470. svr.wait_until_ready();
  10471. bool verify_callback_called = false;
  10472. bool verify_result_wrong = false;
  10473. SSLClient cli(HOST, PORT);
  10474. cli.enable_server_certificate_verification(true);
  10475. cli.set_ca_cert_path(CA_CERT_FILE);
  10476. cli.set_connection_timeout(5);
  10477. // Note: Test certificate has CN="Common Name", not "localhost"
  10478. bool verify_result_cn = false;
  10479. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10480. verify_callback_called = true;
  10481. if (!ctx.cert) return false;
  10482. // Test 1: "Common Name" should match (our test server cert CN)
  10483. verify_result_cn = ctx.check_hostname("Common Name");
  10484. // Test 2: wrong hostname should not match
  10485. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10486. return true; // Accept for the purpose of this test
  10487. });
  10488. auto res = cli.Get("/test");
  10489. // The request may succeed or fail depending on cert configuration
  10490. // but the callback should have been called
  10491. ASSERT_TRUE(verify_callback_called)
  10492. << "Verify callback should have been called";
  10493. // CN="Common Name" should match our test certificate
  10494. //
  10495. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10496. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10497. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10498. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10499. // <openssl/base.h>, which is included transitively when
  10500. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10501. #if defined(OPENSSL_IS_BORINGSSL)
  10502. EXPECT_FALSE(verify_result_cn)
  10503. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10504. #else
  10505. EXPECT_TRUE(verify_result_cn)
  10506. << "verify_hostname should match 'Common Name' (certificate CN)";
  10507. #endif
  10508. // Wrong hostname should not match
  10509. EXPECT_FALSE(verify_result_wrong)
  10510. << "verify_hostname should not match 'wronghost.example.com'";
  10511. }
  10512. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10513. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10514. // X509_check_ip behavior and must hold for every backend.
  10515. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10516. using namespace httplib::tls;
  10517. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10518. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10519. ASSERT_TRUE(svr.is_valid());
  10520. svr.Get("/test", [](const Request &, Response &res) {
  10521. res.set_content("ok", "text/plain");
  10522. });
  10523. thread t([&]() { svr.listen(HOST, PORT); });
  10524. auto se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. t.join();
  10527. });
  10528. svr.wait_until_ready();
  10529. bool verify_callback_called = false;
  10530. bool ip_matched_via_cn = true;
  10531. SSLClient cli(HOST, PORT);
  10532. cli.enable_server_certificate_verification(true);
  10533. cli.set_ca_cert_path(CA_CERT_FILE);
  10534. cli.set_connection_timeout(5);
  10535. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10536. verify_callback_called = true;
  10537. if (!ctx.cert) return false;
  10538. // The IP appears only in the CN, so it must NOT be accepted.
  10539. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10540. return true; // Accept for the purpose of this test
  10541. });
  10542. cli.Get("/test");
  10543. ASSERT_TRUE(verify_callback_called)
  10544. << "Verify callback should have been called";
  10545. EXPECT_FALSE(ip_matched_via_cn)
  10546. << "An IP host must not be authenticated via the certificate CN";
  10547. }
  10548. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10549. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10550. using namespace httplib::tls;
  10551. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10552. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10553. ASSERT_TRUE(svr.is_valid());
  10554. svr.Get("/test", [](const Request &, Response &res) {
  10555. res.set_content("ok", "text/plain");
  10556. });
  10557. thread t([&]() { svr.listen(HOST, PORT); });
  10558. auto se = detail::scope_exit([&] {
  10559. svr.stop();
  10560. t.join();
  10561. });
  10562. svr.wait_until_ready();
  10563. bool verify_callback_called = false;
  10564. bool san_matched = false;
  10565. bool wrong_ipv6_matched = true;
  10566. bool cn_ipv6_matched = true;
  10567. SSLClient cli(HOST, PORT);
  10568. cli.enable_server_certificate_verification(true);
  10569. cli.set_ca_cert_path(CA_CERT_FILE);
  10570. cli.set_connection_timeout(5);
  10571. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10572. verify_callback_called = true;
  10573. if (!ctx.cert) return false;
  10574. // Matches the IPv6 iPAddress SAN.
  10575. san_matched = ctx.check_hostname("2001:db8::1");
  10576. // A different IPv6 address must not match.
  10577. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10578. // "::1" lives only in the CN, so it must not be accepted.
  10579. cn_ipv6_matched = ctx.check_hostname("::1");
  10580. return true; // Accept for the purpose of this test
  10581. });
  10582. cli.Get("/test");
  10583. ASSERT_TRUE(verify_callback_called)
  10584. << "Verify callback should have been called";
  10585. EXPECT_TRUE(san_matched)
  10586. << "verify_hostname should match an IPv6 iPAddress SAN";
  10587. EXPECT_FALSE(wrong_ipv6_matched)
  10588. << "verify_hostname should not match a non-matching IPv6 address";
  10589. EXPECT_FALSE(cn_ipv6_matched)
  10590. << "An IPv6 host must not be authenticated via the certificate CN";
  10591. }
  10592. #endif
  10593. // mbedTLS-specific callback constructor test
  10594. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10595. #ifdef CPPHTTPLIB_SSL_ENABLED
  10596. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10598. ASSERT_TRUE(svr.is_valid());
  10599. // Set up a handler to verify client certificate is present
  10600. bool client_cert_verified = false;
  10601. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10602. // Verify that client certificate was provided
  10603. client_cert_verified = true;
  10604. res.set_content("success", "text/plain");
  10605. });
  10606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.wait_until_ready();
  10613. // Client with certificate
  10614. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10615. cli.enable_server_certificate_verification(false);
  10616. cli.set_connection_timeout(30);
  10617. auto res = cli.Get("/test");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. ASSERT_EQ(StatusCode::OK_200, res->status);
  10620. ASSERT_TRUE(client_cert_verified);
  10621. EXPECT_EQ("success", res->body);
  10622. }
  10623. #endif
  10624. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10625. // backends
  10626. #ifdef CPPHTTPLIB_SSL_ENABLED
  10627. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10628. using namespace httplib::tls;
  10629. // Test that when client CA cert file is provided,
  10630. // the server properly requests and validates client certificates
  10631. // Create a server with client authentication
  10632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10633. ASSERT_TRUE(svr.is_valid());
  10634. bool handler_called = false;
  10635. svr.Get("/test", [&](const Request &req, Response &res) {
  10636. handler_called = true;
  10637. // Verify that a client certificate was provided
  10638. auto cert = req.peer_cert();
  10639. ASSERT_TRUE(static_cast<bool>(cert));
  10640. // Get the issuer name
  10641. std::string issuer_str = cert.issuer_name();
  10642. ASSERT_FALSE(issuer_str.empty());
  10643. // The client certificate should be issued by our test CA
  10644. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10645. res.set_content("authenticated", "text/plain");
  10646. });
  10647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. t.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.wait_until_ready();
  10654. // Connect with a client certificate issued by the CA
  10655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10656. cli.enable_server_certificate_verification(false);
  10657. cli.set_connection_timeout(30);
  10658. auto res = cli.Get("/test");
  10659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10660. ASSERT_EQ(StatusCode::OK_200, res->status);
  10661. ASSERT_TRUE(handler_called);
  10662. EXPECT_EQ("authenticated", res->body);
  10663. }
  10664. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10665. using namespace httplib::tls;
  10666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10667. ASSERT_TRUE(svr.is_valid());
  10668. svr.Get("/test", [](const Request &, Response &res) {
  10669. res.set_content("ok", "text/plain");
  10670. });
  10671. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. t.join();
  10675. });
  10676. svr.wait_until_ready();
  10677. SSLClient cli(HOST, PORT);
  10678. cli.enable_server_certificate_verification(false);
  10679. cli.set_connection_timeout(30);
  10680. bool cert_checked = false;
  10681. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10682. if (ctx.cert) {
  10683. auto sans = ctx.sans();
  10684. // Test certificate may or may not have SANs - just verify the API
  10685. // works If SANs exist, verify the types are valid
  10686. for (const auto &san : sans) {
  10687. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10688. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10689. san.type == SanType::OTHER);
  10690. EXPECT_FALSE(san.value.empty());
  10691. }
  10692. cert_checked = true;
  10693. }
  10694. return true;
  10695. });
  10696. auto res = cli.Get("/test");
  10697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10698. EXPECT_TRUE(cert_checked);
  10699. }
  10700. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10701. using namespace httplib::tls;
  10702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10703. ASSERT_TRUE(svr.is_valid());
  10704. svr.Get("/test", [](const Request &, Response &res) {
  10705. res.set_content("ok", "text/plain");
  10706. });
  10707. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10708. auto se = detail::scope_exit([&] {
  10709. svr.stop();
  10710. t.join();
  10711. });
  10712. svr.wait_until_ready();
  10713. SSLClient cli(HOST, PORT);
  10714. cli.enable_server_certificate_verification(false);
  10715. cli.set_connection_timeout(30);
  10716. bool validity_checked = false;
  10717. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10718. if (ctx.cert) {
  10719. time_t not_before = 0, not_after = 0;
  10720. bool result = ctx.validity(not_before, not_after);
  10721. EXPECT_TRUE(result);
  10722. // Verify that not_before < now < not_after for a valid cert
  10723. time_t now = time(nullptr);
  10724. EXPECT_LT(not_before, now);
  10725. EXPECT_GT(not_after, now);
  10726. validity_checked = true;
  10727. }
  10728. return true;
  10729. });
  10730. auto res = cli.Get("/test");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. EXPECT_TRUE(validity_checked);
  10733. }
  10734. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10735. using namespace httplib::tls;
  10736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10737. ASSERT_TRUE(svr.is_valid());
  10738. svr.Get("/test", [](const Request &, Response &res) {
  10739. res.set_content("ok", "text/plain");
  10740. });
  10741. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. t.join();
  10745. });
  10746. svr.wait_until_ready();
  10747. SSLClient cli(HOST, PORT);
  10748. cli.enable_server_certificate_verification(false);
  10749. cli.set_connection_timeout(30);
  10750. bool serial_checked = false;
  10751. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10752. if (ctx.cert) {
  10753. std::string serial = ctx.serial();
  10754. EXPECT_FALSE(serial.empty());
  10755. // Serial should be a hex string
  10756. for (char c : serial) {
  10757. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10758. (c >= 'a' && c <= 'f'));
  10759. }
  10760. serial_checked = true;
  10761. }
  10762. return true;
  10763. });
  10764. auto res = cli.Get("/test");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_TRUE(serial_checked);
  10767. }
  10768. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10769. // Test 1: Valid CA file - no error should be recorded
  10770. {
  10771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10772. CLIENT_CA_CERT_FILE);
  10773. ASSERT_TRUE(svr.is_valid());
  10774. // With valid setup, last_ssl_error should be 0
  10775. EXPECT_EQ(0, svr.ssl_last_error());
  10776. }
  10777. // Test 2: Invalid CA file content
  10778. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10779. {
  10780. // Create a temporary file with completely invalid content
  10781. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10782. {
  10783. std::ofstream ofs(temp_invalid_ca);
  10784. ofs << "This is not a certificate file at all\n";
  10785. ofs << "Just plain text content\n";
  10786. }
  10787. // Create server with invalid CA file
  10788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10789. // Clean up temporary file
  10790. std::remove(temp_invalid_ca);
  10791. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10792. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10793. // Note: SSL_CTX_load_verify_locations typically fails first,
  10794. // but our error handling code path is still exercised
  10795. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10796. }
  10797. }
  10798. TEST(VerifyCallbackTest, VerifyContextFields) {
  10799. using namespace httplib::tls;
  10800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10801. ASSERT_TRUE(svr.is_valid());
  10802. svr.Get("/test", [](const Request &, Response &res) {
  10803. res.set_content("ok", "text/plain");
  10804. });
  10805. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10806. auto se = detail::scope_exit([&] {
  10807. svr.stop();
  10808. t.join();
  10809. });
  10810. svr.wait_until_ready();
  10811. SSLClient cli(HOST, PORT);
  10812. cli.enable_server_certificate_verification(false);
  10813. cli.set_connection_timeout(30);
  10814. int callback_count = 0;
  10815. bool saw_leaf_cert = false;
  10816. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10817. if (ctx.cert) {
  10818. callback_count++;
  10819. // We should see at least one certificate (the leaf)
  10820. std::string cn = ctx.subject_cn();
  10821. if (!cn.empty()) { saw_leaf_cert = true; }
  10822. // Verify context fields are populated
  10823. EXPECT_NE(ctx.session, nullptr);
  10824. EXPECT_GE(ctx.depth, 0);
  10825. }
  10826. return true;
  10827. });
  10828. auto res = cli.Get("/test");
  10829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10830. EXPECT_GT(callback_count, 0);
  10831. EXPECT_TRUE(saw_leaf_cert);
  10832. }
  10833. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10834. using httplib::tls::TlsError;
  10835. // Test that verify_error_to_string returns empty for success
  10836. std::string success_str = TlsError::verify_error_to_string(0);
  10837. EXPECT_TRUE(success_str.empty());
  10838. // Test that verify_error_to_string returns non-empty for error codes
  10839. // Using a common error code (certificate expired)
  10840. std::string error_str =
  10841. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10842. EXPECT_FALSE(error_str.empty());
  10843. }
  10844. TEST(SessionVerifierTest, CertificateAccepted) {
  10845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10846. ASSERT_TRUE(svr.is_valid());
  10847. svr.Get("/test", [](const Request &, Response &res) {
  10848. res.set_content("ok", "text/plain");
  10849. });
  10850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. t.join();
  10854. });
  10855. svr.wait_until_ready();
  10856. SSLClient cli(HOST, PORT);
  10857. cli.enable_server_certificate_verification(false);
  10858. cli.set_connection_timeout(30);
  10859. bool callback_called = false;
  10860. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10861. EXPECT_NE(session, nullptr);
  10862. callback_called = true;
  10863. return SSLVerifierResponse::CertificateAccepted;
  10864. });
  10865. auto res = cli.Get("/test");
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. EXPECT_EQ(200, res->status);
  10868. EXPECT_TRUE(callback_called);
  10869. }
  10870. TEST(SessionVerifierTest, CertificateRejected) {
  10871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10872. ASSERT_TRUE(svr.is_valid());
  10873. svr.Get("/test", [](const Request &, Response &res) {
  10874. res.set_content("ok", "text/plain");
  10875. });
  10876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10877. auto se = detail::scope_exit([&] {
  10878. svr.stop();
  10879. t.join();
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_connection_timeout(30);
  10885. bool callback_called = false;
  10886. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10887. EXPECT_NE(session, nullptr);
  10888. callback_called = true;
  10889. return SSLVerifierResponse::CertificateRejected;
  10890. });
  10891. auto res = cli.Get("/test");
  10892. EXPECT_FALSE(res);
  10893. EXPECT_TRUE(callback_called);
  10894. }
  10895. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10897. ASSERT_TRUE(svr.is_valid());
  10898. svr.Get("/test", [](const Request &, Response &res) {
  10899. res.set_content("ok", "text/plain");
  10900. });
  10901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. t.join();
  10905. });
  10906. svr.wait_until_ready();
  10907. // NoDecisionMade with verification disabled should succeed (no default check)
  10908. SSLClient cli(HOST, PORT);
  10909. cli.enable_server_certificate_verification(false);
  10910. cli.set_connection_timeout(30);
  10911. bool callback_called = false;
  10912. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10913. EXPECT_NE(session, nullptr);
  10914. callback_called = true;
  10915. return SSLVerifierResponse::NoDecisionMade;
  10916. });
  10917. auto res = cli.Get("/test");
  10918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10919. EXPECT_EQ(200, res->status);
  10920. EXPECT_TRUE(callback_called);
  10921. }
  10922. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10924. ASSERT_TRUE(svr.is_valid());
  10925. svr.Get("/test", [](const Request &, Response &res) {
  10926. res.set_content("ok", "text/plain");
  10927. });
  10928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. t.join();
  10932. });
  10933. svr.wait_until_ready();
  10934. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10935. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10936. // so we only check that the request fails, not whether the callback was
  10937. // called.
  10938. SSLClient cli(HOST, PORT);
  10939. cli.enable_server_certificate_verification(true);
  10940. cli.set_connection_timeout(30);
  10941. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10942. EXPECT_NE(session, nullptr);
  10943. return SSLVerifierResponse::NoDecisionMade;
  10944. });
  10945. auto res = cli.Get("/test");
  10946. EXPECT_FALSE(res);
  10947. }
  10948. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10949. // Test SSL server using PemMemory constructor with client CA certificates
  10950. // Read PEM files
  10951. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10952. read_file(SERVER_CERT_FILE, server_cert_pem);
  10953. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10954. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10955. // Create SSLServer with PemMemory constructor including client CA
  10956. SSLServer::PemMemory server_pem = {
  10957. server_cert_pem.c_str(),
  10958. server_cert_pem.size(),
  10959. server_key_pem.c_str(),
  10960. server_key_pem.size(),
  10961. client_ca_pem.c_str(),
  10962. client_ca_pem.size(),
  10963. nullptr // no password for server key
  10964. };
  10965. SSLServer svr(server_pem);
  10966. ASSERT_TRUE(svr.is_valid());
  10967. // No SSL error should be recorded for valid setup
  10968. EXPECT_EQ(0, svr.ssl_last_error());
  10969. // Set up server endpoints
  10970. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10971. res.set_content("ok", "text/plain");
  10972. });
  10973. // Start server in a thread
  10974. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10975. svr.wait_until_ready();
  10976. // Connect with client certificate (using constructor with paths)
  10977. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10978. cli.enable_server_certificate_verification(false);
  10979. auto res = cli.Get("/test-pem-ca");
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ(200, res->status);
  10982. EXPECT_EQ("ok", res->body);
  10983. svr.stop();
  10984. server_thread.join();
  10985. }
  10986. #endif
  10987. #ifdef _WIN32
  10988. TEST(CleanupTest, WSACleanup) {
  10989. int ret = WSACleanup();
  10990. ASSERT_EQ(0, ret);
  10991. }
  10992. #endif
  10993. #ifndef CPPHTTPLIB_SSL_ENABLED
  10994. TEST(NoSSLSupport, SimpleInterface) {
  10995. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10996. }
  10997. #endif
  10998. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10999. TEST(InvalidScheme, SimpleInterface) {
  11000. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11001. }
  11002. #endif
  11003. TEST(NoScheme, SimpleInterface) {
  11004. Client cli("yahoo.com:80");
  11005. ASSERT_TRUE(cli.is_valid());
  11006. }
  11007. TEST(SendAPI, SimpleInterface_Online) {
  11008. Client cli("http://yahoo.com");
  11009. Request req;
  11010. req.method = "GET";
  11011. req.path = "/";
  11012. auto res = cli.send(req);
  11013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11014. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11015. }
  11016. TEST(SendAPI, WithParamsInRequest) {
  11017. Server svr;
  11018. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11019. EXPECT_TRUE(req.has_param("test"));
  11020. EXPECT_EQ("test_value", req.get_param_value("test"));
  11021. });
  11022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11023. auto se = detail::scope_exit([&] {
  11024. svr.stop();
  11025. t.join();
  11026. ASSERT_FALSE(svr.is_running());
  11027. });
  11028. svr.wait_until_ready();
  11029. Client cli(HOST, PORT);
  11030. {
  11031. Request req;
  11032. req.method = "GET";
  11033. req.path = "/";
  11034. req.params.emplace("test", "test_value");
  11035. auto res = cli.send(req);
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. }
  11038. {
  11039. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11041. }
  11042. }
  11043. TEST(ClientImplMethods, GetSocketTest) {
  11044. httplib::Server svr;
  11045. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11046. res.status = StatusCode::OK_200;
  11047. });
  11048. auto port = svr.bind_to_any_port("127.0.0.1");
  11049. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. thread.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. {
  11057. httplib::Client cli("127.0.0.1", port);
  11058. cli.set_keep_alive(true);
  11059. // Use the behavior of cpp-httplib of opening the connection
  11060. // only when the first request happens. If that changes,
  11061. // this test would be obsolete.
  11062. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11063. // This also implicitly tests the server. But other tests would fail much
  11064. // earlier than this one to be considered.
  11065. auto res = cli.Get("/");
  11066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11069. }
  11070. }
  11071. #ifdef CPPHTTPLIB_SSL_ENABLED
  11072. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11073. Client cli("http://yahoo.com");
  11074. auto res = cli.Get("/");
  11075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11076. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11077. cli.set_follow_location(true);
  11078. res = cli.Get("/");
  11079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11080. EXPECT_EQ(StatusCode::OK_200, res->status);
  11081. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11082. }
  11083. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11084. Client cli("https://yahoo.com");
  11085. auto res = cli.Get("/");
  11086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11087. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11088. cli.set_follow_location(true);
  11089. res = cli.Get("/");
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11093. }
  11094. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11095. Client cli("https://yahoo.com");
  11096. auto res = cli.Get("/");
  11097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11098. ASSERT_FALSE(!res);
  11099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11100. ASSERT_FALSE(res == nullptr);
  11101. ASSERT_TRUE(res != nullptr);
  11102. EXPECT_EQ(Error::Success, res.error());
  11103. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11104. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11105. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11106. cli.set_follow_location(true);
  11107. res = cli.Get("/");
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. EXPECT_EQ(Error::Success, res.error());
  11110. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11111. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11112. EXPECT_EQ(StatusCode::OK_200, res->status);
  11113. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11114. }
  11115. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11116. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11117. Client cli("https://cdnjs.cloudflare.com");
  11118. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11119. Headers{{"Accept-Encoding", "br"}});
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(StatusCode::OK_200, res->status);
  11122. EXPECT_EQ(287630U, res->body.size());
  11123. EXPECT_EQ("application/javascript; charset=utf-8",
  11124. res->get_header_value("Content-Type"));
  11125. }
  11126. #endif
  11127. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11128. #undef REDIR_HOST // Silence compiler warning
  11129. #define REDIR_HOST "https://httpbingo.org"
  11130. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11131. Client cli(REDIR_HOST);
  11132. cli.set_follow_location(true);
  11133. auto res =
  11134. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11136. EXPECT_EQ(StatusCode::OK_200, res->status);
  11137. }
  11138. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11139. Client cli(REDIR_HOST);
  11140. cli.set_follow_location(true);
  11141. Params params;
  11142. params.emplace("url", "http://example.com");
  11143. params.emplace("status_code", "302");
  11144. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11146. EXPECT_EQ(StatusCode::OK_200, res->status);
  11147. }
  11148. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11149. Client cli(REDIR_HOST);
  11150. cli.set_follow_location(true);
  11151. Params params;
  11152. params.emplace("url", "http://example.com");
  11153. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. }
  11157. TEST(HttpToHttpsRedirectTest, CertFile) {
  11158. auto ssl_port = PORT + 1;
  11159. Server svr;
  11160. ASSERT_TRUE(svr.is_valid());
  11161. svr.Get("/index", [&](const Request &, Response &res) {
  11162. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11163. "/index");
  11164. svr.stop();
  11165. });
  11166. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11167. ASSERT_TRUE(ssl_svr.is_valid());
  11168. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11169. res.set_content("test", "text/plain");
  11170. ssl_svr.stop();
  11171. });
  11172. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11173. thread t2 =
  11174. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11175. auto se = detail::scope_exit([&] {
  11176. t2.join();
  11177. t.join();
  11178. ASSERT_FALSE(svr.is_running());
  11179. });
  11180. svr.wait_until_ready();
  11181. ssl_svr.wait_until_ready();
  11182. Client cli("127.0.0.1", PORT);
  11183. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11184. cli.enable_server_certificate_verification(true);
  11185. cli.set_follow_location(true);
  11186. cli.set_connection_timeout(30);
  11187. auto res = cli.Get("/index");
  11188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11189. ASSERT_EQ(StatusCode::OK_200, res->status);
  11190. }
  11191. TEST(SSLClientRedirectTest, CertFile) {
  11192. auto ssl_port = PORT + 1;
  11193. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11194. ASSERT_TRUE(ssl_svr1.is_valid());
  11195. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11196. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11197. "/index");
  11198. ssl_svr1.stop();
  11199. });
  11200. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11201. ASSERT_TRUE(ssl_svr2.is_valid());
  11202. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11203. res.set_content("test", "text/plain");
  11204. ssl_svr2.stop();
  11205. });
  11206. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11207. thread t2 =
  11208. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11209. auto se = detail::scope_exit([&] {
  11210. t2.join();
  11211. t.join();
  11212. ASSERT_FALSE(ssl_svr1.is_running());
  11213. });
  11214. ssl_svr1.wait_until_ready();
  11215. ssl_svr2.wait_until_ready();
  11216. SSLClient cli("127.0.0.1", PORT);
  11217. std::string cert;
  11218. read_file(SERVER_CERT2_FILE, cert);
  11219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11220. cli.enable_server_certificate_verification(true);
  11221. cli.set_follow_location(true);
  11222. cli.set_connection_timeout(30);
  11223. auto res = cli.Get("/index");
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. ASSERT_EQ(StatusCode::OK_200, res->status);
  11226. }
  11227. #endif
  11228. #ifdef CPPHTTPLIB_SSL_ENABLED
  11229. // Test that set_ca_cert_store() skips system certs (consistent with
  11230. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11231. // should be trusted - system certs should NOT be loaded.
  11232. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11233. // Load a specific cert that is NOT a system CA cert
  11234. std::string cert;
  11235. read_file(SERVER_CERT2_FILE, cert);
  11236. SSLClient cli("google.com");
  11237. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11238. cli.enable_server_certificate_verification(true);
  11239. // This should FAIL because:
  11240. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11241. // 2. System certs should NOT be loaded when custom store is set
  11242. // If system certs WERE loaded, this would succeed
  11243. auto res = cli.Get("/");
  11244. ASSERT_FALSE(res);
  11245. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11246. }
  11247. // Same as above, but through the native store handle path. Regression test:
  11248. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11249. // merged system certs into the user-provided store.
  11250. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11251. std::string cert;
  11252. read_file(SERVER_CERT2_FILE, cert);
  11253. SSLClient cli("google.com");
  11254. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11255. cli.enable_server_certificate_verification(true);
  11256. auto res = cli.Get("/");
  11257. ASSERT_FALSE(res);
  11258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11259. }
  11260. // A custom store set via the native handle must still verify a server whose
  11261. // cert it does contain.
  11262. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11263. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11264. ASSERT_TRUE(svr.is_valid());
  11265. svr.Get("/test", [&](const Request &, Response &res) {
  11266. res.set_content("test", "text/plain");
  11267. });
  11268. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11269. auto se = detail::scope_exit([&] {
  11270. svr.stop();
  11271. t.join();
  11272. ASSERT_FALSE(svr.is_running());
  11273. });
  11274. svr.wait_until_ready();
  11275. SSLClient cli("127.0.0.1", PORT);
  11276. std::string cert;
  11277. read_file(SERVER_CERT2_FILE, cert);
  11278. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11279. cli.enable_server_certificate_verification(true);
  11280. cli.set_connection_timeout(30);
  11281. auto res = cli.Get("/test");
  11282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11283. ASSERT_EQ(StatusCode::OK_200, res->status);
  11284. }
  11285. // CA certs loaded through the universal Client must be transferred to the
  11286. // client created internally for following an HTTPS redirect. Regression test:
  11287. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11288. // the CA data for redirect transfer.
  11289. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11290. auto ssl_port = PORT + 1;
  11291. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11292. ASSERT_TRUE(ssl_svr1.is_valid());
  11293. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11294. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11295. "/index");
  11296. });
  11297. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11298. ASSERT_TRUE(ssl_svr2.is_valid());
  11299. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11300. res.set_content("test", "text/plain");
  11301. });
  11302. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11303. thread t2 =
  11304. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11305. auto se = detail::scope_exit([&] {
  11306. ssl_svr2.stop();
  11307. ssl_svr1.stop();
  11308. t2.join();
  11309. t.join();
  11310. ASSERT_FALSE(ssl_svr1.is_running());
  11311. });
  11312. ssl_svr1.wait_until_ready();
  11313. ssl_svr2.wait_until_ready();
  11314. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11315. std::string cert;
  11316. read_file(SERVER_CERT2_FILE, cert);
  11317. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11318. cli.enable_server_certificate_verification(true);
  11319. cli.set_follow_location(true);
  11320. cli.set_connection_timeout(30);
  11321. auto res = cli.Get("/index");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. ASSERT_EQ(StatusCode::OK_200, res->status);
  11324. }
  11325. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11326. // so a host signed by a system CA verifies even though a custom CA is set
  11327. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11328. std::string cert;
  11329. read_file(SERVER_CERT2_FILE, cert);
  11330. SSLClient cli("google.com");
  11331. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11332. cli.enable_system_ca(true);
  11333. cli.enable_server_certificate_verification(true);
  11334. auto res = cli.Get("/");
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11337. }
  11338. // The custom CA remains effective when combined with the system CA
  11339. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11340. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11341. ASSERT_TRUE(svr.is_valid());
  11342. svr.Get("/test", [&](const Request &, Response &res) {
  11343. res.set_content("test", "text/plain");
  11344. });
  11345. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11346. auto se = detail::scope_exit([&] {
  11347. svr.stop();
  11348. t.join();
  11349. ASSERT_FALSE(svr.is_running());
  11350. });
  11351. svr.wait_until_ready();
  11352. SSLClient cli("127.0.0.1", PORT);
  11353. std::string cert;
  11354. read_file(SERVER_CERT2_FILE, cert);
  11355. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11356. cli.enable_system_ca(true);
  11357. cli.enable_server_certificate_verification(true);
  11358. cli.set_connection_timeout(30);
  11359. auto res = cli.Get("/test");
  11360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11361. ASSERT_EQ(StatusCode::OK_200, res->status);
  11362. }
  11363. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11364. // skip chain verification entirely (only the certificate identity was
  11365. // checked), so a server presenting an untrusted certificate with a matching
  11366. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11367. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11368. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11369. ASSERT_TRUE(svr.is_valid());
  11370. svr.Get("/test", [&](const Request &, Response &res) {
  11371. res.set_content("test", "text/plain");
  11372. });
  11373. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11374. auto se = detail::scope_exit([&] {
  11375. svr.stop();
  11376. t.join();
  11377. ASSERT_FALSE(svr.is_running());
  11378. });
  11379. svr.wait_until_ready();
  11380. SSLClient cli("127.0.0.1", PORT);
  11381. std::string cert;
  11382. // A trusted CA that did not sign the server certificate. The server cert
  11383. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11384. // this connection.
  11385. read_file(CLIENT_CA_CERT_FILE, cert);
  11386. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11387. cli.enable_server_certificate_verification(true);
  11388. cli.set_connection_timeout(30);
  11389. auto res = cli.Get("/test");
  11390. ASSERT_FALSE(res);
  11391. }
  11392. // enable_system_ca(false) prevents system CA loading entirely
  11393. TEST(SSLClientTest, DisableSystemCa_Online) {
  11394. SSLClient cli("google.com");
  11395. cli.enable_system_ca(false);
  11396. cli.enable_server_certificate_verification(true);
  11397. auto res = cli.Get("/");
  11398. ASSERT_FALSE(res);
  11399. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11400. // itself when the CA chain is empty
  11401. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11402. res.error() == Error::SSLConnection);
  11403. }
  11404. // The universal Client forwards enable_system_ca()
  11405. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11406. std::string cert;
  11407. read_file(SERVER_CERT2_FILE, cert);
  11408. Client cli("https://google.com");
  11409. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11410. cli.enable_system_ca(true);
  11411. cli.enable_server_certificate_verification(true);
  11412. auto res = cli.Get("/");
  11413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11414. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11415. }
  11416. // The system CA policy must carry over to the client created internally for
  11417. // following a cross-host HTTPS redirect
  11418. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11419. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11420. ASSERT_TRUE(svr.is_valid());
  11421. svr.Get("/index", [&](const Request &, Response &res) {
  11422. res.set_redirect("https://www.google.com/");
  11423. });
  11424. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11425. auto se = detail::scope_exit([&] {
  11426. svr.stop();
  11427. t.join();
  11428. ASSERT_FALSE(svr.is_running());
  11429. });
  11430. svr.wait_until_ready();
  11431. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11432. std::string cert;
  11433. read_file(SERVER_CERT2_FILE, cert);
  11434. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11435. cli.enable_system_ca(true);
  11436. cli.enable_server_certificate_verification(true);
  11437. cli.set_follow_location(true);
  11438. cli.set_connection_timeout(30);
  11439. // Receiving any response proves the redirect client completed the TLS
  11440. // handshake with a system-CA-signed host
  11441. auto res = cli.Get("/index");
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. }
  11444. TEST(MultipartFormDataTest, LargeData) {
  11445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11446. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11447. const ContentReader &content_reader) {
  11448. if (req.is_multipart_form_data()) {
  11449. std::vector<FormData> items;
  11450. content_reader(
  11451. [&](const FormData &file) {
  11452. items.push_back(file);
  11453. return true;
  11454. },
  11455. [&](const char *data, size_t data_length) {
  11456. items.back().content.append(data, data_length);
  11457. return true;
  11458. });
  11459. EXPECT_TRUE(std::string(items[0].name) == "document");
  11460. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11461. EXPECT_TRUE(items[0].filename == "2MB_data");
  11462. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11463. EXPECT_TRUE(items[1].name == "hello");
  11464. EXPECT_TRUE(items[1].content == "world");
  11465. EXPECT_TRUE(items[1].filename == "");
  11466. EXPECT_TRUE(items[1].content_type == "");
  11467. } else {
  11468. std::string body;
  11469. content_reader([&](const char *data, size_t data_length) {
  11470. body.append(data, data_length);
  11471. return true;
  11472. });
  11473. }
  11474. });
  11475. auto port = svr.bind_to_any_port(HOST);
  11476. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11477. auto se = detail::scope_exit([&] {
  11478. svr.stop();
  11479. t.join();
  11480. ASSERT_FALSE(svr.is_running());
  11481. });
  11482. svr.wait_until_ready();
  11483. {
  11484. std::string data(1024 * 1024 * 2, '.');
  11485. std::stringstream buffer;
  11486. buffer << data;
  11487. SSLClient cli(HOST, port);
  11488. cli.enable_server_certificate_verification(false);
  11489. UploadFormDataItems items{
  11490. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11491. {"hello", "world", "", ""},
  11492. };
  11493. auto res = cli.Post("/post", items);
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. ASSERT_EQ(StatusCode::OK_200, res->status);
  11496. }
  11497. }
  11498. TEST(MultipartFormDataTest, DataProviderItems) {
  11499. std::random_device seed_gen;
  11500. std::mt19937 random(seed_gen());
  11501. std::string rand1;
  11502. rand1.resize(1000);
  11503. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11504. std::string rand2;
  11505. rand2.resize(3000);
  11506. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11508. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11509. const ContentReader &content_reader) {
  11510. ASSERT_FALSE(req.is_multipart_form_data());
  11511. std::string body;
  11512. content_reader([&](const char *data, size_t data_length) {
  11513. body.append(data, data_length);
  11514. return true;
  11515. });
  11516. EXPECT_EQ(body, "");
  11517. });
  11518. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11519. const ContentReader &content_reader) {
  11520. ASSERT_TRUE(req.is_multipart_form_data());
  11521. std::vector<FormData> items;
  11522. content_reader(
  11523. [&](const FormData &file) {
  11524. items.push_back(file);
  11525. return true;
  11526. },
  11527. [&](const char *data, size_t data_length) {
  11528. items.back().content.append(data, data_length);
  11529. return true;
  11530. });
  11531. ASSERT_TRUE(items.size() == 2);
  11532. EXPECT_EQ(std::string(items[0].name), "name1");
  11533. EXPECT_EQ(items[0].content, "Testing123");
  11534. EXPECT_EQ(items[0].filename, "filename1");
  11535. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11536. EXPECT_EQ(items[1].name, "name2");
  11537. EXPECT_EQ(items[1].content, "Testing456");
  11538. EXPECT_EQ(items[1].filename, "");
  11539. EXPECT_EQ(items[1].content_type, "");
  11540. });
  11541. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11542. const ContentReader &content_reader) {
  11543. ASSERT_TRUE(req.is_multipart_form_data());
  11544. std::vector<FormData> items;
  11545. content_reader(
  11546. [&](const FormData &file) {
  11547. items.push_back(file);
  11548. return true;
  11549. },
  11550. [&](const char *data, size_t data_length) {
  11551. items.back().content.append(data, data_length);
  11552. return true;
  11553. });
  11554. ASSERT_TRUE(items.size() == 2);
  11555. EXPECT_EQ(items[0].name, "name3");
  11556. EXPECT_EQ(items[0].content, rand1);
  11557. EXPECT_EQ(items[0].filename, "filename3");
  11558. EXPECT_EQ(items[0].content_type, "");
  11559. EXPECT_EQ(items[1].name, "name4");
  11560. EXPECT_EQ(items[1].content, rand2);
  11561. EXPECT_EQ(items[1].filename, "filename4");
  11562. EXPECT_EQ(items[1].content_type, "");
  11563. });
  11564. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11565. const ContentReader &content_reader) {
  11566. ASSERT_TRUE(req.is_multipart_form_data());
  11567. std::vector<FormData> items;
  11568. content_reader(
  11569. [&](const FormData &file) {
  11570. items.push_back(file);
  11571. return true;
  11572. },
  11573. [&](const char *data, size_t data_length) {
  11574. items.back().content.append(data, data_length);
  11575. return true;
  11576. });
  11577. ASSERT_TRUE(items.size() == 4);
  11578. EXPECT_EQ(std::string(items[0].name), "name1");
  11579. EXPECT_EQ(items[0].content, "Testing123");
  11580. EXPECT_EQ(items[0].filename, "filename1");
  11581. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11582. EXPECT_EQ(items[1].name, "name2");
  11583. EXPECT_EQ(items[1].content, "Testing456");
  11584. EXPECT_EQ(items[1].filename, "");
  11585. EXPECT_EQ(items[1].content_type, "");
  11586. EXPECT_EQ(items[2].name, "name3");
  11587. EXPECT_EQ(items[2].content, rand1);
  11588. EXPECT_EQ(items[2].filename, "filename3");
  11589. EXPECT_EQ(items[2].content_type, "");
  11590. EXPECT_EQ(items[3].name, "name4");
  11591. EXPECT_EQ(items[3].content, rand2);
  11592. EXPECT_EQ(items[3].filename, "filename4");
  11593. EXPECT_EQ(items[3].content_type, "");
  11594. });
  11595. auto port = svr.bind_to_any_port("localhost");
  11596. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11597. auto se = detail::scope_exit([&] {
  11598. svr.stop();
  11599. t.join();
  11600. ASSERT_FALSE(svr.is_running());
  11601. });
  11602. svr.wait_until_ready();
  11603. {
  11604. SSLClient cli("localhost", port);
  11605. cli.enable_server_certificate_verification(false);
  11606. UploadFormDataItems items{
  11607. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11608. {"name2", "Testing456", "", ""}, // not a file
  11609. };
  11610. {
  11611. auto res = cli.Post("/post-none", {}, {}, {});
  11612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11613. ASSERT_EQ(StatusCode::OK_200, res->status);
  11614. }
  11615. FormDataProviderItems providers;
  11616. {
  11617. auto res =
  11618. cli.Post("/post-items", {}, items, providers); // empty providers
  11619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11620. ASSERT_EQ(StatusCode::OK_200, res->status);
  11621. }
  11622. providers.push_back({"name3",
  11623. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11624. // test the offset is given correctly at each step
  11625. if (!offset)
  11626. sink.os.write(rand1.data(), 30);
  11627. else if (offset == 30)
  11628. sink.os.write(rand1.data() + 30, 300);
  11629. else if (offset == 330)
  11630. sink.os.write(rand1.data() + 330, 670);
  11631. else if (offset == rand1.size())
  11632. sink.done();
  11633. return true;
  11634. },
  11635. "filename3",
  11636. {}});
  11637. providers.push_back({"name4",
  11638. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11639. // test the offset is given correctly at each step
  11640. if (!offset)
  11641. sink.os.write(rand2.data(), 2000);
  11642. else if (offset == 2000)
  11643. sink.os.write(rand2.data() + 2000, 1);
  11644. else if (offset == 2001)
  11645. sink.os.write(rand2.data() + 2001, 999);
  11646. else if (offset == rand2.size())
  11647. sink.done();
  11648. return true;
  11649. },
  11650. "filename4",
  11651. {}});
  11652. {
  11653. auto res = cli.Post("/post-providers", {}, {}, providers);
  11654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11655. ASSERT_EQ(StatusCode::OK_200, res->status);
  11656. }
  11657. {
  11658. auto res = cli.Post("/post-both", {}, items, providers);
  11659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11660. ASSERT_EQ(StatusCode::OK_200, res->status);
  11661. }
  11662. }
  11663. }
  11664. TEST(MultipartFormDataTest, BadHeader) {
  11665. Server svr;
  11666. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11667. res.set_content("ok", "text/plain");
  11668. });
  11669. thread t = thread([&] { svr.listen(HOST, PORT); });
  11670. auto se = detail::scope_exit([&] {
  11671. svr.stop();
  11672. t.join();
  11673. ASSERT_FALSE(svr.is_running());
  11674. });
  11675. svr.wait_until_ready();
  11676. const std::string body =
  11677. "This is the preamble. It is to be ignored, though it\r\n"
  11678. "is a handy place for composition agents to include an\r\n"
  11679. "explanatory note to non-MIME conformant readers.\r\n"
  11680. "\r\n"
  11681. "\r\n"
  11682. "--simple boundary\r\n"
  11683. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11684. ": BAD...\r\n"
  11685. "\r\n"
  11686. "value1\r\n"
  11687. "--simple boundary\r\n"
  11688. "Content-Disposition: form-data; name=\"field2\"; "
  11689. "filename=\"example.txt\"\r\n"
  11690. "\r\n"
  11691. "value2\r\n"
  11692. "--simple boundary--\r\n"
  11693. "This is the epilogue. It is also to be ignored.\r\n";
  11694. std::string content_type =
  11695. R"(multipart/form-data; boundary="simple boundary")";
  11696. Client cli(HOST, PORT);
  11697. auto res = cli.Post("/post", body, content_type.c_str());
  11698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11699. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11700. }
  11701. TEST(MultipartFormDataTest, WithPreamble) {
  11702. Server svr;
  11703. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11704. res.set_content("ok", "text/plain");
  11705. });
  11706. thread t = thread([&] { svr.listen(HOST, PORT); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. t.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. const std::string body =
  11714. "This is the preamble. It is to be ignored, though it\r\n"
  11715. "is a handy place for composition agents to include an\r\n"
  11716. "explanatory note to non-MIME conformant readers.\r\n"
  11717. "\r\n"
  11718. "\r\n"
  11719. "--simple boundary\r\n"
  11720. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11721. "\r\n"
  11722. "value1\r\n"
  11723. "--simple boundary\r\n"
  11724. "Content-Disposition: form-data; name=\"field2\"; "
  11725. "filename=\"example.txt\"\r\n"
  11726. "\r\n"
  11727. "value2\r\n"
  11728. "--simple boundary--\r\n"
  11729. "This is the epilogue. It is also to be ignored.\r\n";
  11730. std::string content_type =
  11731. R"(multipart/form-data; boundary="simple boundary")";
  11732. Client cli(HOST, PORT);
  11733. auto res = cli.Post("/post", body, content_type.c_str());
  11734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11735. EXPECT_EQ(StatusCode::OK_200, res->status);
  11736. }
  11737. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11739. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11740. const ContentReader &content_reader) {
  11741. if (req.is_multipart_form_data()) {
  11742. std::vector<FormData> items;
  11743. content_reader(
  11744. [&](const FormData &file) {
  11745. items.push_back(file);
  11746. return true;
  11747. },
  11748. [&](const char *data, size_t data_length) {
  11749. items.back().content.append(data, data_length);
  11750. return true;
  11751. });
  11752. EXPECT_TRUE(std::string(items[0].name) == "document");
  11753. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11754. EXPECT_TRUE(items[0].filename == "2MB_data");
  11755. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11756. EXPECT_TRUE(items[1].name == "hello");
  11757. EXPECT_TRUE(items[1].content == "world");
  11758. EXPECT_TRUE(items[1].filename == "");
  11759. EXPECT_TRUE(items[1].content_type == "");
  11760. } else {
  11761. std::string body;
  11762. content_reader([&](const char *data, size_t data_length) {
  11763. body.append(data, data_length);
  11764. return true;
  11765. });
  11766. }
  11767. });
  11768. auto port = svr.bind_to_any_port("localhost");
  11769. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11770. auto se = detail::scope_exit([&] {
  11771. svr.stop();
  11772. t.join();
  11773. ASSERT_FALSE(svr.is_running());
  11774. });
  11775. svr.wait_until_ready();
  11776. {
  11777. std::string data(1024 * 1024 * 2, '.');
  11778. std::stringstream buffer;
  11779. buffer << data;
  11780. SSLClient cli("localhost", port);
  11781. cli.enable_server_certificate_verification(false);
  11782. UploadFormDataItems items{
  11783. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11784. {"hello", "world", "", ""},
  11785. };
  11786. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11788. ASSERT_EQ(StatusCode::OK_200, res->status);
  11789. }
  11790. }
  11791. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11792. std::string data(1024 * 1024 * 2, '&');
  11793. std::stringstream buffer;
  11794. buffer << data;
  11795. Client cli("https://localhost:8080");
  11796. UploadFormDataItems items{
  11797. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11798. {"hello", "world", "", ""},
  11799. };
  11800. for (const char &c : " \t\r\n") {
  11801. auto res =
  11802. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11803. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11804. ASSERT_FALSE(res);
  11805. }
  11806. }
  11807. TEST(MultipartFormDataTest, PutFormData) {
  11808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11809. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11810. const ContentReader &content_reader) {
  11811. if (req.is_multipart_form_data()) {
  11812. std::vector<FormData> items;
  11813. content_reader(
  11814. [&](const FormData &file) {
  11815. items.push_back(file);
  11816. return true;
  11817. },
  11818. [&](const char *data, size_t data_length) {
  11819. items.back().content.append(data, data_length);
  11820. return true;
  11821. });
  11822. EXPECT_TRUE(std::string(items[0].name) == "document");
  11823. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11824. EXPECT_TRUE(items[0].filename == "2MB_data");
  11825. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11826. EXPECT_TRUE(items[1].name == "hello");
  11827. EXPECT_TRUE(items[1].content == "world");
  11828. EXPECT_TRUE(items[1].filename == "");
  11829. EXPECT_TRUE(items[1].content_type == "");
  11830. } else {
  11831. std::string body;
  11832. content_reader([&](const char *data, size_t data_length) {
  11833. body.append(data, data_length);
  11834. return true;
  11835. });
  11836. }
  11837. });
  11838. auto port = svr.bind_to_any_port("localhost");
  11839. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11840. auto se = detail::scope_exit([&] {
  11841. svr.stop();
  11842. t.join();
  11843. ASSERT_FALSE(svr.is_running());
  11844. });
  11845. svr.wait_until_ready();
  11846. {
  11847. std::string data(1024 * 1024 * 2, '&');
  11848. std::stringstream buffer;
  11849. buffer << data;
  11850. SSLClient cli("localhost", port);
  11851. cli.enable_server_certificate_verification(false);
  11852. UploadFormDataItems items{
  11853. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11854. {"hello", "world", "", ""},
  11855. };
  11856. auto res = cli.Put("/put", items);
  11857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11858. ASSERT_EQ(StatusCode::OK_200, res->status);
  11859. }
  11860. }
  11861. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11863. svr.Put("/put_customboundary",
  11864. [&](const Request &req, const Response & /*res*/,
  11865. const ContentReader &content_reader) {
  11866. if (req.is_multipart_form_data()) {
  11867. std::vector<FormData> items;
  11868. content_reader(
  11869. [&](const FormData &file) {
  11870. items.push_back(file);
  11871. return true;
  11872. },
  11873. [&](const char *data, size_t data_length) {
  11874. items.back().content.append(data, data_length);
  11875. return true;
  11876. });
  11877. EXPECT_TRUE(std::string(items[0].name) == "document");
  11878. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11879. EXPECT_TRUE(items[0].filename == "2MB_data");
  11880. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11881. EXPECT_TRUE(items[1].name == "hello");
  11882. EXPECT_TRUE(items[1].content == "world");
  11883. EXPECT_TRUE(items[1].filename == "");
  11884. EXPECT_TRUE(items[1].content_type == "");
  11885. } else {
  11886. std::string body;
  11887. content_reader([&](const char *data, size_t data_length) {
  11888. body.append(data, data_length);
  11889. return true;
  11890. });
  11891. }
  11892. });
  11893. auto port = svr.bind_to_any_port("localhost");
  11894. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11895. auto se = detail::scope_exit([&] {
  11896. svr.stop();
  11897. t.join();
  11898. ASSERT_FALSE(svr.is_running());
  11899. });
  11900. svr.wait_until_ready();
  11901. {
  11902. std::string data(1024 * 1024 * 2, '&');
  11903. std::stringstream buffer;
  11904. buffer << data;
  11905. SSLClient cli("localhost", port);
  11906. cli.enable_server_certificate_verification(false);
  11907. UploadFormDataItems items{
  11908. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11909. {"hello", "world", "", ""},
  11910. };
  11911. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. ASSERT_EQ(StatusCode::OK_200, res->status);
  11914. }
  11915. }
  11916. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11917. std::string data(1024 * 1024 * 2, '&');
  11918. std::stringstream buffer;
  11919. buffer << data;
  11920. Client cli("https://localhost:8080");
  11921. cli.enable_server_certificate_verification(false);
  11922. UploadFormDataItems items{
  11923. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11924. {"hello", "world", "", ""},
  11925. };
  11926. for (const char &c : " \t\r\n") {
  11927. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11928. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11929. ASSERT_FALSE(res);
  11930. }
  11931. }
  11932. TEST(MultipartFormDataTest, AlternateFilename) {
  11933. auto handled = false;
  11934. Server svr;
  11935. svr.Post("/test", [&](const Request &req, Response &res) {
  11936. ASSERT_EQ(2u, req.form.files.size());
  11937. ASSERT_EQ(1u, req.form.fields.size());
  11938. // Test files
  11939. const auto &file1 = req.form.get_file("file1");
  11940. ASSERT_EQ("file1", file1.name);
  11941. ASSERT_EQ("A.txt", file1.filename);
  11942. ASSERT_EQ("text/plain", file1.content_type);
  11943. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11944. const auto &file2 = req.form.get_file("file2");
  11945. ASSERT_EQ("file2", file2.name);
  11946. ASSERT_EQ("a.html", file2.filename);
  11947. ASSERT_EQ("text/html", file2.content_type);
  11948. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11949. file2.content);
  11950. // Test text field
  11951. const auto &text = req.form.get_field("text");
  11952. ASSERT_EQ("text default", text);
  11953. res.set_content("ok", "text/plain");
  11954. handled = true;
  11955. });
  11956. thread t = thread([&] { svr.listen(HOST, PORT); });
  11957. auto se = detail::scope_exit([&] {
  11958. svr.stop();
  11959. t.join();
  11960. ASSERT_FALSE(svr.is_running());
  11961. ASSERT_TRUE(handled);
  11962. });
  11963. svr.wait_until_ready();
  11964. auto req = "POST /test HTTP/1.1\r\n"
  11965. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11966. "Content-Length: 399\r\n"
  11967. "\r\n"
  11968. "----------\r\n"
  11969. "Content-Disposition: form-data; name=\"text\"\r\n"
  11970. "\r\n"
  11971. "text default\r\n"
  11972. "----------\r\n"
  11973. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11974. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11975. "Content-Type: text/plain\r\n"
  11976. "\r\n"
  11977. "Content of a.txt.\r\n"
  11978. "\r\n"
  11979. "----------\r\n"
  11980. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11981. "\"a.html\"\r\n"
  11982. "Content-Type: text/html\r\n"
  11983. "\r\n"
  11984. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11985. "\r\n"
  11986. "------------\r\n";
  11987. ASSERT_TRUE(send_request(1, req));
  11988. }
  11989. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11990. auto handled = false;
  11991. Server svr;
  11992. svr.Post("/test", [&](const Request &req, Response &res) {
  11993. // Case-insensitive "utf-8''" prefix with a long value
  11994. const auto &file = req.form.get_file("file1");
  11995. ASSERT_EQ("file1", file.name);
  11996. // 8000 chars exercises both the Content-Disposition parser and the
  11997. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11998. // Prior to the fix, std::regex_match on this header would cause O(N)
  11999. // stack recursion in libstdc++, leading to SIGSEGV.
  12000. std::string expected_filename(8000, 'A');
  12001. ASSERT_EQ(expected_filename, file.filename);
  12002. res.set_content("ok", "text/plain");
  12003. handled = true;
  12004. });
  12005. thread t = thread([&] { svr.listen(HOST, PORT); });
  12006. auto se = detail::scope_exit([&] {
  12007. svr.stop();
  12008. t.join();
  12009. ASSERT_FALSE(svr.is_running());
  12010. ASSERT_TRUE(handled);
  12011. });
  12012. svr.wait_until_ready();
  12013. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12014. // Regression test for GHSA-qq6v-r583-3h69
  12015. std::string long_filename(8000, 'A');
  12016. std::string body = "----------\r\n"
  12017. "Content-Disposition: form-data; name=\"file1\"; "
  12018. "filename*=\"Utf-8''" +
  12019. long_filename +
  12020. "\"\r\n"
  12021. "\r\n"
  12022. "hello\r\n"
  12023. "------------\r\n";
  12024. auto req = "POST /test HTTP/1.1\r\n"
  12025. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12026. "Content-Length: " +
  12027. std::to_string(body.size()) + "\r\n\r\n" + body;
  12028. ASSERT_TRUE(send_request(1, req));
  12029. }
  12030. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12031. auto handled = false;
  12032. Server svr;
  12033. svr.Post("/test", [&](const Request &req, Response &) {
  12034. ASSERT_EQ(2u, req.form.fields.size());
  12035. const auto &text1 = req.form.get_field("text1");
  12036. ASSERT_EQ("text1", text1);
  12037. const auto &text2 = req.form.get_field("text2");
  12038. ASSERT_EQ("text2", text2);
  12039. handled = true;
  12040. });
  12041. thread t = thread([&] { svr.listen(HOST, PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. t.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. ASSERT_TRUE(handled);
  12047. });
  12048. svr.wait_until_ready();
  12049. auto req = "POST /test HTTP/1.1\r\n"
  12050. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12051. "Content-Length: 146\r\n"
  12052. "\r\n----------\r\n"
  12053. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12054. "\r\n"
  12055. "text1"
  12056. "\r\n----------\r\n"
  12057. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12058. "\r\n"
  12059. "text2"
  12060. "\r\n------------";
  12061. std::string response;
  12062. ASSERT_TRUE(send_request(1, req, &response));
  12063. ASSERT_EQ("200", response.substr(9, 3));
  12064. }
  12065. TEST(MultipartFormDataTest, ContentLength) {
  12066. auto handled = false;
  12067. Server svr;
  12068. svr.Post("/test", [&](const Request &req, Response &) {
  12069. ASSERT_EQ(2u, req.form.fields.size());
  12070. const auto &text1 = req.form.get_field("text1");
  12071. ASSERT_EQ("text1", text1);
  12072. const auto &text2 = req.form.get_field("text2");
  12073. ASSERT_EQ("text2", text2);
  12074. handled = true;
  12075. });
  12076. thread t = thread([&] { svr.listen(HOST, PORT); });
  12077. auto se = detail::scope_exit([&] {
  12078. svr.stop();
  12079. t.join();
  12080. ASSERT_FALSE(svr.is_running());
  12081. ASSERT_TRUE(handled);
  12082. });
  12083. svr.wait_until_ready();
  12084. auto req = "POST /test HTTP/1.1\r\n"
  12085. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12086. "Content-Length: 167\r\n"
  12087. "\r\n----------\r\n"
  12088. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12089. "Content-Length: 5\r\n"
  12090. "\r\n"
  12091. "text1"
  12092. "\r\n----------\r\n"
  12093. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12094. "\r\n"
  12095. "text2"
  12096. "\r\n------------\r\n";
  12097. std::string response;
  12098. ASSERT_TRUE(send_request(1, req, &response));
  12099. ASSERT_EQ("200", response.substr(9, 3));
  12100. }
  12101. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12102. auto handled = false;
  12103. Server svr;
  12104. svr.Post("/test", [&](const Request &req, Response &) {
  12105. ASSERT_EQ(2u, req.form.fields.size());
  12106. const auto &text1 = req.form.get_field("text1");
  12107. ASSERT_EQ("text1", text1);
  12108. // TODO: Add header access for text fields if needed
  12109. const auto &text2 = req.form.get_field("text2");
  12110. ASSERT_EQ("text2", text2);
  12111. // TODO: Header access for text fields needs to be implemented
  12112. // auto &headers = it->second.headers;
  12113. // ASSERT_EQ(3U, headers.size());
  12114. // auto custom_header = headers.find("x-whatever");
  12115. // ASSERT_TRUE(custom_header != headers.end());
  12116. // ASSERT_NE("customvalue", custom_header->second);
  12117. // ASSERT_EQ("CustomValue", custom_header->second);
  12118. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12119. handled = true;
  12120. });
  12121. thread t = thread([&] { svr.listen(HOST, PORT); });
  12122. auto se = detail::scope_exit([&] {
  12123. svr.stop();
  12124. t.join();
  12125. ASSERT_FALSE(svr.is_running());
  12126. ASSERT_TRUE(handled);
  12127. });
  12128. svr.wait_until_ready();
  12129. auto req = "POST /test HTTP/1.1\r\n"
  12130. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12131. "Content-Length: 232\r\n"
  12132. "\r\n----------\r\n"
  12133. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12134. "Content-Length: 5\r\n"
  12135. "X-Test: 1\r\n"
  12136. "\r\n"
  12137. "text1"
  12138. "\r\n----------\r\n"
  12139. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12140. "Content-Type: text/plain\r\n"
  12141. "X-Whatever: CustomValue\r\n"
  12142. "\r\n"
  12143. "text2"
  12144. "\r\n------------\r\n"
  12145. "That should be disregarded. Not even read";
  12146. std::string response;
  12147. ASSERT_TRUE(send_request(1, req, &response));
  12148. ASSERT_EQ("200", response.substr(9, 3));
  12149. }
  12150. TEST(MultipartFormDataTest, LargeHeader) {
  12151. auto handled = false;
  12152. Server svr;
  12153. svr.Post("/test", [&](const Request &req, Response &) {
  12154. ASSERT_EQ(1u, req.form.fields.size());
  12155. const auto &text = req.form.get_field("name1");
  12156. ASSERT_EQ("text1", text);
  12157. handled = true;
  12158. });
  12159. thread t = thread([&] { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. ASSERT_TRUE(handled);
  12165. });
  12166. svr.wait_until_ready();
  12167. auto boundary = std::string("cpp-httplib-multipart-data");
  12168. std::string content = "--" + boundary +
  12169. "\r\n"
  12170. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12171. "\r\n"
  12172. "text1\r\n"
  12173. "--" +
  12174. boundary + "--\r\n";
  12175. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12176. "Content-Type: multipart/form-data;boundary=" +
  12177. boundary +
  12178. "\r\n"
  12179. "Content-Length: " +
  12180. std::to_string(content.size()) +
  12181. "\r\n"
  12182. "Dummy-Header: ";
  12183. std::string header_suffix = "\r\n"
  12184. "\r\n";
  12185. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12186. size_t header_dummy_size =
  12187. read_buff_size -
  12188. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12189. auto header_dummy = std::string(header_dummy_size, '@');
  12190. auto req = header_prefix + header_dummy + header_suffix + content;
  12191. std::string response;
  12192. ASSERT_TRUE(send_request(1, req, &response));
  12193. ASSERT_EQ("200", response.substr(9, 3));
  12194. }
  12195. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12196. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12197. // (not chunked Transfer-Encoding) after the streaming refactor.
  12198. auto handled = false;
  12199. Server svr;
  12200. svr.Post("/upload", [&](const Request &req, Response &res) {
  12201. auto cl_it = req.headers.find("Content-Length");
  12202. EXPECT_TRUE(cl_it != req.headers.end());
  12203. auto te_it = req.headers.find("Transfer-Encoding");
  12204. EXPECT_TRUE(te_it == req.headers.end());
  12205. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12206. res.set_content("ok", "text/plain");
  12207. handled = true;
  12208. });
  12209. auto port = svr.bind_to_any_port(HOST);
  12210. auto t = thread([&] { svr.listen_after_bind(); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. t.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. ASSERT_TRUE(handled);
  12216. });
  12217. svr.wait_until_ready();
  12218. UploadFormDataItems items = {
  12219. {"field1", "hello", "", "text/plain"},
  12220. {"file1", "world", "test.txt", "application/octet-stream"},
  12221. };
  12222. Client cli(HOST, port);
  12223. auto res = cli.Post("/upload", {}, items);
  12224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12225. EXPECT_EQ(StatusCode::OK_200, res->status);
  12226. }
  12227. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12228. // Verify that make_multipart_content_provider coalesces many small segments
  12229. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12230. constexpr size_t kItemCount = 1000;
  12231. UploadFormDataItems items;
  12232. items.reserve(kItemCount);
  12233. for (size_t i = 0; i < kItemCount; i++) {
  12234. items.push_back(
  12235. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12236. }
  12237. const std::string boundary = "----test-boundary";
  12238. auto content_length = detail::get_multipart_content_length(items, boundary);
  12239. auto provider = detail::make_multipart_content_provider(items, boundary);
  12240. // Drive the provider the same way write_content_with_progress does
  12241. size_t write_count = 0;
  12242. size_t total_bytes = 0;
  12243. DataSink sink;
  12244. size_t offset = 0;
  12245. sink.write = [&](const char *d, size_t l) -> bool {
  12246. (void)d;
  12247. write_count++;
  12248. total_bytes += l;
  12249. offset += l;
  12250. return true;
  12251. };
  12252. sink.is_writable = []() -> bool { return true; };
  12253. while (offset < content_length) {
  12254. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12255. }
  12256. EXPECT_EQ(content_length, total_bytes);
  12257. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12258. // With buffering into 64KB blocks, write_count should be much smaller.
  12259. auto segment_count = 3 * kItemCount + 1;
  12260. EXPECT_LT(write_count, segment_count / 10);
  12261. }
  12262. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12263. // Integration test: send many UploadFormDataItems and verify the server
  12264. // receives all of them correctly (#2410).
  12265. constexpr size_t kItemCount = 500;
  12266. auto handled = false;
  12267. Server svr;
  12268. svr.Post("/upload", [&](const Request &req, Response &res) {
  12269. EXPECT_EQ(kItemCount, req.form.fields.size());
  12270. for (size_t i = 0; i < kItemCount; i++) {
  12271. auto key = "field" + std::to_string(i);
  12272. auto val = "value" + std::to_string(i);
  12273. auto it = req.form.fields.find(key);
  12274. if (it != req.form.fields.end()) {
  12275. EXPECT_EQ(val, it->second.content);
  12276. } else {
  12277. ADD_FAILURE() << "Missing field: " << key;
  12278. }
  12279. }
  12280. res.set_content("ok", "text/plain");
  12281. handled = true;
  12282. });
  12283. auto port = svr.bind_to_any_port(HOST);
  12284. auto t = thread([&] { svr.listen_after_bind(); });
  12285. auto se = detail::scope_exit([&] {
  12286. svr.stop();
  12287. t.join();
  12288. ASSERT_FALSE(svr.is_running());
  12289. ASSERT_TRUE(handled);
  12290. });
  12291. svr.wait_until_ready();
  12292. UploadFormDataItems items;
  12293. items.reserve(kItemCount);
  12294. for (size_t i = 0; i < kItemCount; i++) {
  12295. items.push_back(
  12296. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12297. }
  12298. Client cli(HOST, port);
  12299. auto res = cli.Post("/upload", items);
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. }
  12303. TEST(MultipartFormDataTest, MakeFileProvider) {
  12304. // Verify make_file_provider sends a file's contents correctly.
  12305. const std::string file_content(4096, 'Z');
  12306. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12307. {
  12308. std::ofstream ofs(tmp_path, std::ios::binary);
  12309. ofs.write(file_content.data(),
  12310. static_cast<std::streamsize>(file_content.size()));
  12311. }
  12312. auto handled = false;
  12313. Server svr;
  12314. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12315. const ContentReader &content_reader) {
  12316. ASSERT_TRUE(req.is_multipart_form_data());
  12317. std::vector<FormData> items;
  12318. content_reader(
  12319. [&](const FormData &file) {
  12320. items.push_back(file);
  12321. return true;
  12322. },
  12323. [&](const char *data, size_t data_length) {
  12324. items.back().content.append(data, data_length);
  12325. return true;
  12326. });
  12327. ASSERT_EQ(1u, items.size());
  12328. EXPECT_EQ("myfile", items[0].name);
  12329. EXPECT_EQ("data.bin", items[0].filename);
  12330. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12331. EXPECT_EQ(file_content, items[0].content);
  12332. handled = true;
  12333. });
  12334. auto port = svr.bind_to_any_port(HOST);
  12335. auto t = thread([&] { svr.listen_after_bind(); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. t.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. ASSERT_TRUE(handled);
  12341. std::remove(tmp_path.c_str());
  12342. });
  12343. svr.wait_until_ready();
  12344. FormDataProviderItems providers;
  12345. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12346. "application/octet-stream"));
  12347. Client cli(HOST, port);
  12348. auto res = cli.Post("/upload", {}, {}, providers);
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::OK_200, res->status);
  12351. }
  12352. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12353. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12354. // (100) headers is rejected with a 400 Bad Request response.
  12355. Server svr;
  12356. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12357. res.set_content("ok", "text/plain");
  12358. });
  12359. thread t = thread([&] { svr.listen(HOST, PORT); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. ASSERT_FALSE(svr.is_running());
  12364. });
  12365. svr.wait_until_ready();
  12366. // Build a multipart part with 101 custom headers (exceeding
  12367. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12368. std::stringstream body;
  12369. body << "--simpleboundary\r\n"
  12370. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12371. for (int i = 0; i < 101; i++) {
  12372. body << "X-Custom-Header-" << i << ": value\r\n";
  12373. }
  12374. body << "\r\n"
  12375. << "value1\r\n"
  12376. << "--simpleboundary--\r\n";
  12377. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12378. Client cli(HOST, PORT);
  12379. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12381. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12382. }
  12383. TEST(MakeFileBodyTest, Basic) {
  12384. const std::string file_content(4096, 'Z');
  12385. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12386. {
  12387. std::ofstream ofs(tmp_path, std::ios::binary);
  12388. ofs.write(file_content.data(),
  12389. static_cast<std::streamsize>(file_content.size()));
  12390. }
  12391. auto handled = false;
  12392. Server svr;
  12393. svr.Post("/upload", [&](const Request &req, Response &res) {
  12394. EXPECT_EQ(file_content, req.body);
  12395. handled = true;
  12396. res.status = StatusCode::OK_200;
  12397. });
  12398. auto port = svr.bind_to_any_port(HOST);
  12399. auto t = thread([&] { svr.listen_after_bind(); });
  12400. auto se = detail::scope_exit([&] {
  12401. svr.stop();
  12402. t.join();
  12403. ASSERT_FALSE(svr.is_running());
  12404. ASSERT_TRUE(handled);
  12405. std::remove(tmp_path.c_str());
  12406. });
  12407. svr.wait_until_ready();
  12408. auto fb = make_file_body(tmp_path);
  12409. ASSERT_GT(fb.first, 0u);
  12410. Client cli(HOST, port);
  12411. auto res =
  12412. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12414. EXPECT_EQ(StatusCode::OK_200, res->status);
  12415. }
  12416. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12417. static constexpr unsigned int number_of_tasks{1000000};
  12418. std::atomic_uint count{0};
  12419. std::unique_ptr<TaskQueue> task_queue{
  12420. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12421. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12422. auto queued = task_queue->enqueue(
  12423. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12424. EXPECT_TRUE(queued);
  12425. }
  12426. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12427. task_queue->shutdown();
  12428. #else
  12429. EXPECT_NO_THROW(task_queue->shutdown());
  12430. #endif
  12431. EXPECT_EQ(number_of_tasks, count.load());
  12432. }
  12433. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12434. static constexpr unsigned int number_of_tasks{1000000};
  12435. static constexpr unsigned int qlimit{2};
  12436. unsigned int queued_count{0};
  12437. std::atomic_uint count{0};
  12438. std::unique_ptr<TaskQueue> task_queue{
  12439. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12440. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12441. if (task_queue->enqueue(
  12442. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12443. queued_count++;
  12444. }
  12445. }
  12446. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12447. task_queue->shutdown();
  12448. #else
  12449. EXPECT_NO_THROW(task_queue->shutdown());
  12450. #endif
  12451. EXPECT_EQ(queued_count, count.load());
  12452. EXPECT_TRUE(queued_count <= number_of_tasks);
  12453. EXPECT_TRUE(queued_count >= qlimit);
  12454. }
  12455. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12456. // Use a short idle timeout so a dynamic thread spawns, times out and
  12457. // exits during the test, and the pool keeps working afterwards.
  12458. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12459. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12460. /*idle_timeout_sec=*/1}};
  12461. std::atomic_uint count{0};
  12462. std::condition_variable cv;
  12463. std::mutex mtx;
  12464. bool release = false;
  12465. // Block the base thread so the second task spawns a dynamic thread.
  12466. EXPECT_TRUE(task_queue->enqueue([&] {
  12467. std::unique_lock<std::mutex> lock(mtx);
  12468. while (!release) {
  12469. cv.wait(lock);
  12470. }
  12471. count++;
  12472. }));
  12473. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12474. // Let the dynamic thread finish its task and exceed the idle timeout.
  12475. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12476. {
  12477. std::unique_lock<std::mutex> lock(mtx);
  12478. release = true;
  12479. }
  12480. cv.notify_all();
  12481. // The pool must still accept and run tasks after the dynamic thread exited.
  12482. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12483. task_queue->shutdown();
  12484. EXPECT_EQ(3u, count.load());
  12485. }
  12486. TEST(TaskQueueTest, MaxQueuedRequests) {
  12487. static constexpr unsigned int qlimit{3};
  12488. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12489. std::condition_variable sem_cv;
  12490. std::mutex sem_mtx;
  12491. int credits = 0;
  12492. bool queued;
  12493. /* Fill up the queue with tasks that will block until we give them credits to
  12494. * complete. */
  12495. for (unsigned int n = 0; n <= qlimit;) {
  12496. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12497. std::unique_lock<std::mutex> lock(sem_mtx);
  12498. while (credits <= 0) {
  12499. sem_cv.wait(lock);
  12500. }
  12501. /* Consume the credit and signal the test code if they are all gone. */
  12502. if (--credits == 0) { sem_cv.notify_one(); }
  12503. });
  12504. if (n < qlimit) {
  12505. /* The first qlimit enqueues must succeed. */
  12506. EXPECT_TRUE(queued);
  12507. } else {
  12508. /* The last one will succeed only when the worker thread
  12509. * starts and dequeues the first blocking task. Although
  12510. * not necessary for the correctness of this test, we sleep for
  12511. * a short while to avoid busy waiting. */
  12512. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12513. }
  12514. if (queued) { n++; }
  12515. }
  12516. /* Further enqueues must fail since the queue is full. */
  12517. for (auto i = 0; i < 4; i++) {
  12518. queued = task_queue->enqueue([] {});
  12519. EXPECT_FALSE(queued);
  12520. }
  12521. /* Give the credits to allow the previous tasks to complete. */
  12522. {
  12523. std::unique_lock<std::mutex> lock(sem_mtx);
  12524. credits += qlimit + 1;
  12525. }
  12526. sem_cv.notify_all();
  12527. /* Wait for all the credits to be consumed. */
  12528. {
  12529. std::unique_lock<std::mutex> lock(sem_mtx);
  12530. while (credits > 0) {
  12531. sem_cv.wait(lock);
  12532. }
  12533. }
  12534. /* Check that we are able again to enqueue at least qlimit tasks. */
  12535. for (unsigned int i = 0; i < qlimit; i++) {
  12536. queued = task_queue->enqueue([] {});
  12537. EXPECT_TRUE(queued);
  12538. }
  12539. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12540. task_queue->shutdown();
  12541. #else
  12542. EXPECT_NO_THROW(task_queue->shutdown());
  12543. #endif
  12544. }
  12545. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12546. Server svr;
  12547. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12548. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12549. });
  12550. svr.Get("/hello", [](const Request &req, Response &res) {
  12551. res.set_content(req.get_param_value("key"), "text/plain");
  12552. });
  12553. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12554. auto se = detail::scope_exit([&] {
  12555. svr.stop();
  12556. thread.join();
  12557. ASSERT_FALSE(svr.is_running());
  12558. });
  12559. svr.wait_until_ready();
  12560. {
  12561. Client cli(HOST, PORT);
  12562. cli.set_follow_location(true);
  12563. auto res = cli.Get("/");
  12564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12565. EXPECT_EQ(StatusCode::OK_200, res->status);
  12566. EXPECT_EQ("val&key2=val2", res->body);
  12567. }
  12568. }
  12569. #endif
  12570. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12571. Server svr;
  12572. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12573. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12574. });
  12575. svr.Get("/hello", [](const Request &req, Response &res) {
  12576. res.set_content(req.get_param_value("key"), "text/plain");
  12577. });
  12578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12579. auto se = detail::scope_exit([&] {
  12580. svr.stop();
  12581. thread.join();
  12582. ASSERT_FALSE(svr.is_running());
  12583. });
  12584. svr.wait_until_ready();
  12585. {
  12586. Client cli(HOST, PORT);
  12587. cli.set_follow_location(true);
  12588. auto res = cli.Get("/");
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. EXPECT_EQ(StatusCode::OK_200, res->status);
  12591. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12592. }
  12593. }
  12594. TEST(RedirectTest, RedirectWithPlusInPath) {
  12595. Server svr;
  12596. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12597. res.set_redirect("/a+b");
  12598. });
  12599. // Route pattern uses regex; escape + as \\+
  12600. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12601. res.set_content(req.path, "text/plain");
  12602. });
  12603. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12604. auto se = detail::scope_exit([&] {
  12605. svr.stop();
  12606. thread.join();
  12607. ASSERT_FALSE(svr.is_running());
  12608. });
  12609. svr.wait_until_ready();
  12610. {
  12611. Client cli(HOST, PORT);
  12612. cli.set_follow_location(true);
  12613. auto res = cli.Get("/");
  12614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12615. EXPECT_EQ(StatusCode::OK_200, res->status);
  12616. EXPECT_EQ("/a+b", res->body);
  12617. }
  12618. }
  12619. #ifdef CPPHTTPLIB_SSL_ENABLED
  12620. TEST(RedirectTest, Issue2185_Online) {
  12621. SSLClient client("github.com");
  12622. client.set_follow_location(true);
  12623. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12624. "Coollab-Windows.zip");
  12625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12626. EXPECT_EQ(StatusCode::OK_200, res->status);
  12627. EXPECT_EQ(9920427U, res->body.size());
  12628. }
  12629. #endif
  12630. TEST(VulnerabilityTest, CRLFInjection) {
  12631. Server svr;
  12632. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12633. res.set_content("Hello 1", "text/plain");
  12634. });
  12635. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12636. res.set_content("Hello 2", "text/plain");
  12637. });
  12638. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12639. res.set_content("Hello 3", "text/plain");
  12640. });
  12641. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12642. res.set_content("Hello 4", "text/plain");
  12643. });
  12644. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12645. for (const auto &x : req.headers) {
  12646. auto key = x.first;
  12647. EXPECT_STRNE("evil", key.c_str());
  12648. }
  12649. });
  12650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12651. auto se = detail::scope_exit([&] {
  12652. svr.stop();
  12653. thread.join();
  12654. ASSERT_FALSE(svr.is_running());
  12655. });
  12656. svr.wait_until_ready();
  12657. {
  12658. Client cli(HOST, PORT);
  12659. cli.Post("/test1", "A=B",
  12660. "application/x-www-form-urlencoded\r\nevil: hello1");
  12661. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12662. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12663. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12664. }
  12665. }
  12666. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12667. auto server_thread = std::thread([] {
  12668. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12669. default_socket_options(srv);
  12670. sockaddr_in addr{};
  12671. addr.sin_family = AF_INET;
  12672. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12673. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12674. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12675. ::listen(srv, 1);
  12676. sockaddr_in cli_addr{};
  12677. socklen_t cli_len = sizeof(cli_addr);
  12678. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12679. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12680. std::string buf_all;
  12681. char buf[2048];
  12682. ssize_t n;
  12683. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12684. buf_all.append(buf, static_cast<size_t>(n));
  12685. size_t pos;
  12686. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12687. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12688. auto e = request_block.find("\r\n");
  12689. if (e != std::string::npos) {
  12690. auto request_line = request_block.substr(0, e);
  12691. std::string msg =
  12692. "CRLF injection detected in request line: '" + request_line + "'";
  12693. EXPECT_FALSE(true) << msg;
  12694. }
  12695. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12696. ::send(cli,
  12697. #ifdef _WIN32
  12698. static_cast<const char *>(resp.c_str()),
  12699. static_cast<int>(resp.size()),
  12700. #else
  12701. resp.c_str(), resp.size(),
  12702. #endif
  12703. 0);
  12704. buf_all.erase(0, pos + 4);
  12705. }
  12706. }
  12707. detail::close_socket(cli);
  12708. detail::close_socket(srv);
  12709. });
  12710. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12711. auto cli = Client("127.0.0.1", PORT + 1);
  12712. auto headers = Headers{
  12713. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12714. {"Connection", "keep-alive"}};
  12715. auto res = cli.Get("/hi", headers);
  12716. EXPECT_FALSE(res);
  12717. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12718. server_thread.join();
  12719. }
  12720. TEST(PathParamsTest, StaticMatch) {
  12721. const auto pattern = "/users/all";
  12722. detail::PathParamsMatcher matcher(pattern);
  12723. Request request;
  12724. request.path = "/users/all";
  12725. ASSERT_TRUE(matcher.match(request));
  12726. std::unordered_map<std::string, std::string> expected_params = {};
  12727. EXPECT_EQ(request.path_params, expected_params);
  12728. }
  12729. TEST(PathParamsTest, StaticMismatch) {
  12730. const auto pattern = "/users/all";
  12731. detail::PathParamsMatcher matcher(pattern);
  12732. Request request;
  12733. request.path = "/users/1";
  12734. ASSERT_FALSE(matcher.match(request));
  12735. }
  12736. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12737. const auto pattern = "/users/:id/subscriptions";
  12738. detail::PathParamsMatcher matcher(pattern);
  12739. Request request;
  12740. request.path = "/users/42/subscriptions";
  12741. ASSERT_TRUE(matcher.match(request));
  12742. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12743. EXPECT_EQ(request.path_params, expected_params);
  12744. }
  12745. TEST(PathParamsTest, SingleParamInTheEnd) {
  12746. const auto pattern = "/users/:id";
  12747. detail::PathParamsMatcher matcher(pattern);
  12748. Request request;
  12749. request.path = "/users/24";
  12750. ASSERT_TRUE(matcher.match(request));
  12751. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12752. EXPECT_EQ(request.path_params, expected_params);
  12753. }
  12754. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12755. const auto pattern = "/users/:id/";
  12756. detail::PathParamsMatcher matcher(pattern);
  12757. Request request;
  12758. request.path = "/users/42/";
  12759. ASSERT_TRUE(matcher.match(request));
  12760. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12761. EXPECT_EQ(request.path_params, expected_params);
  12762. }
  12763. TEST(PathParamsTest, EmptyParam) {
  12764. const auto pattern = "/users/:id/";
  12765. detail::PathParamsMatcher matcher(pattern);
  12766. Request request;
  12767. request.path = "/users//";
  12768. ASSERT_TRUE(matcher.match(request));
  12769. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12770. EXPECT_EQ(request.path_params, expected_params);
  12771. }
  12772. TEST(PathParamsTest, FragmentMismatch) {
  12773. const auto pattern = "/users/:id/";
  12774. detail::PathParamsMatcher matcher(pattern);
  12775. Request request;
  12776. request.path = "/admins/24/";
  12777. ASSERT_FALSE(matcher.match(request));
  12778. }
  12779. TEST(PathParamsTest, ExtraFragments) {
  12780. const auto pattern = "/users/:id";
  12781. detail::PathParamsMatcher matcher(pattern);
  12782. Request request;
  12783. request.path = "/users/42/subscriptions";
  12784. ASSERT_FALSE(matcher.match(request));
  12785. }
  12786. TEST(PathParamsTest, MissingTrailingParam) {
  12787. const auto pattern = "/users/:id";
  12788. detail::PathParamsMatcher matcher(pattern);
  12789. Request request;
  12790. request.path = "/users";
  12791. ASSERT_FALSE(matcher.match(request));
  12792. }
  12793. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12794. const auto pattern = "/users/:id/subscriptions";
  12795. detail::PathParamsMatcher matcher(pattern);
  12796. Request request;
  12797. request.path = "/users/subscriptions";
  12798. ASSERT_FALSE(matcher.match(request));
  12799. }
  12800. TEST(PathParamsTest, MultipleParams) {
  12801. const auto pattern = "/users/:userid/subscriptions/:subid";
  12802. detail::PathParamsMatcher matcher(pattern);
  12803. Request request;
  12804. request.path = "/users/42/subscriptions/2";
  12805. ASSERT_TRUE(matcher.match(request));
  12806. std::unordered_map<std::string, std::string> expected_params = {
  12807. {"userid", "42"}, {"subid", "2"}};
  12808. EXPECT_EQ(request.path_params, expected_params);
  12809. }
  12810. TEST(PathParamsTest, SequenceOfParams) {
  12811. const auto pattern = "/values/:x/:y/:z";
  12812. detail::PathParamsMatcher matcher(pattern);
  12813. Request request;
  12814. request.path = "/values/1/2/3";
  12815. ASSERT_TRUE(matcher.match(request));
  12816. std::unordered_map<std::string, std::string> expected_params = {
  12817. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12818. EXPECT_EQ(request.path_params, expected_params);
  12819. }
  12820. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12821. const auto pattern = "/prefix:suffix";
  12822. detail::PathParamsMatcher matcher(pattern);
  12823. Request request;
  12824. request.path = "/prefix:suffix";
  12825. ASSERT_TRUE(matcher.match(request));
  12826. const std::unordered_map<std::string, std::string> expected_params = {};
  12827. EXPECT_EQ(request.path_params, expected_params);
  12828. }
  12829. TEST(ParseUrlTest, VariousPatterns) {
  12830. {
  12831. detail::UrlComponents uc;
  12832. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12833. EXPECT_EQ("http", uc.scheme);
  12834. EXPECT_EQ("example.com", uc.host);
  12835. EXPECT_EQ("8080", uc.port);
  12836. EXPECT_EQ("/path", uc.path);
  12837. EXPECT_EQ("?q=1", uc.query);
  12838. }
  12839. {
  12840. detail::UrlComponents uc;
  12841. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12842. EXPECT_EQ("https", uc.scheme);
  12843. EXPECT_EQ("example.com", uc.host);
  12844. EXPECT_TRUE(uc.port.empty());
  12845. EXPECT_EQ("/path", uc.path);
  12846. }
  12847. {
  12848. detail::UrlComponents uc;
  12849. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12850. EXPECT_EQ("::1", uc.host);
  12851. EXPECT_EQ("8080", uc.port);
  12852. EXPECT_EQ("/path", uc.path);
  12853. }
  12854. {
  12855. detail::UrlComponents uc;
  12856. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12857. }
  12858. {
  12859. detail::UrlComponents uc;
  12860. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12861. EXPECT_TRUE(uc.scheme.empty());
  12862. EXPECT_EQ("example.com", uc.host);
  12863. EXPECT_EQ("/path", uc.path);
  12864. EXPECT_EQ("?q=1", uc.query);
  12865. }
  12866. {
  12867. detail::UrlComponents uc;
  12868. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12869. EXPECT_TRUE(uc.host.empty());
  12870. EXPECT_EQ("/path", uc.path);
  12871. EXPECT_EQ("?q=1", uc.query);
  12872. }
  12873. {
  12874. detail::UrlComponents uc;
  12875. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12876. EXPECT_EQ("example.com", uc.host);
  12877. EXPECT_EQ("8080", uc.port);
  12878. }
  12879. {
  12880. // Unix socket path — must not be parsed as host
  12881. detail::UrlComponents uc;
  12882. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12883. EXPECT_TRUE(uc.host.empty());
  12884. }
  12885. {
  12886. detail::UrlComponents uc;
  12887. ASSERT_TRUE(detail::parse_url("", uc));
  12888. EXPECT_TRUE(uc.host.empty());
  12889. EXPECT_TRUE(uc.path.empty());
  12890. }
  12891. {
  12892. detail::UrlComponents uc;
  12893. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12894. }
  12895. {
  12896. detail::UrlComponents uc;
  12897. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12898. }
  12899. {
  12900. // Accepted by parse_url; callers restrict to http/https
  12901. detail::UrlComponents uc;
  12902. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12903. EXPECT_EQ("ftp", uc.scheme);
  12904. }
  12905. {
  12906. detail::UrlComponents uc;
  12907. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12908. }
  12909. {
  12910. detail::UrlComponents uc;
  12911. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12912. }
  12913. }
  12914. TEST(ParseUrlTest, FragmentHandling) {
  12915. {
  12916. detail::UrlComponents uc;
  12917. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12918. EXPECT_EQ("/path", uc.path);
  12919. EXPECT_TRUE(uc.query.empty());
  12920. }
  12921. {
  12922. detail::UrlComponents uc;
  12923. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12924. EXPECT_TRUE(uc.path.empty());
  12925. EXPECT_TRUE(uc.query.empty());
  12926. }
  12927. }
  12928. TEST(ParseUrlTest, UserinfoHandling) {
  12929. // Userinfo with @ but no colon — host includes @
  12930. detail::UrlComponents uc;
  12931. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12932. EXPECT_EQ("user@host.com", uc.host);
  12933. EXPECT_EQ("/path", uc.path);
  12934. }
  12935. TEST(ParseUrlTest, IPv6EdgeCases) {
  12936. {
  12937. detail::UrlComponents uc;
  12938. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12939. EXPECT_TRUE(uc.scheme.empty());
  12940. EXPECT_EQ("::1", uc.host);
  12941. EXPECT_EQ("8080", uc.port);
  12942. }
  12943. {
  12944. // Zone ID '%25' is not in [a-fA-F0-9:]
  12945. detail::UrlComponents uc;
  12946. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12947. }
  12948. }
  12949. TEST(ParseUrlTest, SchemeEdgeCases) {
  12950. {
  12951. detail::UrlComponents uc;
  12952. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12953. }
  12954. {
  12955. detail::UrlComponents uc;
  12956. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12957. }
  12958. {
  12959. detail::UrlComponents uc;
  12960. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12961. }
  12962. }
  12963. TEST(ParseUrlTest, PortEdgeCases) {
  12964. {
  12965. detail::UrlComponents uc;
  12966. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12967. EXPECT_TRUE(uc.port.empty());
  12968. EXPECT_EQ("/path", uc.path);
  12969. }
  12970. {
  12971. // parse_url accepts any port string; validation is done by parse_port
  12972. detail::UrlComponents uc;
  12973. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12974. EXPECT_EQ("abc", uc.port);
  12975. }
  12976. }
  12977. TEST(ParseUrlTest, WebSocketPatterns) {
  12978. {
  12979. detail::UrlComponents uc;
  12980. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12981. EXPECT_EQ("ws", uc.scheme);
  12982. EXPECT_EQ("echo.example.com", uc.host);
  12983. EXPECT_EQ("8080", uc.port);
  12984. EXPECT_EQ("/ws", uc.path);
  12985. }
  12986. {
  12987. detail::UrlComponents uc;
  12988. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12989. EXPECT_EQ("wss", uc.scheme);
  12990. EXPECT_EQ("echo.example.com", uc.host);
  12991. EXPECT_TRUE(uc.port.empty());
  12992. EXPECT_EQ("/ws", uc.path);
  12993. }
  12994. }
  12995. TEST(ParseUrlTest, QueryOnly) {
  12996. detail::UrlComponents uc;
  12997. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12998. EXPECT_TRUE(uc.host.empty());
  12999. EXPECT_TRUE(uc.path.empty());
  13000. EXPECT_EQ("?q=1&r=2", uc.query);
  13001. }
  13002. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13003. detail::UrlComponents uc;
  13004. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13005. EXPECT_TRUE(uc.scheme.empty());
  13006. EXPECT_EQ("example.com", uc.host);
  13007. EXPECT_EQ("443", uc.port);
  13008. EXPECT_EQ("/path", uc.path);
  13009. }
  13010. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13011. // If ipv6 regex working, regex match codepath is taken.
  13012. // else port will default to 80 in Client impl
  13013. int clientImplMagicPort = 80;
  13014. int port = 4321;
  13015. // above ports must be different to avoid false negative
  13016. EXPECT_NE(clientImplMagicPort, port);
  13017. std::string ipV6TestURL = "http://[ff06::c3]";
  13018. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13019. CLIENT_PRIVATE_KEY_FILE);
  13020. EXPECT_EQ(cli.port(), port);
  13021. }
  13022. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13023. auto file_path = "./www/dir/index.html";
  13024. auto dir_path = "./www/dir";
  13025. detail::FileStat stat_file(file_path);
  13026. EXPECT_TRUE(stat_file.is_file());
  13027. EXPECT_FALSE(stat_file.is_dir());
  13028. detail::FileStat stat_dir(dir_path);
  13029. EXPECT_FALSE(stat_dir.is_file());
  13030. EXPECT_TRUE(stat_dir.is_dir());
  13031. }
  13032. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13033. // IPv4 with default HTTP port (80)
  13034. EXPECT_EQ("example.com",
  13035. detail::make_host_and_port_string("example.com", 80, false));
  13036. // IPv4 with default HTTPS port (443)
  13037. EXPECT_EQ("example.com",
  13038. detail::make_host_and_port_string("example.com", 443, true));
  13039. // IPv4 with non-default HTTP port
  13040. EXPECT_EQ("example.com:8080",
  13041. detail::make_host_and_port_string("example.com", 8080, false));
  13042. // IPv4 with non-default HTTPS port
  13043. EXPECT_EQ("example.com:8443",
  13044. detail::make_host_and_port_string("example.com", 8443, true));
  13045. // IPv6 with default HTTP port (80)
  13046. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13047. // IPv6 with default HTTPS port (443)
  13048. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13049. // IPv6 with non-default HTTP port
  13050. EXPECT_EQ("[::1]:8080",
  13051. detail::make_host_and_port_string("::1", 8080, false));
  13052. // IPv6 with non-default HTTPS port
  13053. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13054. // IPv6 full address with default port
  13055. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13056. detail::make_host_and_port_string(
  13057. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13058. // IPv6 full address with non-default port
  13059. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13060. detail::make_host_and_port_string(
  13061. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13062. // IPv6 localhost with non-default port
  13063. EXPECT_EQ("[::1]:3000",
  13064. detail::make_host_and_port_string("::1", 3000, false));
  13065. // IPv6 with zone ID (link-local address) with default port
  13066. EXPECT_EQ("[fe80::1%eth0]",
  13067. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13068. // IPv6 with zone ID (link-local address) with non-default port
  13069. EXPECT_EQ("[fe80::1%eth0]:8080",
  13070. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13071. // Edge case: Port 443 with is_ssl=false (should add port)
  13072. EXPECT_EQ("example.com:443",
  13073. detail::make_host_and_port_string("example.com", 443, false));
  13074. // Edge case: Port 80 with is_ssl=true (should add port)
  13075. EXPECT_EQ("example.com:80",
  13076. detail::make_host_and_port_string("example.com", 80, true));
  13077. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13078. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13079. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13080. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13081. // Security fix: Already bracketed IPv6 should not get double brackets
  13082. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13083. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13084. EXPECT_EQ("[::1]:8080",
  13085. detail::make_host_and_port_string("[::1]", 8080, false));
  13086. EXPECT_EQ("[2001:db8::1]:8080",
  13087. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13088. EXPECT_EQ("[fe80::1%eth0]",
  13089. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13090. EXPECT_EQ("[fe80::1%eth0]:8080",
  13091. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13092. // Edge case: Empty host (should return as-is)
  13093. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13094. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13095. // This is a known limitation but shouldn't crash
  13096. EXPECT_EQ("[host:name]",
  13097. detail::make_host_and_port_string("host:name", 80, false));
  13098. // Port number edge cases (no validation, but should not crash)
  13099. EXPECT_EQ("example.com:0",
  13100. detail::make_host_and_port_string("example.com", 0, false));
  13101. EXPECT_EQ("example.com:-1",
  13102. detail::make_host_and_port_string("example.com", -1, false));
  13103. EXPECT_EQ("example.com:65535",
  13104. detail::make_host_and_port_string("example.com", 65535, false));
  13105. EXPECT_EQ("example.com:65536",
  13106. detail::make_host_and_port_string("example.com", 65536, false));
  13107. }
  13108. #ifdef CPPHTTPLIB_SSL_ENABLED
  13109. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13110. httplib::SSLClient cli("roblox.com", 443);
  13111. cli.set_follow_location(true);
  13112. auto res = cli.Get("/");
  13113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13114. EXPECT_EQ(StatusCode::OK_200, res->status);
  13115. }
  13116. #endif
  13117. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13118. Server svr;
  13119. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13120. EXPECT_EQ(res.status, 400);
  13121. });
  13122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13123. auto se = detail::scope_exit([&] {
  13124. svr.stop();
  13125. thread.join();
  13126. ASSERT_FALSE(svr.is_running());
  13127. });
  13128. svr.wait_until_ready();
  13129. Client cli(HOST, PORT);
  13130. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13131. }
  13132. TEST(InvalidHeaderCharsTest, is_field_name) {
  13133. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13134. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13135. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13136. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13137. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13138. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13139. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13140. EXPECT_FALSE(detail::fields::is_field_name(""));
  13141. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13142. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13143. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13144. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13145. }
  13146. TEST(InvalidHeaderCharsTest, is_field_value) {
  13147. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13148. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13149. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13150. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13151. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13152. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13153. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13154. EXPECT_TRUE(detail::fields::is_field_value(""));
  13155. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13156. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13157. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13158. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13159. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13160. }
  13161. TEST(InvalidHeaderCharsTest, OnServer) {
  13162. Server svr;
  13163. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13164. std::string header = "Not Set";
  13165. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13166. res.set_header(header, "value");
  13167. res.set_content("Page Content Page Content", "text/plain");
  13168. });
  13169. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13170. std::string header = "Not Set";
  13171. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13172. res.set_header("X-Test", header);
  13173. res.set_content("Page Content Page Content", "text/plain");
  13174. });
  13175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13176. auto se = detail::scope_exit([&] {
  13177. svr.stop();
  13178. thread.join();
  13179. ASSERT_FALSE(svr.is_running());
  13180. });
  13181. svr.wait_until_ready();
  13182. Client cli(HOST, PORT);
  13183. {
  13184. auto res = cli.Get(
  13185. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ("Page Content Page Content", res->body);
  13188. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13189. }
  13190. {
  13191. auto res = cli.Get(
  13192. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13194. EXPECT_EQ("Page Content Page Content", res->body);
  13195. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13196. }
  13197. }
  13198. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13199. auto handled = false;
  13200. Server svr;
  13201. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13202. thread t = thread([&] { svr.listen(HOST, PORT); });
  13203. auto se = detail::scope_exit([&] {
  13204. svr.stop();
  13205. t.join();
  13206. ASSERT_FALSE(svr.is_running());
  13207. ASSERT_FALSE(handled);
  13208. });
  13209. svr.wait_until_ready();
  13210. auto req = "POST /test HTTP/1.1\r\n"
  13211. "Content-Length: x\r\n"
  13212. "\r\n";
  13213. std::string response;
  13214. ASSERT_TRUE(send_request(1, req, &response));
  13215. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13216. response.substr(0, response.find("\r\n")));
  13217. }
  13218. #ifndef _WIN32
  13219. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13220. static constexpr char reject[] = "Unauthorized";
  13221. static constexpr char accept[] = "Upload accepted";
  13222. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13223. Server svr;
  13224. svr.set_expect_100_continue_handler(
  13225. [](const Request & /*req*/, Response &res) {
  13226. res.status = StatusCode::Unauthorized_401;
  13227. res.set_content(reject, "text/plain");
  13228. return res.status;
  13229. });
  13230. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13231. res.set_content(accept, "text/plain");
  13232. });
  13233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13234. auto se = detail::scope_exit([&] {
  13235. svr.stop();
  13236. thread.join();
  13237. ASSERT_FALSE(svr.is_running());
  13238. });
  13239. svr.wait_until_ready();
  13240. {
  13241. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13242. curl_easy_init(), &curl_easy_cleanup};
  13243. ASSERT_NE(curl, nullptr);
  13244. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13245. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13246. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13247. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13248. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13249. &curl_slist_free_all};
  13250. ASSERT_NE(list, nullptr);
  13251. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13252. struct read_data {
  13253. size_t read_size;
  13254. size_t total_size;
  13255. } data = {0, total_size};
  13256. using read_callback_t =
  13257. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13258. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13259. void *userdata) -> size_t {
  13260. read_data *d = (read_data *)userdata;
  13261. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13262. std::fill_n(ptr, size * nmemb, 'A');
  13263. d->read_size += size * nmemb;
  13264. return size * nmemb;
  13265. };
  13266. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13267. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13268. std::vector<char> buffer;
  13269. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13270. using write_callback_t =
  13271. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13272. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13273. void *userdata) -> size_t {
  13274. std::vector<char> *buf = (std::vector<char> *)userdata;
  13275. buf->reserve(buf->size() + size * nmemb + 1);
  13276. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13277. return size * nmemb;
  13278. };
  13279. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13280. {
  13281. const auto res = curl_easy_perform(curl.get());
  13282. ASSERT_EQ(res, CURLE_OK);
  13283. }
  13284. {
  13285. auto response_code = long{};
  13286. const auto res =
  13287. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13288. ASSERT_EQ(res, CURLE_OK);
  13289. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13290. }
  13291. {
  13292. auto dl = curl_off_t{};
  13293. const auto res =
  13294. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13295. ASSERT_EQ(res, CURLE_OK);
  13296. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13297. }
  13298. {
  13299. buffer.push_back('\0');
  13300. ASSERT_STRCASEEQ(buffer.data(), reject);
  13301. }
  13302. }
  13303. }
  13304. #endif
  13305. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13306. // Regression test for #2458.
  13307. //
  13308. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13309. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13310. // ticket can make the client socket spuriously readable during the
  13311. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13312. // the client withholds the body and then blocks reading a response that never
  13313. // comes, failing with `Failed to read connection`.
  13314. //
  13315. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13316. // within the timeout. This raw OpenSSL server deliberately never sends
  13317. // `100 Continue`; the client must still deliver the body and receive 200.
  13318. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13319. signal(SIGPIPE, SIG_IGN);
  13320. const auto port = PORT + 4;
  13321. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13322. ASSERT_NE(srv, INVALID_SOCKET);
  13323. int opt = 1;
  13324. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13325. sockaddr_in addr{};
  13326. addr.sin_family = AF_INET;
  13327. addr.sin_port = htons(static_cast<uint16_t>(port));
  13328. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13329. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13330. ASSERT_EQ(0, ::listen(srv, 1));
  13331. std::atomic<size_t> server_body_bytes{0};
  13332. auto server_thread = std::thread([&] {
  13333. sockaddr_in cli_addr{};
  13334. socklen_t cli_len = sizeof(cli_addr);
  13335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13336. if (cli == INVALID_SOCKET) { return; }
  13337. // Bound the lifetime of the server side so a buggy client (which never
  13338. // sends the body) cannot make this thread block forever on join.
  13339. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13340. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13341. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13342. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13343. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13344. SSL *ssl = SSL_new(ctx);
  13345. SSL_set_fd(ssl, static_cast<int>(cli));
  13346. if (SSL_accept(ssl) > 0) {
  13347. // Read the request headers. Reading here also flushes the TLS 1.3
  13348. // session tickets to the client. Deliberately do NOT send
  13349. // `100 Continue`.
  13350. std::string buf;
  13351. char tmp[1024];
  13352. while (buf.find("\r\n\r\n") == std::string::npos) {
  13353. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13354. if (n <= 0) { break; }
  13355. buf.append(tmp, static_cast<size_t>(n));
  13356. }
  13357. // A correct client sends the body now; count what arrives.
  13358. auto pos = buf.find("\r\n\r\n");
  13359. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13360. while (body < 4096) {
  13361. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13362. if (n <= 0) { break; }
  13363. body += static_cast<size_t>(n);
  13364. }
  13365. server_body_bytes = body;
  13366. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13367. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13368. SSL_shutdown(ssl);
  13369. }
  13370. SSL_free(ssl);
  13371. detail::close_socket(cli);
  13372. SSL_CTX_free(ctx);
  13373. });
  13374. auto se = detail::scope_exit([&] {
  13375. server_thread.join();
  13376. detail::close_socket(srv);
  13377. });
  13378. SSLClient cli("127.0.0.1", port);
  13379. cli.enable_server_certificate_verification(false);
  13380. cli.set_connection_timeout(5, 0);
  13381. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13382. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13383. std::string body(4096, 'A');
  13384. auto res = cli.Put("/api/test", body, "application/json");
  13385. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13386. EXPECT_EQ(StatusCode::OK_200, res->status);
  13387. EXPECT_EQ(body.size(), server_body_bytes.load());
  13388. }
  13389. #endif
  13390. template <typename S, typename C>
  13391. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13392. svr.Get("/stream", [&](const Request &, Response &res) {
  13393. auto data = new std::string("01234567890123456789");
  13394. res.set_content_provider(
  13395. data->size(), "text/plain",
  13396. [&, data](size_t offset, size_t length, DataSink &sink) {
  13397. const size_t DATA_CHUNK_SIZE = 4;
  13398. const auto &d = *data;
  13399. std::this_thread::sleep_for(std::chrono::seconds(1));
  13400. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13401. return true;
  13402. },
  13403. [data](bool success) {
  13404. EXPECT_FALSE(success);
  13405. delete data;
  13406. });
  13407. });
  13408. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13409. auto i = new size_t(0);
  13410. res.set_content_provider(
  13411. "text/plain",
  13412. [i](size_t, DataSink &sink) {
  13413. if (*i < 5) {
  13414. std::this_thread::sleep_for(std::chrono::seconds(1));
  13415. sink.write("abcd", 4);
  13416. (*i)++;
  13417. } else {
  13418. sink.done();
  13419. }
  13420. return true;
  13421. },
  13422. [i](bool success) {
  13423. EXPECT_FALSE(success);
  13424. delete i;
  13425. });
  13426. });
  13427. svr.Get("/chunked", [&](const Request &, Response &res) {
  13428. auto i = new size_t(0);
  13429. res.set_chunked_content_provider(
  13430. "text/plain",
  13431. [i](size_t, DataSink &sink) {
  13432. if (*i < 5) {
  13433. std::this_thread::sleep_for(std::chrono::seconds(1));
  13434. sink.os << "abcd";
  13435. (*i)++;
  13436. } else {
  13437. sink.done();
  13438. }
  13439. return true;
  13440. },
  13441. [i](bool success) {
  13442. EXPECT_FALSE(success);
  13443. delete i;
  13444. });
  13445. });
  13446. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13447. auto se = detail::scope_exit([&] {
  13448. svr.stop();
  13449. listen_thread.join();
  13450. ASSERT_FALSE(svr.is_running());
  13451. });
  13452. svr.wait_until_ready();
  13453. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13454. {
  13455. auto start = std::chrono::steady_clock::now();
  13456. auto res = cli.Get("/stream");
  13457. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13458. std::chrono::steady_clock::now() - start)
  13459. .count();
  13460. ASSERT_FALSE(res);
  13461. EXPECT_EQ(Error::Read, res.error());
  13462. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13463. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13464. }
  13465. {
  13466. auto start = std::chrono::steady_clock::now();
  13467. auto res = cli.Get("/stream_without_length");
  13468. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13469. std::chrono::steady_clock::now() - start)
  13470. .count();
  13471. ASSERT_FALSE(res);
  13472. EXPECT_EQ(Error::Read, res.error());
  13473. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13474. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13475. }
  13476. {
  13477. auto start = std::chrono::steady_clock::now();
  13478. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13479. EXPECT_EQ("abcd", string(data, data_length));
  13480. return true;
  13481. });
  13482. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13483. std::chrono::steady_clock::now() - start)
  13484. .count();
  13485. ASSERT_FALSE(res);
  13486. EXPECT_EQ(Error::Read, res.error());
  13487. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13488. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13489. }
  13490. }
  13491. TEST(MaxTimeoutTest, ContentStream) {
  13492. time_t timeout = 2000;
  13493. time_t threshold = 200;
  13494. Server svr;
  13495. Client cli("localhost", PORT);
  13496. max_timeout_test(svr, cli, timeout, threshold);
  13497. }
  13498. #ifdef CPPHTTPLIB_SSL_ENABLED
  13499. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13500. time_t timeout = 2000;
  13501. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. SSLClient cli("localhost", PORT);
  13504. cli.enable_server_certificate_verification(false);
  13505. max_timeout_test(svr, cli, timeout, threshold);
  13506. }
  13507. #endif
  13508. class EventDispatcher {
  13509. public:
  13510. EventDispatcher() {}
  13511. bool wait_event(DataSink *sink) {
  13512. unique_lock<mutex> lk(m_);
  13513. int id = id_;
  13514. // Wait with timeout to prevent hanging if client disconnects
  13515. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13516. [&] { return cid_ == id; })) {
  13517. return false; // Timeout occurred
  13518. }
  13519. sink->write(message_.data(), message_.size());
  13520. return true;
  13521. }
  13522. void send_event(const string &message) {
  13523. lock_guard<mutex> lk(m_);
  13524. cid_ = id_++;
  13525. message_ = message;
  13526. cv_.notify_all();
  13527. }
  13528. private:
  13529. mutex m_;
  13530. condition_variable cv_;
  13531. atomic_int id_{0};
  13532. atomic_int cid_{-1};
  13533. string message_;
  13534. };
  13535. TEST(ClientInThreadTest, Issue2068) {
  13536. EventDispatcher ed;
  13537. Server svr;
  13538. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13539. res.set_chunked_content_provider("text/event-stream",
  13540. [&](size_t /*offset*/, DataSink &sink) {
  13541. return ed.wait_event(&sink);
  13542. });
  13543. });
  13544. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13545. svr.wait_until_ready();
  13546. thread event_thread([&] {
  13547. int id = 0;
  13548. while (svr.is_running()) {
  13549. this_thread::sleep_for(chrono::milliseconds(500));
  13550. std::stringstream ss;
  13551. ss << "data: " << id << "\n\n";
  13552. ed.send_event(ss.str());
  13553. id++;
  13554. }
  13555. });
  13556. auto se = detail::scope_exit([&] {
  13557. svr.stop();
  13558. listen_thread.join();
  13559. event_thread.join();
  13560. ASSERT_FALSE(svr.is_running());
  13561. });
  13562. {
  13563. auto client = detail::make_unique<Client>(HOST, PORT);
  13564. client->set_read_timeout(std::chrono::minutes(10));
  13565. std::atomic<bool> stop{false};
  13566. std::thread t([&] {
  13567. client->Get("/event1",
  13568. [&](const char *, size_t) -> bool { return !stop; });
  13569. });
  13570. std::this_thread::sleep_for(std::chrono::seconds(2));
  13571. stop = true;
  13572. client->stop();
  13573. t.join();
  13574. // Reset client after thread has finished
  13575. client.reset();
  13576. }
  13577. }
  13578. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13579. auto handled = false;
  13580. Server svr;
  13581. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13583. auto se = detail::scope_exit([&] {
  13584. svr.stop();
  13585. t.join();
  13586. ASSERT_FALSE(svr.is_running());
  13587. ASSERT_FALSE(handled);
  13588. });
  13589. svr.wait_until_ready();
  13590. // Two Content-Length headers with different values — must be rejected
  13591. auto req = "POST /test HTTP/1.1\r\n"
  13592. "Content-Length: 5\r\n"
  13593. "Content-Length: 10\r\n"
  13594. "\r\n"
  13595. "hello";
  13596. std::string response;
  13597. ASSERT_TRUE(send_request(1, req, &response));
  13598. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13599. response.substr(0, response.find("\r\n")));
  13600. }
  13601. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13602. auto handled = false;
  13603. Server svr;
  13604. svr.Post("/test", [&](const Request &, Response &res) {
  13605. handled = true;
  13606. res.set_content("ok", "text/plain");
  13607. });
  13608. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. ASSERT_TRUE(handled);
  13614. });
  13615. svr.wait_until_ready();
  13616. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13617. auto req = "POST /test HTTP/1.1\r\n"
  13618. "Content-Length: 5\r\n"
  13619. "Content-Length: 5\r\n"
  13620. "\r\n"
  13621. "hello";
  13622. std::string response;
  13623. ASSERT_TRUE(send_request(1, req, &response));
  13624. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13625. }
  13626. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13627. Server svr;
  13628. svr.Get("/", [](const Request &req, Response &res) {
  13629. EXPECT_EQ(2U, req.trailers.size());
  13630. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13631. // Denied
  13632. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13633. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13634. // Accepted
  13635. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13636. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13637. EXPECT_TRUE(req.has_trailer("X-World"));
  13638. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13639. res.set_content("ok", "text/plain");
  13640. });
  13641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. const std::string req = "GET / HTTP/1.1\r\n"
  13649. "Transfer-Encoding: chunked\r\n"
  13650. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13651. "\r\n"
  13652. "0\r\n"
  13653. "Content-Length: 10\r\n"
  13654. "Host: internal.local\r\n"
  13655. "Content-Type: malicious/content\r\n"
  13656. "Cookie: any\r\n"
  13657. "Set-Cookie: any\r\n"
  13658. "X-Forwarded-For: attacker.com\r\n"
  13659. "X-Real-Ip: 1.1.1.1\r\n"
  13660. "X-Hello: hello\r\n"
  13661. "X-World: world\r\n"
  13662. "\r\n";
  13663. std::string res;
  13664. ASSERT_TRUE(send_request(1, req, &res));
  13665. }
  13666. // A direct client that is not listed in trusted_proxies must not be able to
  13667. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13668. // the peer address on the actual TCP connection determines whether the
  13669. // header is honored.
  13670. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13671. Server svr;
  13672. // Deliberately does NOT include the loopback address the test client
  13673. // actually connects from, so the direct connection is not a trusted proxy.
  13674. svr.set_trusted_proxies({"203.0.113.66"});
  13675. std::string observed_remote_addr;
  13676. svr.Get("/ip", [&](const Request &req, Response &res) {
  13677. observed_remote_addr = req.remote_addr;
  13678. res.set_content("ok", "text/plain");
  13679. });
  13680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13681. auto se = detail::scope_exit([&] {
  13682. svr.stop();
  13683. t.join();
  13684. ASSERT_FALSE(svr.is_running());
  13685. });
  13686. svr.wait_until_ready();
  13687. Client cli(HOST, PORT);
  13688. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13690. EXPECT_EQ(StatusCode::OK_200, res->status);
  13691. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13692. // ignored entirely and the real connection-level address retained.
  13693. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13694. observed_remote_addr == "127.0.0.1");
  13695. }
  13696. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13697. Server svr;
  13698. std::string observed_remote_addr;
  13699. std::string observed_xff;
  13700. svr.Get("/ip", [&](const Request &req, Response &res) {
  13701. observed_remote_addr = req.remote_addr;
  13702. observed_xff = req.get_header_value("X-Forwarded-For");
  13703. res.set_content("ok", "text/plain");
  13704. });
  13705. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13706. auto se = detail::scope_exit([&] {
  13707. svr.stop();
  13708. t.join();
  13709. ASSERT_FALSE(svr.is_running());
  13710. });
  13711. svr.wait_until_ready();
  13712. Client cli(HOST, PORT);
  13713. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13715. EXPECT_EQ(StatusCode::OK_200, res->status);
  13716. EXPECT_EQ(observed_xff, "203.0.113.66");
  13717. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13718. observed_remote_addr == "127.0.0.1");
  13719. }
  13720. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13721. Server svr;
  13722. svr.set_trusted_proxies({"203.0.113.66"});
  13723. std::string observed_remote_addr;
  13724. std::string observed_xff;
  13725. svr.Get("/ip", [&](const Request &req, Response &res) {
  13726. observed_remote_addr = req.remote_addr;
  13727. observed_xff = req.get_header_value("X-Forwarded-For");
  13728. res.set_content("ok", "text/plain");
  13729. });
  13730. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. t.join();
  13734. ASSERT_FALSE(svr.is_running());
  13735. });
  13736. svr.wait_until_ready();
  13737. Client cli(HOST, PORT);
  13738. auto res = cli.Get("/ip");
  13739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13740. EXPECT_EQ(StatusCode::OK_200, res->status);
  13741. EXPECT_EQ(observed_xff, "");
  13742. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13743. observed_remote_addr == "127.0.0.1");
  13744. }
  13745. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13746. Server svr;
  13747. // Include the loopback address the test client actually connects from, so
  13748. // the direct connection itself is recognized as the trusted proxy hop.
  13749. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13750. std::string observed_remote_addr;
  13751. std::string observed_xff;
  13752. svr.Get("/ip", [&](const Request &req, Response &res) {
  13753. observed_remote_addr = req.remote_addr;
  13754. observed_xff = req.get_header_value("X-Forwarded-For");
  13755. res.set_content("ok", "text/plain");
  13756. });
  13757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13758. auto se = detail::scope_exit([&] {
  13759. svr.stop();
  13760. t.join();
  13761. ASSERT_FALSE(svr.is_running());
  13762. });
  13763. svr.wait_until_ready();
  13764. Client cli(HOST, PORT);
  13765. auto res = cli.Get(
  13766. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13768. EXPECT_EQ(StatusCode::OK_200, res->status);
  13769. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13770. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13771. }
  13772. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13773. Server svr;
  13774. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13775. std::string observed_remote_addr;
  13776. std::string observed_xff;
  13777. svr.Get("/ip", [&](const Request &req, Response &res) {
  13778. observed_remote_addr = req.remote_addr;
  13779. observed_xff = req.get_header_value("X-Forwarded-For");
  13780. res.set_content("ok", "text/plain");
  13781. });
  13782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. ASSERT_FALSE(svr.is_running());
  13787. });
  13788. svr.wait_until_ready();
  13789. Client cli(HOST, PORT);
  13790. auto res = cli.Get(
  13791. "/ip",
  13792. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13794. EXPECT_EQ(StatusCode::OK_200, res->status);
  13795. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13796. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13797. }
  13798. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13799. Server svr;
  13800. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13801. std::string observed_remote_addr;
  13802. std::string observed_xff;
  13803. svr.Get("/ip", [&](const Request &req, Response &res) {
  13804. observed_remote_addr = req.remote_addr;
  13805. observed_xff = req.get_header_value("X-Forwarded-For");
  13806. res.set_content("ok", "text/plain");
  13807. });
  13808. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13809. auto se = detail::scope_exit([&] {
  13810. svr.stop();
  13811. t.join();
  13812. ASSERT_FALSE(svr.is_running());
  13813. });
  13814. svr.wait_until_ready();
  13815. Client cli(HOST, PORT);
  13816. auto res = cli.Get(
  13817. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13819. EXPECT_EQ(StatusCode::OK_200, res->status);
  13820. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13821. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13822. // and must not be selected.
  13823. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13824. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13825. }
  13826. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13827. Server svr;
  13828. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13829. std::string observed_remote_addr;
  13830. svr.Get("/ip", [&](const Request &req, Response &res) {
  13831. observed_remote_addr = req.remote_addr;
  13832. res.set_content("ok", "text/plain");
  13833. });
  13834. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13835. auto se = detail::scope_exit([&] {
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13842. // a forged address and the trusted proxy's own address; the forged value must
  13843. // not win over the address the trusted proxy actually recorded.
  13844. Client cli(HOST, PORT);
  13845. auto res = cli.Get(
  13846. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13848. EXPECT_EQ(StatusCode::OK_200, res->status);
  13849. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13850. }
  13851. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13852. Server svr;
  13853. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13854. std::string observed_remote_addr;
  13855. std::string observed_xff;
  13856. svr.Get("/ip", [&](const Request &req, Response &res) {
  13857. observed_remote_addr = req.remote_addr;
  13858. observed_xff = req.get_header_value("X-Forwarded-For");
  13859. res.set_content("ok", "text/plain");
  13860. });
  13861. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13862. auto se = detail::scope_exit([&] {
  13863. svr.stop();
  13864. t.join();
  13865. ASSERT_FALSE(svr.is_running());
  13866. });
  13867. svr.wait_until_ready();
  13868. Client cli(HOST, PORT);
  13869. auto res = cli.Get(
  13870. "/ip",
  13871. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13873. EXPECT_EQ(StatusCode::OK_200, res->status);
  13874. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13875. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13876. }
  13877. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13878. Server svr;
  13879. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13880. std::string observed_remote_addr;
  13881. std::string observed_xff;
  13882. svr.Get("/ip", [&](const Request &req, Response &res) {
  13883. observed_remote_addr = req.remote_addr;
  13884. observed_xff = req.get_header_value("X-Forwarded-For");
  13885. res.set_content("ok", "text/plain");
  13886. });
  13887. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13888. auto se = detail::scope_exit([&] {
  13889. svr.stop();
  13890. t.join();
  13891. ASSERT_FALSE(svr.is_running());
  13892. });
  13893. svr.wait_until_ready();
  13894. std::string raw_req =
  13895. "GET /ip HTTP/1.1\r\n"
  13896. "Host: localhost\r\n"
  13897. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13898. "Connection: close\r\n"
  13899. "\r\n";
  13900. std::string out;
  13901. ASSERT_TRUE(send_request(5, raw_req, &out));
  13902. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13903. // Header parser trims surrounding whitespace of the header value
  13904. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13905. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13906. }
  13907. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13908. // crash the server (it used to call front() on an empty vector inside
  13909. // get_client_ip). The connection-level remote address must be retained instead.
  13910. static void run_malformed_xff_test(const std::string &xff_value) {
  13911. Server svr;
  13912. svr.set_trusted_proxies({"192.0.2.45"});
  13913. std::string observed_remote_addr;
  13914. svr.Get("/ip", [&](const Request &req, Response &res) {
  13915. observed_remote_addr = req.remote_addr;
  13916. res.set_content("ok", "text/plain");
  13917. });
  13918. int port = 0;
  13919. thread t = thread([&]() {
  13920. port = svr.bind_to_any_port(HOST);
  13921. svr.listen_after_bind();
  13922. });
  13923. auto se = detail::scope_exit([&] {
  13924. svr.stop();
  13925. t.join();
  13926. ASSERT_FALSE(svr.is_running());
  13927. });
  13928. svr.wait_until_ready();
  13929. Client cli(HOST, port);
  13930. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13932. EXPECT_EQ(StatusCode::OK_200, res->status);
  13933. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13934. observed_remote_addr == "127.0.0.1");
  13935. }
  13936. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13937. run_malformed_xff_test("");
  13938. }
  13939. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13940. run_malformed_xff_test(",");
  13941. }
  13942. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13943. run_malformed_xff_test(", , ,");
  13944. }
  13945. #ifndef _WIN32
  13946. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13947. Server svr;
  13948. svr.Post("/post", [&](const Request &req, Response &res) {
  13949. res.set_content(req.body, "text/plain");
  13950. });
  13951. svr.Put("/put", [&](const Request &req, Response &res) {
  13952. res.set_content(req.body, "text/plain");
  13953. });
  13954. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13955. res.set_content(req.body, "text/plain");
  13956. });
  13957. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13958. res.set_content(req.body, "text/plain");
  13959. });
  13960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. });
  13966. svr.wait_until_ready();
  13967. std::string resp;
  13968. // POST without Content-Length
  13969. ASSERT_TRUE(send_request(5,
  13970. "POST /post HTTP/1.1\r\n"
  13971. "Host: localhost\r\n"
  13972. "Connection: close\r\n"
  13973. "\r\n",
  13974. &resp));
  13975. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13976. // PUT without Content-Length
  13977. resp.clear();
  13978. ASSERT_TRUE(send_request(5,
  13979. "PUT /put HTTP/1.1\r\n"
  13980. "Host: localhost\r\n"
  13981. "Connection: close\r\n"
  13982. "\r\n",
  13983. &resp));
  13984. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13985. // PATCH without Content-Length
  13986. resp.clear();
  13987. ASSERT_TRUE(send_request(5,
  13988. "PATCH /patch HTTP/1.1\r\n"
  13989. "Host: localhost\r\n"
  13990. "Connection: close\r\n"
  13991. "\r\n",
  13992. &resp));
  13993. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13994. // DELETE without Content-Length
  13995. resp.clear();
  13996. ASSERT_TRUE(send_request(5,
  13997. "DELETE /delete HTTP/1.1\r\n"
  13998. "Host: localhost\r\n"
  13999. "Connection: close\r\n"
  14000. "\r\n",
  14001. &resp));
  14002. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14003. }
  14004. #endif
  14005. //==============================================================================
  14006. // open_stream() Tests
  14007. //==============================================================================
  14008. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14009. std::string result;
  14010. char buf[8192];
  14011. ssize_t n;
  14012. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14013. result.append(buf, static_cast<size_t>(n));
  14014. }
  14015. return result;
  14016. }
  14017. // Mock stream for unit tests
  14018. class MockStream : public Stream {
  14019. public:
  14020. std::string data;
  14021. size_t pos = 0;
  14022. ssize_t error_after = -1; // -1 = no error
  14023. explicit MockStream(const std::string &d, ssize_t err = -1)
  14024. : data(d), error_after(err) {}
  14025. bool is_readable() const override { return true; }
  14026. bool wait_readable() const override { return true; }
  14027. bool wait_writable() const override { return true; }
  14028. ssize_t read(char *ptr, size_t size) override {
  14029. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14030. if (pos >= data.size()) return 0;
  14031. size_t limit =
  14032. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14033. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14034. std::memcpy(ptr, data.data() + pos, to_read);
  14035. pos += to_read;
  14036. return static_cast<ssize_t>(to_read);
  14037. }
  14038. ssize_t write(const char *, size_t) override { return -1; }
  14039. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14040. ip = "127.0.0.1";
  14041. port = 0;
  14042. }
  14043. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14044. ip = "127.0.0.1";
  14045. port = 0;
  14046. }
  14047. socket_t socket() const override { return INVALID_SOCKET; }
  14048. time_t duration() const override { return 0; }
  14049. };
  14050. TEST(StreamHandleTest, Basic) {
  14051. ClientImpl::StreamHandle handle;
  14052. EXPECT_FALSE(handle.is_valid());
  14053. handle.response = detail::make_unique<Response>();
  14054. handle.error = Error::Connection;
  14055. EXPECT_FALSE(handle.is_valid());
  14056. handle.error = Error::Success;
  14057. EXPECT_TRUE(handle.is_valid());
  14058. }
  14059. TEST(BodyReaderTest, Basic) {
  14060. MockStream stream("Hello, World!");
  14061. detail::BodyReader reader;
  14062. reader.stream = &stream;
  14063. reader.content_length = 13;
  14064. char buf[32];
  14065. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14066. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14067. EXPECT_TRUE(reader.eof);
  14068. }
  14069. TEST(BodyReaderTest, NoStream) {
  14070. detail::BodyReader reader;
  14071. char buf[32];
  14072. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14073. EXPECT_EQ(Error::Connection, reader.last_error);
  14074. }
  14075. TEST(BodyReaderTest, Error) {
  14076. MockStream stream("Hello, World!", 5);
  14077. detail::BodyReader reader;
  14078. reader.stream = &stream;
  14079. reader.content_length = 13;
  14080. char buf[32];
  14081. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14082. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14083. EXPECT_EQ(Error::Read, reader.last_error);
  14084. }
  14085. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14086. // Mock-based StreamHandle tests relying on private internals are removed.
  14087. class OpenStreamTest : public ::testing::Test {
  14088. protected:
  14089. void SetUp() override {
  14090. svr_.Get("/hello", [](const Request &, Response &res) {
  14091. res.set_content("Hello World!", "text/plain");
  14092. });
  14093. svr_.Get("/large", [](const Request &, Response &res) {
  14094. res.set_content(std::string(10000, 'X'), "text/plain");
  14095. });
  14096. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14097. res.set_content("Hello World!", "image/jpeg");
  14098. res.set_header("Content-Encoding", "UTF-8");
  14099. });
  14100. svr_.Get("/chunked", [](const Request &, Response &res) {
  14101. res.set_chunked_content_provider("text/plain",
  14102. [](size_t offset, DataSink &sink) {
  14103. if (offset < 15) {
  14104. sink.write("chunk", 5);
  14105. return true;
  14106. }
  14107. sink.done();
  14108. return true;
  14109. });
  14110. });
  14111. svr_.Get("/compressible", [](const Request &, Response &res) {
  14112. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14113. DataSink &sink) {
  14114. if (offset < 100 * 1024) {
  14115. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14116. sink.write(chunk.data(), chunk.size());
  14117. return true;
  14118. }
  14119. sink.done();
  14120. return true;
  14121. });
  14122. });
  14123. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14124. [](const Request & /*req*/, Response &res) {
  14125. auto i = new int(0);
  14126. res.set_header("Trailer", "Content-Length, X-Allowed");
  14127. res.set_chunked_content_provider(
  14128. "text/plain",
  14129. [i](size_t /*offset*/, DataSink &sink) {
  14130. switch (*i) {
  14131. case 0: sink.os << "123"; break;
  14132. case 1: sink.os << "456"; break;
  14133. case 2: sink.os << "789"; break;
  14134. case 3: {
  14135. sink.done_with_trailer(
  14136. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14137. } break;
  14138. }
  14139. (*i)++;
  14140. return true;
  14141. },
  14142. [i](bool success) {
  14143. EXPECT_TRUE(success);
  14144. delete i;
  14145. });
  14146. });
  14147. // Echo headers endpoint for header-related tests
  14148. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14149. std::string body;
  14150. for (const auto &h : req.headers) {
  14151. body.append(h.first);
  14152. body.push_back(':');
  14153. body.append(h.second);
  14154. body.push_back('\n');
  14155. }
  14156. res.set_content(body, "text/plain");
  14157. });
  14158. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14159. std::string body;
  14160. for (const auto &h : req.headers) {
  14161. body.append(h.first);
  14162. body.push_back(':');
  14163. body.append(h.second);
  14164. body.push_back('\n');
  14165. }
  14166. res.set_content(body, "text/plain");
  14167. });
  14168. port_ = svr_.bind_to_any_port("127.0.0.1");
  14169. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14170. svr_.wait_until_ready();
  14171. }
  14172. void TearDown() override {
  14173. svr_.stop();
  14174. if (thread_.joinable()) thread_.join();
  14175. }
  14176. Server svr_;
  14177. std::thread thread_;
  14178. int port_ = 0;
  14179. };
  14180. TEST_F(OpenStreamTest, Basic) {
  14181. Client cli("127.0.0.1", port_);
  14182. auto handle = cli.open_stream("GET", "/hello");
  14183. EXPECT_TRUE(handle.is_valid());
  14184. EXPECT_EQ("Hello World!", read_all(handle));
  14185. }
  14186. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14187. Client cli("127.0.0.1", port_);
  14188. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14189. ASSERT_TRUE(handle.is_valid());
  14190. EXPECT_EQ("Hello World!", read_all(handle));
  14191. }
  14192. TEST_F(OpenStreamTest, SmallBuffer) {
  14193. Client cli("127.0.0.1", port_);
  14194. auto handle = cli.open_stream("GET", "/hello");
  14195. std::string result;
  14196. char buf[4];
  14197. ssize_t n;
  14198. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14199. result.append(buf, static_cast<size_t>(n));
  14200. EXPECT_EQ("Hello World!", result);
  14201. }
  14202. TEST_F(OpenStreamTest, DefaultHeaders) {
  14203. Client cli("127.0.0.1", port_);
  14204. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14205. {
  14206. auto handle = cli.open_stream("GET", "/echo-headers");
  14207. ASSERT_TRUE(handle.is_valid());
  14208. auto body = read_all(handle);
  14209. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14210. std::string::npos);
  14211. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14212. std::string::npos);
  14213. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14214. }
  14215. // open_stream POST with body and no explicit content_type should NOT add
  14216. // text/plain Content-Type (behavior differs from non-streaming path), but
  14217. // should include Content-Length
  14218. {
  14219. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14220. ASSERT_TRUE(handle.is_valid());
  14221. auto body = read_all(handle);
  14222. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14223. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14224. }
  14225. // open_stream POST with explicit Content-Type should preserve it
  14226. {
  14227. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14228. {{"Content-Type", "application/custom"}},
  14229. "{}", "application/custom");
  14230. ASSERT_TRUE(handle.is_valid());
  14231. auto body = read_all(handle);
  14232. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14233. }
  14234. // User-specified User-Agent must not be overwritten for stream API
  14235. {
  14236. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14237. {{"User-Agent", "MyAgent/1.2"}});
  14238. ASSERT_TRUE(handle.is_valid());
  14239. auto body = read_all(handle);
  14240. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14241. }
  14242. }
  14243. TEST_F(OpenStreamTest, Large) {
  14244. Client cli("127.0.0.1", port_);
  14245. auto handle = cli.open_stream("GET", "/large");
  14246. EXPECT_EQ(10000u, read_all(handle).size());
  14247. }
  14248. TEST_F(OpenStreamTest, ConnectionError) {
  14249. Client cli("127.0.0.1", 9999);
  14250. auto handle = cli.open_stream("GET", "/hello");
  14251. EXPECT_FALSE(handle.is_valid());
  14252. }
  14253. TEST_F(OpenStreamTest, Chunked) {
  14254. Client cli("127.0.0.1", port_);
  14255. auto handle = cli.open_stream("GET", "/chunked");
  14256. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14257. "Transfer-Encoding") == "chunked");
  14258. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14259. }
  14260. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14261. Client cli("127.0.0.1", port_);
  14262. auto handle =
  14263. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14264. ASSERT_TRUE(handle.is_valid());
  14265. // Consume body to allow trailers to be received/parsed
  14266. auto body = read_all(handle);
  14267. // Explicitly parse trailers (ensure trailers are available for assertion)
  14268. handle.parse_trailers_if_needed();
  14269. EXPECT_EQ(std::string("123456789"), body);
  14270. // The response should include a Trailer header declaring both names
  14271. ASSERT_TRUE(handle.response);
  14272. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14273. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14274. handle.response->get_header_value("Trailer"));
  14275. // Prohibited trailer must not be present
  14276. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14277. // Allowed trailer should be present
  14278. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14279. EXPECT_EQ(std::string("yes"),
  14280. handle.response->get_trailer_value("X-Allowed"));
  14281. // Verify trailers are NOT present as regular headers
  14282. EXPECT_EQ(std::string(""),
  14283. handle.response->get_header_value("Content-Length"));
  14284. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14285. }
  14286. static std::thread serve_single_response(std::promise<int> &port_promise,
  14287. const std::string &response) {
  14288. return std::thread([&port_promise, response] {
  14289. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14290. default_socket_options(srv);
  14291. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14293. sockaddr_in addr{};
  14294. addr.sin_family = AF_INET;
  14295. addr.sin_port = htons(0); // Let OS assign a free port
  14296. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14297. int opt = 1;
  14298. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14299. #ifdef _WIN32
  14300. reinterpret_cast<const char *>(&opt),
  14301. #else
  14302. &opt,
  14303. #endif
  14304. sizeof(opt));
  14305. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14306. ::listen(srv, 1) != 0) {
  14307. port_promise.set_value(-1);
  14308. detail::close_socket(srv);
  14309. return;
  14310. }
  14311. socklen_t addr_len = sizeof(addr);
  14312. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14313. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14314. sockaddr_in cli_addr{};
  14315. socklen_t cli_len = sizeof(cli_addr);
  14316. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14317. if (cli != INVALID_SOCKET) {
  14318. // Read the complete HTTP request (until the blank line that terminates
  14319. // headers) before sending the response. If the server closes the socket
  14320. // while the client's request data is still unread in the kernel receive
  14321. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14322. // connection on both sides: it discards the client's receive buffer
  14323. // (which already holds our response) and causes any in-progress write on
  14324. // the client to fail with ECONNRESET. Reading all request data first
  14325. // ensures close() emits a graceful FIN.
  14326. {
  14327. char rbuf[256];
  14328. std::string req;
  14329. while (req.find("\r\n\r\n") == std::string::npos) {
  14330. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14331. if (n <= 0) { break; }
  14332. req.append(rbuf, static_cast<size_t>(n));
  14333. }
  14334. }
  14335. ::send(cli,
  14336. #ifdef _WIN32
  14337. static_cast<const char *>(response.c_str()),
  14338. static_cast<int>(response.size()),
  14339. #else
  14340. response.c_str(), response.size(),
  14341. #endif
  14342. 0);
  14343. detail::close_socket(cli);
  14344. }
  14345. detail::close_socket(srv);
  14346. });
  14347. }
  14348. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14349. #ifndef _WIN32
  14350. signal(SIGPIPE, SIG_IGN);
  14351. #endif
  14352. std::promise<int> port_promise;
  14353. auto port_future = port_promise.get_future();
  14354. auto server_thread =
  14355. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14356. "Content-Type: text/plain\r\n"
  14357. "Content-Length: not-a-number\r\n"
  14358. "Connection: close\r\n"
  14359. "\r\n"
  14360. "hello");
  14361. auto port = port_future.get();
  14362. ASSERT_GT(port, 0);
  14363. Client cli("127.0.0.1", port);
  14364. auto handle = cli.open_stream("GET", "/");
  14365. EXPECT_FALSE(handle.is_valid());
  14366. server_thread.join();
  14367. }
  14368. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14369. #ifndef _WIN32
  14370. signal(SIGPIPE, SIG_IGN);
  14371. #endif
  14372. std::promise<int> port_promise;
  14373. auto port_future = port_promise.get_future();
  14374. auto server_thread = serve_single_response(
  14375. port_promise, "HTTP/1.1 200 OK\r\n"
  14376. "Content-Type: text/plain\r\n"
  14377. "Content-Length: 99999999999999999999999999\r\n"
  14378. "Connection: close\r\n"
  14379. "\r\n"
  14380. "hello");
  14381. auto port = port_future.get();
  14382. ASSERT_GT(port, 0);
  14383. // Historically std::stoull would throw std::out_of_range here and crash
  14384. // the process, then parsing silently clamped to a bogus framing length and
  14385. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14386. // so the stream fails to open, matching the not-a-number case above. The
  14387. // process still must NOT terminate.
  14388. Client cli("127.0.0.1", port);
  14389. auto handle = cli.open_stream("GET", "/");
  14390. EXPECT_FALSE(handle.is_valid());
  14391. server_thread.join();
  14392. }
  14393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14394. TEST_F(OpenStreamTest, Gzip) {
  14395. Client cli("127.0.0.1", port_);
  14396. auto handle = cli.open_stream("GET", "/compressible", {},
  14397. {{"Accept-Encoding", "gzip"}});
  14398. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14399. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14400. }
  14401. #endif
  14402. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14403. TEST_F(OpenStreamTest, Brotli) {
  14404. Client cli("127.0.0.1", port_);
  14405. auto handle =
  14406. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14407. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14408. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14409. }
  14410. #endif
  14411. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14412. TEST_F(OpenStreamTest, Zstd) {
  14413. Client cli("127.0.0.1", port_);
  14414. auto handle = cli.open_stream("GET", "/compressible", {},
  14415. {{"Accept-Encoding", "zstd"}});
  14416. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14417. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14418. }
  14419. #endif
  14420. #ifdef CPPHTTPLIB_SSL_ENABLED
  14421. class SSLOpenStreamTest : public ::testing::Test {
  14422. protected:
  14423. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14424. void SetUp() override {
  14425. svr_.Get("/hello", [](const Request &, Response &res) {
  14426. res.set_content("Hello SSL World!", "text/plain");
  14427. });
  14428. svr_.Get("/chunked", [](const Request &, Response &res) {
  14429. res.set_chunked_content_provider("text/plain",
  14430. [](size_t offset, DataSink &sink) {
  14431. if (offset < 15) {
  14432. sink.write("chunk", 5);
  14433. return true;
  14434. }
  14435. sink.done();
  14436. return true;
  14437. });
  14438. });
  14439. svr_.Post("/echo", [](const Request &req, Response &res) {
  14440. res.set_content(req.body, req.get_header_value("Content-Type"));
  14441. });
  14442. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14443. std::string body = req.body;
  14444. res.set_chunked_content_provider(
  14445. "text/plain", [body](size_t offset, DataSink &sink) {
  14446. if (offset < body.size()) {
  14447. sink.write(body.data() + offset, body.size() - offset);
  14448. }
  14449. sink.done();
  14450. return true;
  14451. });
  14452. });
  14453. port_ = svr_.bind_to_any_port("127.0.0.1");
  14454. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14455. svr_.wait_until_ready();
  14456. }
  14457. void TearDown() override {
  14458. svr_.stop();
  14459. if (thread_.joinable()) thread_.join();
  14460. }
  14461. SSLServer svr_;
  14462. std::thread thread_;
  14463. int port_ = 0;
  14464. };
  14465. TEST_F(SSLOpenStreamTest, Basic) {
  14466. SSLClient cli("127.0.0.1", port_);
  14467. cli.enable_server_certificate_verification(false);
  14468. auto handle = cli.open_stream("GET", "/hello");
  14469. ASSERT_TRUE(handle.is_valid());
  14470. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14471. }
  14472. TEST_F(SSLOpenStreamTest, Chunked) {
  14473. SSLClient cli("127.0.0.1", port_);
  14474. cli.enable_server_certificate_verification(false);
  14475. auto handle = cli.open_stream("GET", "/chunked");
  14476. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14477. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14478. "Transfer-Encoding") == "chunked");
  14479. auto body = read_all(handle);
  14480. EXPECT_EQ("chunkchunkchunk", body);
  14481. }
  14482. TEST_F(SSLOpenStreamTest, Post) {
  14483. SSLClient cli("127.0.0.1", port_);
  14484. cli.enable_server_certificate_verification(false);
  14485. auto handle =
  14486. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14487. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14488. EXPECT_EQ(200, handle.response->status);
  14489. auto body = read_all(handle);
  14490. EXPECT_EQ("Hello SSL POST", body);
  14491. }
  14492. TEST_F(SSLOpenStreamTest, PostChunked) {
  14493. SSLClient cli("127.0.0.1", port_);
  14494. cli.enable_server_certificate_verification(false);
  14495. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14496. "Chunked SSL Data", "text/plain");
  14497. ASSERT_TRUE(handle.is_valid());
  14498. EXPECT_EQ(200, handle.response->status);
  14499. auto body = read_all(handle);
  14500. EXPECT_EQ("Chunked SSL Data", body);
  14501. }
  14502. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14503. // Content-Length is terminated by the server closing the connection. When the
  14504. // SSL peer sends a close_notify after the body, the client must treat it as a
  14505. // clean EOF and return a successful response rather than an error.
  14506. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14508. ASSERT_TRUE(svr.is_valid());
  14509. svr.set_keep_alive_max_count(1);
  14510. const std::string expected_body = "Hello from connection-close response!";
  14511. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14512. res.set_content_provider("text/plain",
  14513. [&](size_t offset, DataSink &sink) -> bool {
  14514. if (offset < expected_body.size()) {
  14515. sink.write(expected_body.data() + offset,
  14516. expected_body.size() - offset);
  14517. }
  14518. sink.done();
  14519. return true;
  14520. });
  14521. });
  14522. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14523. auto se = detail::scope_exit([&] {
  14524. svr.stop();
  14525. listen_thread.join();
  14526. ASSERT_FALSE(svr.is_running());
  14527. });
  14528. svr.wait_until_ready();
  14529. SSLClient cli(HOST, PORT);
  14530. cli.enable_server_certificate_verification(false);
  14531. auto res = cli.Get("/no-content-length");
  14532. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14533. EXPECT_EQ(StatusCode::OK_200, res->status);
  14534. EXPECT_EQ(expected_body, res->body);
  14535. }
  14536. #endif // CPPHTTPLIB_SSL_ENABLED
  14537. //==============================================================================
  14538. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14539. // results for various scenarios.
  14540. //==============================================================================
  14541. TEST(ParityTest, GetVsOpenStream) {
  14542. Server svr;
  14543. const std::string path = "/parity";
  14544. const std::string content = "Parity test content: hello world";
  14545. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14546. res.set_content(content, "text/plain");
  14547. });
  14548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14549. auto se = detail::scope_exit([&] {
  14550. svr.stop();
  14551. t.join();
  14552. ASSERT_FALSE(svr.is_running());
  14553. });
  14554. svr.wait_until_ready();
  14555. Client cli(HOST, PORT);
  14556. // Non-stream path
  14557. auto r1 = cli.Get(path);
  14558. ASSERT_TRUE(r1);
  14559. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14560. // Stream path
  14561. auto h = cli.open_stream("GET", path);
  14562. ASSERT_TRUE(h.is_valid());
  14563. EXPECT_EQ(r1->body, read_all(h));
  14564. }
  14565. // Helper to compress data with provided compressor type T
  14566. template <typename Compressor>
  14567. static std::string compress_payload_for_parity(const std::string &in) {
  14568. std::string out;
  14569. Compressor compressor;
  14570. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14571. [&](const char *data, size_t n) {
  14572. out.append(data, n);
  14573. return true;
  14574. });
  14575. EXPECT_TRUE(ok);
  14576. return out;
  14577. }
  14578. // Helper function for compression parity tests
  14579. template <typename Compressor>
  14580. static void test_compression_parity(const std::string &original,
  14581. const std::string &path,
  14582. const std::string &encoding) {
  14583. const std::string compressed =
  14584. compress_payload_for_parity<Compressor>(original);
  14585. Server svr;
  14586. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14587. res.set_content(compressed, "application/octet-stream");
  14588. res.set_header("Content-Encoding", encoding);
  14589. });
  14590. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14591. auto se = detail::scope_exit([&] {
  14592. svr.stop();
  14593. t.join();
  14594. ASSERT_FALSE(svr.is_running());
  14595. });
  14596. svr.wait_until_ready();
  14597. Client cli(HOST, PORT);
  14598. // Non-streaming
  14599. {
  14600. auto res = cli.Get(path);
  14601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14602. EXPECT_EQ(StatusCode::OK_200, res->status);
  14603. EXPECT_EQ(original, res->body);
  14604. }
  14605. // Streaming
  14606. {
  14607. auto h = cli.open_stream("GET", path);
  14608. ASSERT_TRUE(h.is_valid());
  14609. EXPECT_EQ(original, read_all(h));
  14610. }
  14611. }
  14612. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14613. TEST(ParityTest, Gzip) {
  14614. test_compression_parity<detail::gzip_compressor>(
  14615. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14616. }
  14617. #endif
  14618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14619. TEST(ParityTest, Brotli) {
  14620. test_compression_parity<detail::brotli_compressor>(
  14621. "Hello, brotli parity test payload", "/parity-br", "br");
  14622. }
  14623. #endif
  14624. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14625. TEST(ParityTest, Zstd) {
  14626. test_compression_parity<detail::zstd_compressor>(
  14627. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14628. }
  14629. #endif
  14630. //==============================================================================
  14631. // New Stream API Tests
  14632. //==============================================================================
  14633. inline std::string read_body(httplib::stream::Result &result) {
  14634. std::string body;
  14635. while (result.next()) {
  14636. body.append(result.data(), result.size());
  14637. }
  14638. return body;
  14639. }
  14640. TEST(ClientConnectionTest, Basic) {
  14641. httplib::ClientConnection conn;
  14642. EXPECT_FALSE(conn.is_open());
  14643. conn.sock = 1;
  14644. EXPECT_TRUE(conn.is_open());
  14645. httplib::ClientConnection conn2(std::move(conn));
  14646. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14647. conn2.sock = INVALID_SOCKET;
  14648. }
  14649. // Unified test server for all stream::* tests
  14650. class StreamApiTest : public ::testing::Test {
  14651. protected:
  14652. void SetUp() override {
  14653. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14654. res.set_content("Hello World!", "text/plain");
  14655. });
  14656. svr_.Get("/echo-params",
  14657. [](const httplib::Request &req, httplib::Response &res) {
  14658. std::string r;
  14659. for (const auto &p : req.params) {
  14660. if (!r.empty()) r += "&";
  14661. r += p.first + "=" + p.second;
  14662. }
  14663. res.set_content(r, "text/plain");
  14664. });
  14665. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14666. res.set_content(req.body, req.get_header_value("Content-Type"));
  14667. });
  14668. svr_.Post("/echo-headers",
  14669. [](const httplib::Request &req, httplib::Response &res) {
  14670. std::string r;
  14671. for (const auto &h : req.headers)
  14672. r += h.first + ": " + h.second + "\n";
  14673. res.set_content(r, "text/plain");
  14674. });
  14675. svr_.Post("/echo-params",
  14676. [](const httplib::Request &req, httplib::Response &res) {
  14677. std::string r = "params:";
  14678. for (const auto &p : req.params)
  14679. r += p.first + "=" + p.second + ";";
  14680. res.set_content(r + " body:" + req.body, "text/plain");
  14681. });
  14682. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14683. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14684. });
  14685. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14686. res.set_content("PUT:" + req.body, "text/plain");
  14687. });
  14688. svr_.Patch("/echo",
  14689. [](const httplib::Request &req, httplib::Response &res) {
  14690. res.set_content("PATCH:" + req.body, "text/plain");
  14691. });
  14692. svr_.Delete(
  14693. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14694. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14695. "text/plain");
  14696. });
  14697. svr_.Get("/head-test",
  14698. [](const httplib::Request &, httplib::Response &res) {
  14699. res.set_content("body for HEAD", "text/plain");
  14700. });
  14701. svr_.Options("/options",
  14702. [](const httplib::Request &, httplib::Response &res) {
  14703. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14704. });
  14705. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14706. svr_.wait_until_ready();
  14707. }
  14708. void TearDown() override {
  14709. svr_.stop();
  14710. if (thread_.joinable()) thread_.join();
  14711. }
  14712. httplib::Server svr_;
  14713. std::thread thread_;
  14714. };
  14715. // stream::Get tests
  14716. TEST_F(StreamApiTest, GetBasic) {
  14717. httplib::Client cli(HOST, PORT);
  14718. auto result = httplib::stream::Get(cli, "/hello");
  14719. ASSERT_TRUE(result.is_valid());
  14720. EXPECT_EQ(200, result.status());
  14721. EXPECT_EQ("Hello World!", read_body(result));
  14722. }
  14723. TEST_F(StreamApiTest, GetWithParams) {
  14724. httplib::Client cli(HOST, PORT);
  14725. httplib::Params params{{"foo", "bar"}};
  14726. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14727. ASSERT_TRUE(result.is_valid());
  14728. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14729. }
  14730. TEST_F(StreamApiTest, GetConnectionError) {
  14731. httplib::Client cli(HOST, 9999);
  14732. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14733. }
  14734. TEST_F(StreamApiTest, Get404) {
  14735. httplib::Client cli(HOST, PORT);
  14736. auto result = httplib::stream::Get(cli, "/nonexistent");
  14737. EXPECT_TRUE(result.is_valid());
  14738. EXPECT_EQ(404, result.status());
  14739. }
  14740. // stream::Post tests
  14741. TEST_F(StreamApiTest, PostBasic) {
  14742. httplib::Client cli(HOST, PORT);
  14743. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14744. "application/json");
  14745. ASSERT_TRUE(result.is_valid());
  14746. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14747. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14748. }
  14749. TEST_F(StreamApiTest, PostWithHeaders) {
  14750. httplib::Client cli(HOST, PORT);
  14751. httplib::Headers headers{{"X-Custom", "value"}};
  14752. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14753. "text/plain");
  14754. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14755. }
  14756. TEST_F(StreamApiTest, PostWithParams) {
  14757. httplib::Client cli(HOST, PORT);
  14758. httplib::Params params{{"k", "v"}};
  14759. auto result =
  14760. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14761. auto body = read_body(result);
  14762. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14763. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14764. }
  14765. TEST_F(StreamApiTest, PostLarge) {
  14766. httplib::Client cli(HOST, PORT);
  14767. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14768. size_t total = 0;
  14769. while (result.next()) {
  14770. total += result.size();
  14771. }
  14772. EXPECT_EQ(100u * 1024u, total);
  14773. }
  14774. // stream::Put/Patch tests
  14775. TEST_F(StreamApiTest, PutAndPatch) {
  14776. httplib::Client cli(HOST, PORT);
  14777. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14778. EXPECT_EQ("PUT:test", read_body(put));
  14779. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14780. EXPECT_EQ("PATCH:test", read_body(patch));
  14781. }
  14782. // stream::Delete tests
  14783. TEST_F(StreamApiTest, Delete) {
  14784. httplib::Client cli(HOST, PORT);
  14785. auto del1 = httplib::stream::Delete(cli, "/resource");
  14786. EXPECT_EQ("Deleted", read_body(del1));
  14787. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14788. EXPECT_EQ("Deleted:data", read_body(del2));
  14789. }
  14790. // stream::Head/Options tests
  14791. TEST_F(StreamApiTest, HeadAndOptions) {
  14792. httplib::Client cli(HOST, PORT);
  14793. auto head = httplib::stream::Head(cli, "/head-test");
  14794. EXPECT_TRUE(head.is_valid());
  14795. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14796. auto opts = httplib::stream::Options(cli, "/options");
  14797. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14798. }
  14799. // SSL stream::* tests
  14800. #ifdef CPPHTTPLIB_SSL_ENABLED
  14801. class SSLStreamApiTest : public ::testing::Test {
  14802. protected:
  14803. void SetUp() override {
  14804. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14805. res.set_content("Hello SSL!", "text/plain");
  14806. });
  14807. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14808. res.set_content(req.body, "text/plain");
  14809. });
  14810. port_ = svr_.bind_to_any_port("127.0.0.1");
  14811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14812. svr_.wait_until_ready();
  14813. }
  14814. void TearDown() override {
  14815. svr_.stop();
  14816. if (thread_.joinable()) thread_.join();
  14817. }
  14818. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14819. std::thread thread_;
  14820. int port_ = 0;
  14821. };
  14822. TEST_F(SSLStreamApiTest, GetAndPost) {
  14823. httplib::SSLClient cli("127.0.0.1", port_);
  14824. cli.enable_server_certificate_verification(false);
  14825. auto get = httplib::stream::Get(cli, "/hello");
  14826. EXPECT_EQ("Hello SSL!", read_body(get));
  14827. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14828. EXPECT_EQ("test", read_body(post));
  14829. }
  14830. #endif
  14831. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14832. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14833. // BodyReader
  14834. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14835. // Test that read timeout during streaming is detected
  14836. // Use a large content-length response where server delays mid-stream
  14837. Server svr;
  14838. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14839. // Send a large response with delay in the middle
  14840. res.set_content_provider(
  14841. 1000, // content_length
  14842. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14843. if (offset < 100) {
  14844. // Send first 100 bytes immediately
  14845. std::string data(100, 'A');
  14846. sink.write(data.c_str(), data.size());
  14847. return true;
  14848. }
  14849. // Then delay longer than client timeout
  14850. std::this_thread::sleep_for(std::chrono::seconds(3));
  14851. std::string data(900, 'B');
  14852. sink.write(data.c_str(), data.size());
  14853. return true;
  14854. });
  14855. });
  14856. auto port = 8091;
  14857. std::thread t([&]() { svr.listen("localhost", port); });
  14858. svr.wait_until_ready();
  14859. Client cli("localhost", port);
  14860. cli.set_read_timeout(1, 0); // 1 second timeout
  14861. auto handle = cli.open_stream("GET", "/slow-stream");
  14862. ASSERT_TRUE(handle.is_valid());
  14863. char buf[256];
  14864. ssize_t total = 0;
  14865. ssize_t n;
  14866. bool got_error = false;
  14867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14868. total += n;
  14869. }
  14870. if (n < 0) {
  14871. got_error = true;
  14872. // Should be timeout or read error
  14873. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14874. handle.get_read_error() == Error::Read)
  14875. << "Actual error: " << to_string(handle.get_read_error());
  14876. }
  14877. // Either we got an error, or we got less data than expected
  14878. EXPECT_TRUE(got_error || total < 1000)
  14879. << "Expected timeout but got all " << total << " bytes";
  14880. svr.stop();
  14881. t.join();
  14882. }
  14883. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14884. // Test connection closed detection via BodyReader
  14885. Server svr;
  14886. std::atomic<bool> close_now{false};
  14887. svr.Get("/will-close", [&](const Request &, Response &res) {
  14888. res.set_content_provider(
  14889. 10000, // Large content_length that we won't fully send
  14890. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14891. if (offset < 100) {
  14892. std::string data(100, 'X');
  14893. sink.write(data.c_str(), data.size());
  14894. return true;
  14895. }
  14896. // Wait for signal then abort
  14897. while (!close_now) {
  14898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14899. }
  14900. return false; // Abort - server will close connection
  14901. });
  14902. });
  14903. auto port = 8092;
  14904. std::thread t([&]() { svr.listen("localhost", port); });
  14905. svr.wait_until_ready();
  14906. Client cli("localhost", port);
  14907. auto handle = cli.open_stream("GET", "/will-close");
  14908. ASSERT_TRUE(handle.is_valid());
  14909. char buf[256];
  14910. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14911. EXPECT_GT(n, 0) << "First read should succeed";
  14912. // Signal server to close
  14913. close_now = true;
  14914. // Keep reading until error or EOF
  14915. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14916. // Keep reading
  14917. }
  14918. // Should get an error since content_length wasn't satisfied
  14919. if (n < 0) {
  14920. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14921. handle.get_read_error() == Error::Read)
  14922. << "Actual error: " << to_string(handle.get_read_error());
  14923. }
  14924. svr.stop();
  14925. t.join();
  14926. }
  14927. #ifdef CPPHTTPLIB_SSL_ENABLED
  14928. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14929. // Test that read timeout during SSL streaming is detected
  14930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14931. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14932. res.set_content_provider(
  14933. 1000, "text/plain",
  14934. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14935. if (offset < 100) {
  14936. std::string data(100, 'A');
  14937. sink.write(data.c_str(), data.size());
  14938. return true;
  14939. }
  14940. std::this_thread::sleep_for(std::chrono::seconds(3));
  14941. std::string data(900, 'B');
  14942. sink.write(data.c_str(), data.size());
  14943. return true;
  14944. });
  14945. });
  14946. auto port = 8093;
  14947. std::thread t([&]() { svr.listen("localhost", port); });
  14948. svr.wait_until_ready();
  14949. SSLClient cli("localhost", port);
  14950. cli.enable_server_certificate_verification(false);
  14951. cli.set_read_timeout(1, 0); // 1 second timeout
  14952. auto handle = cli.open_stream("GET", "/slow-stream");
  14953. ASSERT_TRUE(handle.is_valid());
  14954. char buf[256];
  14955. ssize_t total = 0;
  14956. ssize_t n;
  14957. bool got_error = false;
  14958. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14959. total += n;
  14960. }
  14961. if (n < 0) {
  14962. got_error = true;
  14963. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14964. handle.get_read_error() == Error::Read)
  14965. << "Actual error: " << to_string(handle.get_read_error());
  14966. }
  14967. EXPECT_TRUE(got_error || total < 1000)
  14968. << "Expected timeout but got all " << total << " bytes";
  14969. svr.stop();
  14970. t.join();
  14971. }
  14972. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14973. // Test SSL connection closed detection
  14974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14975. std::atomic<bool> close_now{false};
  14976. svr.Get("/will-close", [&](const Request &, Response &res) {
  14977. res.set_content_provider(
  14978. 10000, "text/plain",
  14979. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14980. if (offset < 100) {
  14981. std::string data(100, 'X');
  14982. sink.write(data.c_str(), data.size());
  14983. return true;
  14984. }
  14985. while (!close_now) {
  14986. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14987. }
  14988. return false;
  14989. });
  14990. });
  14991. auto port = 8094;
  14992. std::thread t([&]() { svr.listen("localhost", port); });
  14993. svr.wait_until_ready();
  14994. SSLClient cli("localhost", port);
  14995. cli.enable_server_certificate_verification(false);
  14996. auto handle = cli.open_stream("GET", "/will-close");
  14997. ASSERT_TRUE(handle.is_valid());
  14998. char buf[256];
  14999. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15000. EXPECT_GT(n, 0);
  15001. // Signal server to close
  15002. close_now = true;
  15003. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15004. // Keep reading
  15005. }
  15006. if (n < 0) {
  15007. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15008. handle.get_read_error() == Error::Read)
  15009. << "Actual error: " << to_string(handle.get_read_error());
  15010. }
  15011. svr.stop();
  15012. t.join();
  15013. }
  15014. #endif
  15015. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15016. using namespace httplib;
  15017. // Create a test file
  15018. const char *fname = "etag_testfile.txt";
  15019. const char *content = "etag-content";
  15020. {
  15021. std::ofstream ofs(fname);
  15022. ofs << content;
  15023. ASSERT_TRUE(ofs.good());
  15024. }
  15025. Server svr;
  15026. svr.set_mount_point("/static", ".");
  15027. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15028. svr.wait_until_ready();
  15029. Client cli(HOST, PORT);
  15030. // First request: should get 200 with ETag header
  15031. auto res1 = cli.Get("/static/etag_testfile.txt");
  15032. ASSERT_TRUE(res1);
  15033. ASSERT_EQ(200, res1->status);
  15034. ASSERT_TRUE(res1->has_header("ETag"));
  15035. std::string etag = res1->get_header_value("ETag");
  15036. EXPECT_FALSE(etag.empty());
  15037. // Verify ETag format: W/"hex-hex"
  15038. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15039. EXPECT_EQ('W', etag[0]);
  15040. EXPECT_EQ('/', etag[1]);
  15041. EXPECT_EQ('"', etag[2]);
  15042. EXPECT_EQ('"', etag.back());
  15043. // Exact match: expect 304 Not Modified
  15044. Headers h2 = {{"If-None-Match", etag}};
  15045. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15046. ASSERT_TRUE(res2);
  15047. EXPECT_EQ(304, res2->status);
  15048. // Wildcard match: expect 304 Not Modified
  15049. Headers h3 = {{"If-None-Match", "*"}};
  15050. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15051. ASSERT_TRUE(res3);
  15052. EXPECT_EQ(304, res3->status);
  15053. // Non-matching ETag: expect 200
  15054. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15055. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15056. ASSERT_TRUE(res4);
  15057. EXPECT_EQ(200, res4->status);
  15058. // Multiple ETags with one matching: expect 304
  15059. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15060. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15061. ASSERT_TRUE(res5);
  15062. EXPECT_EQ(304, res5->status);
  15063. svr.stop();
  15064. t.join();
  15065. std::remove(fname);
  15066. }
  15067. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15068. using namespace httplib;
  15069. Server svr;
  15070. svr.set_mount_point("/static", ".");
  15071. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15072. svr.wait_until_ready();
  15073. Client cli(HOST, PORT);
  15074. // Send If-None-Match: * to a non-existent file
  15075. Headers h = {{"If-None-Match", "*"}};
  15076. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. EXPECT_EQ(404, res->status);
  15079. svr.stop();
  15080. t.join();
  15081. }
  15082. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15083. using namespace httplib;
  15084. // Create a test file
  15085. const char *fname = "etag_boundary_testfile.txt";
  15086. const char *content = "boundary-test";
  15087. {
  15088. std::ofstream ofs(fname);
  15089. ofs << content;
  15090. ASSERT_TRUE(ofs.good());
  15091. }
  15092. Server svr;
  15093. svr.set_mount_point("/static", ".");
  15094. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15095. svr.wait_until_ready();
  15096. Client cli(HOST, PORT);
  15097. // Get the actual ETag
  15098. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15099. ASSERT_TRUE(res1);
  15100. ASSERT_EQ(200, res1->status);
  15101. ASSERT_TRUE(res1->has_header("ETag"));
  15102. std::string etag = res1->get_header_value("ETag");
  15103. // Test 1: Very long ETag value (longer than actual ETag)
  15104. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15105. Headers h1 = {{"If-None-Match", "W/"
  15106. "\"very-long-etag-value-that-is-much-longer-"
  15107. "than-the-actual-etag-value\""}};
  15108. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15109. ASSERT_TRUE(res2);
  15110. EXPECT_EQ(200, res2->status); // Should not match
  15111. // Test 2: Long string followed by wildcard
  15112. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15113. // string)
  15114. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15115. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15116. ASSERT_TRUE(res3);
  15117. EXPECT_EQ(304, res3->status); // Should match on "*"
  15118. // Test 3: Wildcard followed by long string
  15119. // Should match on "*" immediately and return 304
  15120. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15121. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15122. ASSERT_TRUE(res4);
  15123. EXPECT_EQ(304, res4->status); // Should match on "*"
  15124. // Test 4: Multiple long non-matching values
  15125. // Should NOT match and return 200 (test that all comparisons are safe)
  15126. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15127. "W/\"second-long-non-matching-value\", "
  15128. "W/\"third-long-non-matching-value\""}};
  15129. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15130. ASSERT_TRUE(res5);
  15131. EXPECT_EQ(200, res5->status); // Should not match
  15132. // Test 5: Single character that is not "*" (edge case)
  15133. Headers h5 = {{"If-None-Match", "X"}};
  15134. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15135. ASSERT_TRUE(res6);
  15136. EXPECT_EQ(200, res6->status); // Should not match
  15137. svr.stop();
  15138. t.join();
  15139. std::remove(fname);
  15140. }
  15141. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15142. using namespace httplib;
  15143. // Create a test file
  15144. const char *fname = "ims_testfile.txt";
  15145. const char *content = "if-modified-since-test";
  15146. {
  15147. std::ofstream ofs(fname);
  15148. ofs << content;
  15149. ASSERT_TRUE(ofs.good());
  15150. }
  15151. Server svr;
  15152. svr.set_mount_point("/static", ".");
  15153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15154. svr.wait_until_ready();
  15155. Client cli(HOST, PORT);
  15156. // First request: should get 200 with Last-Modified header
  15157. auto res1 = cli.Get("/static/ims_testfile.txt");
  15158. ASSERT_TRUE(res1);
  15159. ASSERT_EQ(200, res1->status);
  15160. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15161. std::string last_modified = res1->get_header_value("Last-Modified");
  15162. EXPECT_FALSE(last_modified.empty());
  15163. // If-Modified-Since with same time: expect 304
  15164. Headers h2 = {{"If-Modified-Since", last_modified}};
  15165. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15166. ASSERT_TRUE(res2);
  15167. EXPECT_EQ(304, res2->status);
  15168. // If-Modified-Since with future time: expect 304
  15169. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15170. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15171. ASSERT_TRUE(res3);
  15172. EXPECT_EQ(304, res3->status);
  15173. // If-Modified-Since with past time: expect 200
  15174. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15175. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15176. ASSERT_TRUE(res4);
  15177. EXPECT_EQ(200, res4->status);
  15178. // If-None-Match takes precedence over If-Modified-Since
  15179. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15180. ASSERT_TRUE(res1->has_header("ETag"));
  15181. std::string etag = res1->get_header_value("ETag");
  15182. Headers h5 = {{"If-None-Match", etag},
  15183. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15184. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15185. ASSERT_TRUE(res5);
  15186. EXPECT_EQ(304, res5->status);
  15187. svr.stop();
  15188. t.join();
  15189. std::remove(fname);
  15190. }
  15191. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15192. using namespace httplib;
  15193. Server svr;
  15194. // Endpoint that returns compressible content
  15195. svr.Get("/compressible", [](const Request &, Response &res) {
  15196. // Return a large enough body to trigger compression
  15197. std::string body(1000, 'a');
  15198. res.set_content(body, "text/plain");
  15199. });
  15200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15201. svr.wait_until_ready();
  15202. Client cli(HOST, PORT);
  15203. // Request with gzip support: should get Vary header when compressed
  15204. cli.set_compress(true);
  15205. auto res1 = cli.Get("/compressible");
  15206. ASSERT_TRUE(res1);
  15207. EXPECT_EQ(200, res1->status);
  15208. // If Content-Encoding is set, Vary should also be set
  15209. if (res1->has_header("Content-Encoding")) {
  15210. EXPECT_TRUE(res1->has_header("Vary"));
  15211. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15212. }
  15213. // Request without Accept-Encoding header: should not have compression
  15214. Headers h_no_compress;
  15215. auto res2 = cli.Get("/compressible", h_no_compress);
  15216. ASSERT_TRUE(res2);
  15217. EXPECT_EQ(200, res2->status);
  15218. // Verify Vary header is present when compression is applied
  15219. // (the exact behavior depends on server configuration)
  15220. svr.stop();
  15221. t.join();
  15222. }
  15223. TEST(ETagTest, IfRangeWithETag) {
  15224. using namespace httplib;
  15225. // Create a test file with known content
  15226. const char *fname = "if_range_testfile.txt";
  15227. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15228. {
  15229. std::ofstream ofs(fname);
  15230. ofs << content;
  15231. ASSERT_TRUE(ofs.good());
  15232. }
  15233. Server svr;
  15234. svr.set_mount_point("/static", ".");
  15235. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15236. svr.wait_until_ready();
  15237. Client cli(HOST, PORT);
  15238. // First request: get ETag
  15239. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15240. ASSERT_TRUE(res1);
  15241. ASSERT_EQ(200, res1->status);
  15242. ASSERT_TRUE(res1->has_header("ETag"));
  15243. std::string etag = res1->get_header_value("ETag");
  15244. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15245. // Since our server generates weak ETags (W/"..."), If-Range with our
  15246. // ETag should NOT result in partial content - it should return full content.
  15247. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15248. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15249. ASSERT_TRUE(res2);
  15250. // Weak ETag in If-Range -> full content (200), not partial (206)
  15251. EXPECT_EQ(200, res2->status);
  15252. EXPECT_EQ(content, res2->body);
  15253. EXPECT_FALSE(res2->has_header("Content-Range"));
  15254. // Range request with non-matching If-Range (ETag): should get 200 (full
  15255. // content)
  15256. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15257. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15258. ASSERT_TRUE(res3);
  15259. EXPECT_EQ(200, res3->status);
  15260. EXPECT_EQ(content, res3->body);
  15261. EXPECT_FALSE(res3->has_header("Content-Range"));
  15262. // Range request with strong ETag (hypothetical - our server doesn't generate
  15263. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15264. // should return full content)
  15265. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15266. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15267. ASSERT_TRUE(res4);
  15268. EXPECT_EQ(200, res4->status);
  15269. EXPECT_EQ(content, res4->body);
  15270. EXPECT_FALSE(res4->has_header("Content-Range"));
  15271. svr.stop();
  15272. t.join();
  15273. std::remove(fname);
  15274. }
  15275. TEST(ETagTest, IfRangeWithDate) {
  15276. using namespace httplib;
  15277. // Create a test file
  15278. const char *fname = "if_range_date_testfile.txt";
  15279. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15280. {
  15281. std::ofstream ofs(fname);
  15282. ofs << content;
  15283. ASSERT_TRUE(ofs.good());
  15284. }
  15285. Server svr;
  15286. svr.set_mount_point("/static", ".");
  15287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15288. svr.wait_until_ready();
  15289. Client cli(HOST, PORT);
  15290. // First request: get Last-Modified
  15291. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15292. ASSERT_TRUE(res1);
  15293. ASSERT_EQ(200, res1->status);
  15294. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15295. std::string last_modified = res1->get_header_value("Last-Modified");
  15296. // Range request with matching If-Range (date): should get 206
  15297. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15298. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15299. ASSERT_TRUE(res2);
  15300. EXPECT_EQ(206, res2->status);
  15301. EXPECT_EQ("FGHIJ", res2->body);
  15302. // Range request with old If-Range date: should get 200 (full content)
  15303. Headers h3 = {{"Range", "bytes=5-9"},
  15304. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15305. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15306. ASSERT_TRUE(res3);
  15307. EXPECT_EQ(200, res3->status);
  15308. EXPECT_EQ(content, res3->body);
  15309. // Range request with future If-Range date: should get 206
  15310. Headers h4 = {{"Range", "bytes=0-4"},
  15311. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15312. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15313. ASSERT_TRUE(res4);
  15314. EXPECT_EQ(206, res4->status);
  15315. EXPECT_EQ("ABCDE", res4->body);
  15316. svr.stop();
  15317. t.join();
  15318. std::remove(fname);
  15319. }
  15320. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15321. using namespace httplib;
  15322. const char *fname = "etag_malformed.txt";
  15323. const char *content = "malformed-etag";
  15324. {
  15325. std::ofstream ofs(fname);
  15326. ofs << content;
  15327. ASSERT_TRUE(ofs.good());
  15328. }
  15329. Server svr;
  15330. svr.set_mount_point("/static", ".");
  15331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15332. svr.wait_until_ready();
  15333. Client cli(HOST, PORT);
  15334. // baseline: should get 200 and an ETag
  15335. auto res1 = cli.Get("/static/etag_malformed.txt");
  15336. ASSERT_TRUE(res1);
  15337. ASSERT_EQ(200, res1->status);
  15338. ASSERT_TRUE(res1->has_header("ETag"));
  15339. // Malformed ETag value (missing quotes) should be treated as non-matching
  15340. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15341. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15342. ASSERT_TRUE(res_bad);
  15343. EXPECT_EQ(200, res_bad->status);
  15344. // Whitespace-only header value should be considered invalid / non-matching
  15345. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15346. "Host: localhost\r\n"
  15347. "If-None-Match: \r\n"
  15348. "Connection: close\r\n"
  15349. "\r\n";
  15350. std::string out;
  15351. ASSERT_TRUE(send_request(5, raw_req, &out));
  15352. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15353. svr.stop();
  15354. t.join();
  15355. std::remove(fname);
  15356. }
  15357. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15358. using namespace httplib;
  15359. const char *fname = "ims_invalid_format.txt";
  15360. const char *content = "ims-bad-format";
  15361. {
  15362. std::ofstream ofs(fname);
  15363. ofs << content;
  15364. ASSERT_TRUE(ofs.good());
  15365. }
  15366. Server svr;
  15367. svr.set_mount_point("/static", ".");
  15368. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15369. svr.wait_until_ready();
  15370. Client cli(HOST, PORT);
  15371. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15372. ASSERT_TRUE(res1);
  15373. ASSERT_EQ(200, res1->status);
  15374. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15375. // If-Modified-Since with invalid format should not result in 304
  15376. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15377. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15378. ASSERT_TRUE(res_bad);
  15379. EXPECT_EQ(200, res_bad->status);
  15380. // If-Range with invalid date format should be treated as mismatch -> full
  15381. // content (200)
  15382. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15383. {"If-Range", "invalid-date"}};
  15384. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15385. ASSERT_TRUE(res_ifrange);
  15386. EXPECT_EQ(200, res_ifrange->status);
  15387. svr.stop();
  15388. t.join();
  15389. std::remove(fname);
  15390. }
  15391. TEST(ETagTest, IfRangeWithMalformedETag) {
  15392. using namespace httplib;
  15393. const char *fname = "ifrange_malformed.txt";
  15394. const std::string content = "0123456789";
  15395. {
  15396. std::ofstream ofs(fname);
  15397. ofs << content;
  15398. ASSERT_TRUE(ofs.good());
  15399. }
  15400. Server svr;
  15401. svr.set_mount_point("/static", ".");
  15402. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15403. svr.wait_until_ready();
  15404. Client cli(HOST, PORT);
  15405. // First request: get ETag
  15406. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15407. ASSERT_TRUE(res1);
  15408. ASSERT_EQ(200, res1->status);
  15409. ASSERT_TRUE(res1->has_header("ETag"));
  15410. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15411. // full content (200)
  15412. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15413. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15414. ASSERT_TRUE(res2);
  15415. EXPECT_EQ(200, res2->status);
  15416. EXPECT_EQ(content, res2->body);
  15417. svr.stop();
  15418. t.join();
  15419. std::remove(fname);
  15420. }
  15421. TEST(ETagTest, ExtremeLargeDateValues) {
  15422. using namespace httplib;
  15423. const char *fname = "ims_extreme_date.txt";
  15424. const char *content = "ims-extreme-date";
  15425. {
  15426. std::ofstream ofs(fname);
  15427. ofs << content;
  15428. ASSERT_TRUE(ofs.good());
  15429. }
  15430. Server svr;
  15431. svr.set_mount_point("/static", ".");
  15432. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15433. svr.wait_until_ready();
  15434. Client cli(HOST, PORT);
  15435. auto res1 = cli.Get(std::string("/static/") + fname);
  15436. ASSERT_TRUE(res1);
  15437. ASSERT_EQ(200, res1->status);
  15438. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15439. // Extremely large year that may overflow date parsing routines.
  15440. Headers h_large_date = {
  15441. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15442. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15443. ASSERT_TRUE(res_bad);
  15444. // Expect server to treat this as invalid/mismatch and return full content
  15445. EXPECT_EQ(200, res_bad->status);
  15446. // If-Range with extremely large date should be treated as mismatch -> full
  15447. // content (200)
  15448. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15449. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15450. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15451. ASSERT_TRUE(res_ifrange);
  15452. EXPECT_EQ(200, res_ifrange->status);
  15453. svr.stop();
  15454. t.join();
  15455. std::remove(fname);
  15456. }
  15457. TEST(ETagTest, NegativeFileModificationTime) {
  15458. using namespace httplib;
  15459. const char *fname = "ims_negative_mtime.txt";
  15460. const std::string content = "negative-mtime";
  15461. {
  15462. std::ofstream ofs(fname);
  15463. ofs << content;
  15464. ASSERT_TRUE(ofs.good());
  15465. }
  15466. // Try to set file mtime to a negative value. This may fail on some
  15467. // platforms/filesystems; if it fails, the test will still verify server
  15468. // behaves safely by performing a regular conditional request.
  15469. #if defined(__APPLE__) || defined(__linux__)
  15470. bool set_negative = false;
  15471. do {
  15472. struct timeval times[2];
  15473. // access time: now
  15474. times[0].tv_sec = time(nullptr);
  15475. times[0].tv_usec = 0;
  15476. // modification time: negative (e.g., -1)
  15477. times[1].tv_sec = -1;
  15478. times[1].tv_usec = 0;
  15479. if (utimes(fname, times) == 0) { set_negative = true; }
  15480. } while (0);
  15481. #else
  15482. bool set_negative = false;
  15483. #endif
  15484. Server svr;
  15485. svr.set_mount_point("/static", ".");
  15486. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15487. svr.wait_until_ready();
  15488. Client cli(HOST, PORT);
  15489. auto res1 = cli.Get(std::string("/static/") + fname);
  15490. ASSERT_TRUE(res1);
  15491. ASSERT_EQ(200, res1->status);
  15492. bool has_last_modified = res1->has_header("Last-Modified");
  15493. std::string last_modified;
  15494. if (has_last_modified) {
  15495. last_modified = res1->get_header_value("Last-Modified");
  15496. }
  15497. if (set_negative) {
  15498. // If we successfully set a negative mtime, ensure server returns a
  15499. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15500. // with an old date and ensure server handles it without crash.
  15501. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15502. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15503. ASSERT_TRUE(res2);
  15504. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15505. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15506. } else {
  15507. // Could not set negative mtime on this platform; fall back to verifying
  15508. // that normal invalid/malformed dates are treated safely (non-304).
  15509. Headers h_bad_date = {
  15510. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15511. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15512. ASSERT_TRUE(res_bad);
  15513. EXPECT_EQ(200, res_bad->status);
  15514. }
  15515. svr.stop();
  15516. t.join();
  15517. std::remove(fname);
  15518. }
  15519. //==============================================================================
  15520. // SSE Parsing Tests
  15521. //==============================================================================
  15522. class SSEParsingTest : public ::testing::Test {
  15523. protected:
  15524. // Test helper that mimics SSE parsing behavior
  15525. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15526. int &retry_ms) {
  15527. // Blank line signals end of event
  15528. if (line.empty() || line == "\r") { return true; }
  15529. // Lines starting with ':' are comments (ignored)
  15530. if (!line.empty() && line[0] == ':') { return false; }
  15531. // Find the colon separator
  15532. auto colon_pos = line.find(':');
  15533. if (colon_pos == std::string::npos) {
  15534. // Line with no colon is treated as field name with empty value
  15535. return false;
  15536. }
  15537. std::string field = line.substr(0, colon_pos);
  15538. std::string value;
  15539. // Value starts after colon, skip optional single space
  15540. if (colon_pos + 1 < line.size()) {
  15541. size_t value_start = colon_pos + 1;
  15542. if (line[value_start] == ' ') { value_start++; }
  15543. value = line.substr(value_start);
  15544. // Remove trailing \r if present
  15545. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15546. }
  15547. // Handle known fields
  15548. if (field == "event") {
  15549. msg.event = value;
  15550. } else if (field == "data") {
  15551. // Multiple data lines are concatenated with newlines
  15552. if (!msg.data.empty()) { msg.data += "\n"; }
  15553. msg.data += value;
  15554. } else if (field == "id") {
  15555. // Empty id is valid (clears the last event ID)
  15556. msg.id = value;
  15557. } else if (field == "retry") {
  15558. // Parse retry interval in milliseconds
  15559. {
  15560. int v = 0;
  15561. auto res =
  15562. detail::from_chars(value.data(), value.data() + value.size(), v);
  15563. if (res.ec == std::errc{}) { retry_ms = v; }
  15564. }
  15565. }
  15566. // Unknown fields are ignored per SSE spec
  15567. return false;
  15568. }
  15569. };
  15570. // Test: Single-line data
  15571. TEST_F(SSEParsingTest, SingleLineData) {
  15572. sse::SSEMessage msg;
  15573. int retry_ms = 3000;
  15574. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15575. EXPECT_EQ(msg.data, "hello");
  15576. EXPECT_EQ(msg.event, "message");
  15577. // Blank line ends event
  15578. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15579. }
  15580. // Test: Multi-line data
  15581. TEST_F(SSEParsingTest, MultiLineData) {
  15582. sse::SSEMessage msg;
  15583. int retry_ms = 3000;
  15584. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15585. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15586. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15587. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15588. }
  15589. // Test: Custom event types
  15590. TEST_F(SSEParsingTest, CustomEventType) {
  15591. sse::SSEMessage msg;
  15592. int retry_ms = 3000;
  15593. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15594. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15595. EXPECT_EQ(msg.event, "update");
  15596. EXPECT_EQ(msg.data, "payload");
  15597. }
  15598. // Test: Event ID handling
  15599. TEST_F(SSEParsingTest, EventIdHandling) {
  15600. sse::SSEMessage msg;
  15601. int retry_ms = 3000;
  15602. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15603. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15604. EXPECT_EQ(msg.id, "12345");
  15605. }
  15606. // Test: Empty event ID (clears last event ID)
  15607. TEST_F(SSEParsingTest, EmptyEventId) {
  15608. sse::SSEMessage msg;
  15609. msg.id = "previous";
  15610. int retry_ms = 3000;
  15611. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15612. EXPECT_EQ(msg.id, "");
  15613. }
  15614. // Test: Retry field parsing
  15615. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15616. sse::SSEMessage msg;
  15617. int retry_ms = 3000;
  15618. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15619. EXPECT_EQ(retry_ms, 5000);
  15620. }
  15621. // Test: Invalid retry value
  15622. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15623. sse::SSEMessage msg;
  15624. int retry_ms = 3000;
  15625. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15626. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15627. }
  15628. // Test: Comments (lines starting with :)
  15629. TEST_F(SSEParsingTest, CommentsIgnored) {
  15630. sse::SSEMessage msg;
  15631. int retry_ms = 3000;
  15632. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15633. EXPECT_EQ(msg.data, "");
  15634. EXPECT_EQ(msg.event, "message");
  15635. }
  15636. // Test: Colon in value
  15637. TEST_F(SSEParsingTest, ColonInValue) {
  15638. sse::SSEMessage msg;
  15639. int retry_ms = 3000;
  15640. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15641. EXPECT_EQ(msg.data, "hello:world:test");
  15642. }
  15643. // Test: Line with no colon (field name only)
  15644. TEST_F(SSEParsingTest, FieldNameOnly) {
  15645. sse::SSEMessage msg;
  15646. int retry_ms = 3000;
  15647. // According to SSE spec, this is treated as field name with empty value
  15648. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15649. // Since we don't recognize "data" without colon, data should be empty
  15650. EXPECT_EQ(msg.data, "");
  15651. }
  15652. // Test: Trailing \r handling
  15653. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15654. sse::SSEMessage msg;
  15655. int retry_ms = 3000;
  15656. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15657. EXPECT_EQ(msg.data, "hello");
  15658. }
  15659. // Test: Unknown fields ignored
  15660. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15661. sse::SSEMessage msg;
  15662. int retry_ms = 3000;
  15663. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15664. EXPECT_EQ(msg.data, "");
  15665. EXPECT_EQ(msg.event, "message");
  15666. }
  15667. // Test: Space after colon is optional
  15668. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15669. sse::SSEMessage msg1, msg2;
  15670. int retry_ms = 3000;
  15671. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15672. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15673. EXPECT_EQ(msg1.data, "hello");
  15674. EXPECT_EQ(msg2.data, "hello");
  15675. }
  15676. // Test: SSEMessage clear
  15677. TEST_F(SSEParsingTest, MessageClear) {
  15678. sse::SSEMessage msg;
  15679. msg.event = "custom";
  15680. msg.data = "some data";
  15681. msg.id = "123";
  15682. msg.clear();
  15683. EXPECT_EQ(msg.event, "message");
  15684. EXPECT_EQ(msg.data, "");
  15685. EXPECT_EQ(msg.id, "");
  15686. }
  15687. // Test: Complete event parsing
  15688. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15689. sse::SSEMessage msg;
  15690. int retry_ms = 3000;
  15691. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15692. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15693. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15694. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15695. // Blank line ends event
  15696. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15697. EXPECT_EQ(msg.event, "notification");
  15698. EXPECT_EQ(msg.id, "evt-42");
  15699. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15700. EXPECT_EQ(retry_ms, 1000);
  15701. }
  15702. //==============================================================================
  15703. // Integration Tests with Server
  15704. //==============================================================================
  15705. class SSEIntegrationTest : public ::testing::Test {
  15706. protected:
  15707. void SetUp() override {
  15708. stop_server_.store(false);
  15709. events_.clear();
  15710. server_ = httplib::detail::make_unique<Server>();
  15711. setup_server();
  15712. start_server();
  15713. }
  15714. void TearDown() override {
  15715. stop_server_.store(true);
  15716. event_cv_.notify_all();
  15717. server_->stop();
  15718. if (server_thread_.joinable()) { server_thread_.join(); }
  15719. }
  15720. void setup_server() {
  15721. // Simple SSE endpoint
  15722. server_->Get("/events", [this](const Request &req, Response &res) {
  15723. auto last_id = req.get_header_value("Last-Event-ID");
  15724. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15725. res.set_chunked_content_provider(
  15726. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15727. std::unique_lock<std::mutex> lock(event_mutex_);
  15728. if (event_cv_.wait_for(
  15729. lock, std::chrono::milliseconds(200), [this] {
  15730. return !events_.empty() || stop_server_.load();
  15731. })) {
  15732. if (stop_server_.load()) { return false; }
  15733. if (!events_.empty()) {
  15734. std::string event = events_.front();
  15735. events_.erase(events_.begin());
  15736. sink.write(event.data(), event.size());
  15737. return true;
  15738. }
  15739. }
  15740. return !stop_server_.load();
  15741. });
  15742. });
  15743. // Endpoint that returns error
  15744. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15745. res.status = 500;
  15746. res.set_content("Internal Server Error", "text/plain");
  15747. });
  15748. // Endpoint for custom event types
  15749. server_->Get("/custom-events", [](const Request &, Response &res) {
  15750. res.set_chunked_content_provider(
  15751. "text/event-stream", [](size_t offset, DataSink &sink) {
  15752. if (offset == 0) {
  15753. std::string event = "event: update\ndata: updated\n\n"
  15754. "event: delete\ndata: deleted\n\n";
  15755. sink.write(event.data(), event.size());
  15756. }
  15757. return false; // End stream after sending
  15758. });
  15759. });
  15760. }
  15761. void start_server() {
  15762. port_ = server_->bind_to_any_port(HOST);
  15763. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15764. // Wait for server to start
  15765. while (!server_->is_running()) {
  15766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15767. }
  15768. }
  15769. int get_port() const { return port_; }
  15770. void send_event(const std::string &event) {
  15771. std::lock_guard<std::mutex> lock(event_mutex_);
  15772. events_.push_back(event);
  15773. event_cv_.notify_all();
  15774. }
  15775. std::unique_ptr<Server> server_;
  15776. std::thread server_thread_;
  15777. std::mutex event_mutex_;
  15778. std::condition_variable event_cv_;
  15779. std::vector<std::string> events_;
  15780. std::atomic<bool> stop_server_{false};
  15781. std::string last_received_event_id_;
  15782. int port_ = 0;
  15783. };
  15784. // Test: Successful connection and on_open callback
  15785. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15786. // Add a simple endpoint that sends one event and closes
  15787. server_->Get("/simple-event", [](const Request &, Response &res) {
  15788. res.set_chunked_content_provider(
  15789. "text/event-stream", [](size_t offset, DataSink &sink) {
  15790. if (offset == 0) {
  15791. std::string event = "data: hello\n\n";
  15792. sink.write(event.data(), event.size());
  15793. }
  15794. return false; // Close stream after sending
  15795. });
  15796. });
  15797. Client client("localhost", get_port());
  15798. sse::SSEClient sse(client, "/simple-event");
  15799. std::atomic<bool> open_called{false};
  15800. std::atomic<bool> message_received{false};
  15801. sse.on_open([&open_called]() { open_called.store(true); });
  15802. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15803. if (msg.data == "hello") { message_received.store(true); }
  15804. });
  15805. sse.set_reconnect_interval(100);
  15806. sse.set_max_reconnect_attempts(1);
  15807. // Start async
  15808. sse.start_async();
  15809. // Wait for message to be processed
  15810. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15811. sse.stop();
  15812. EXPECT_TRUE(open_called.load());
  15813. EXPECT_TRUE(message_received.load());
  15814. }
  15815. // Test: on_message callback
  15816. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15817. // Endpoint that sends multiple events then closes
  15818. server_->Get("/multi-event", [](const Request &, Response &res) {
  15819. res.set_chunked_content_provider(
  15820. "text/event-stream", [](size_t offset, DataSink &sink) {
  15821. if (offset == 0) {
  15822. std::string events = "data: message1\n\ndata: message2\n\n";
  15823. sink.write(events.data(), events.size());
  15824. }
  15825. return false;
  15826. });
  15827. });
  15828. Client client("localhost", get_port());
  15829. sse::SSEClient sse(client, "/multi-event");
  15830. std::vector<std::string> received_messages;
  15831. std::mutex messages_mutex;
  15832. sse.on_message([&](const sse::SSEMessage &msg) {
  15833. std::lock_guard<std::mutex> lock(messages_mutex);
  15834. received_messages.push_back(msg.data);
  15835. });
  15836. sse.set_reconnect_interval(100);
  15837. sse.set_max_reconnect_attempts(1);
  15838. sse.start_async();
  15839. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15840. sse.stop();
  15841. std::lock_guard<std::mutex> lock(messages_mutex);
  15842. EXPECT_GE(received_messages.size(), 2u);
  15843. if (received_messages.size() >= 2) {
  15844. EXPECT_EQ(received_messages[0], "message1");
  15845. EXPECT_EQ(received_messages[1], "message2");
  15846. }
  15847. }
  15848. // Test: on_event for specific types
  15849. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15850. Client client("localhost", get_port());
  15851. sse::SSEClient sse(client, "/custom-events");
  15852. std::atomic<bool> update_received{false};
  15853. std::atomic<bool> delete_received{false};
  15854. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15855. if (msg.data == "updated") { update_received.store(true); }
  15856. });
  15857. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15858. if (msg.data == "deleted") { delete_received.store(true); }
  15859. });
  15860. sse.set_max_reconnect_attempts(1);
  15861. sse.start_async();
  15862. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15863. sse.stop();
  15864. EXPECT_TRUE(update_received.load());
  15865. EXPECT_TRUE(delete_received.load());
  15866. }
  15867. // Test: on_error callback on connection failure
  15868. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15869. // Connect to a non-existent port
  15870. Client client("localhost", 59999);
  15871. sse::SSEClient sse(client, "/events");
  15872. std::atomic<bool> error_called{false};
  15873. Error received_error = Error::Success;
  15874. sse.on_error([&](Error err) {
  15875. error_called.store(true);
  15876. received_error = err;
  15877. });
  15878. sse.set_reconnect_interval(50);
  15879. sse.set_max_reconnect_attempts(1);
  15880. sse.start_async();
  15881. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15882. sse.stop();
  15883. EXPECT_TRUE(error_called.load());
  15884. EXPECT_NE(received_error, Error::Success);
  15885. }
  15886. // Test: Last-Event-ID header sent on reconnect
  15887. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15888. // Endpoint that sends event with ID
  15889. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15890. res.set_chunked_content_provider(
  15891. "text/event-stream", [](size_t offset, DataSink &sink) {
  15892. if (offset == 0) {
  15893. std::string event = "id: evt-123\ndata: test\n\n";
  15894. sink.write(event.data(), event.size());
  15895. }
  15896. return false;
  15897. });
  15898. });
  15899. Client client("localhost", get_port());
  15900. sse::SSEClient sse(client, "/event-with-id");
  15901. std::atomic<bool> id_received{false};
  15902. sse.on_message([&](const sse::SSEMessage &msg) {
  15903. if (!msg.id.empty()) { id_received.store(true); }
  15904. });
  15905. sse.set_reconnect_interval(100);
  15906. sse.set_max_reconnect_attempts(1);
  15907. sse.start_async();
  15908. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15909. sse.stop();
  15910. EXPECT_TRUE(id_received.load());
  15911. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15912. }
  15913. // Test: Manual stop
  15914. TEST_F(SSEIntegrationTest, ManualStop) {
  15915. // Endpoint that sends one event and stays open briefly
  15916. std::atomic<bool> handler_running{true};
  15917. server_->Get("/stay-open", [&handler_running](const Request &,
  15918. Response &res) {
  15919. res.set_chunked_content_provider(
  15920. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15921. if (offset == 0) {
  15922. std::string event = "data: connected\n\n";
  15923. sink.write(event.data(), event.size());
  15924. }
  15925. // Keep connection open while handler_running is true
  15926. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15927. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15928. }
  15929. return false;
  15930. });
  15931. });
  15932. Client client("localhost", get_port());
  15933. sse::SSEClient sse(client, "/stay-open");
  15934. std::atomic<bool> connected{false};
  15935. sse.on_open([&connected]() { connected.store(true); });
  15936. sse.set_reconnect_interval(100);
  15937. sse.set_max_reconnect_attempts(1);
  15938. sse.start_async();
  15939. // Wait for connection to establish
  15940. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15941. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15942. }
  15943. EXPECT_TRUE(connected.load());
  15944. EXPECT_TRUE(sse.is_connected());
  15945. // Signal handler to stop
  15946. handler_running.store(false);
  15947. // Stop SSE client
  15948. sse.stop();
  15949. EXPECT_FALSE(sse.is_connected());
  15950. }
  15951. // Test: SSEClient with custom headers
  15952. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15953. // Setup a server endpoint that checks for custom header
  15954. std::atomic<bool> header_received{false};
  15955. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15956. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15957. header_received.store(true);
  15958. }
  15959. res.set_chunked_content_provider("text/event-stream",
  15960. [](size_t, DataSink &) { return false; });
  15961. });
  15962. Client client("localhost", get_port());
  15963. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15964. sse::SSEClient sse(client, "/header-check", headers);
  15965. sse.set_max_reconnect_attempts(1);
  15966. sse.start_async();
  15967. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15968. sse.stop();
  15969. EXPECT_TRUE(header_received.load());
  15970. }
  15971. // Test: Reconnect interval configuration
  15972. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15973. Client client("localhost", get_port());
  15974. sse::SSEClient sse(client, "/events");
  15975. auto &result = sse.set_reconnect_interval(500);
  15976. // Builder pattern should return reference to self
  15977. EXPECT_EQ(&result, &sse);
  15978. }
  15979. // Test: Max reconnect attempts
  15980. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15981. // Connect to non-existent port to force reconnects
  15982. Client client("localhost", 59998);
  15983. sse::SSEClient sse(client, "/events");
  15984. std::atomic<int> error_count{0};
  15985. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15986. sse.set_reconnect_interval(50);
  15987. sse.set_max_reconnect_attempts(2);
  15988. auto start = std::chrono::steady_clock::now();
  15989. sse.start(); // Blocking call
  15990. auto end = std::chrono::steady_clock::now();
  15991. // Should have stopped after 2 failed attempts
  15992. EXPECT_GE(error_count.load(), 2);
  15993. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15994. auto duration =
  15995. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15996. #ifdef _WIN32
  15997. // Windows is much slower for socket connection failures
  15998. EXPECT_LT(duration.count(), 7000);
  15999. #else
  16000. EXPECT_LT(duration.count(), 1000);
  16001. #endif
  16002. }
  16003. // Test: Multi-line data in integration
  16004. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16005. // Endpoint with multi-line data
  16006. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16007. res.set_chunked_content_provider(
  16008. "text/event-stream", [](size_t offset, DataSink &sink) {
  16009. if (offset == 0) {
  16010. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16011. sink.write(event.data(), event.size());
  16012. }
  16013. return false;
  16014. });
  16015. });
  16016. Client client("localhost", get_port());
  16017. sse::SSEClient sse(client, "/multiline-data");
  16018. std::string received_data;
  16019. std::mutex data_mutex;
  16020. sse.on_message([&](const sse::SSEMessage &msg) {
  16021. std::lock_guard<std::mutex> lock(data_mutex);
  16022. received_data = msg.data;
  16023. });
  16024. sse.set_reconnect_interval(100);
  16025. sse.set_max_reconnect_attempts(1);
  16026. sse.start_async();
  16027. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16028. sse.stop();
  16029. std::lock_guard<std::mutex> lock(data_mutex);
  16030. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16031. }
  16032. // Test: Auto-reconnect after server disconnection
  16033. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16034. std::atomic<int> connection_count{0};
  16035. std::atomic<int> message_count{0};
  16036. // Endpoint that sends one event and closes, forcing reconnect
  16037. server_->Get("/reconnect-test",
  16038. [&connection_count](const Request &, Response &res) {
  16039. connection_count.fetch_add(1);
  16040. res.set_chunked_content_provider(
  16041. "text/event-stream", [](size_t offset, DataSink &sink) {
  16042. if (offset == 0) {
  16043. std::string event = "data: hello\n\n";
  16044. sink.write(event.data(), event.size());
  16045. }
  16046. return false; // Close connection after sending
  16047. });
  16048. });
  16049. Client client("localhost", get_port());
  16050. sse::SSEClient sse(client, "/reconnect-test");
  16051. sse.on_message([&message_count](const sse::SSEMessage &) {
  16052. message_count.fetch_add(1);
  16053. });
  16054. sse.set_reconnect_interval(100);
  16055. sse.set_max_reconnect_attempts(3);
  16056. sse.start_async();
  16057. // Wait long enough for multiple reconnects
  16058. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16059. sse.stop();
  16060. // Should have connected multiple times (initial + reconnects)
  16061. EXPECT_GE(connection_count.load(), 2);
  16062. // Should have received messages from multiple connections
  16063. EXPECT_GE(message_count.load(), 2);
  16064. }
  16065. // Test: Last-Event-ID sent on reconnect
  16066. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16067. std::atomic<int> connection_count{0};
  16068. std::vector<std::string> received_last_event_ids;
  16069. std::mutex id_mutex;
  16070. // Endpoint that checks Last-Event-ID header and sends event with ID
  16071. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16072. int conn = connection_count.fetch_add(1);
  16073. // Capture the Last-Event-ID header from each connection
  16074. {
  16075. std::lock_guard<std::mutex> lock(id_mutex);
  16076. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16077. }
  16078. res.set_chunked_content_provider(
  16079. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16080. if (offset == 0) {
  16081. std::string event =
  16082. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16083. sink.write(event.data(), event.size());
  16084. }
  16085. return false;
  16086. });
  16087. });
  16088. Client client("localhost", get_port());
  16089. sse::SSEClient sse(client, "/reconnect-with-id");
  16090. sse.set_reconnect_interval(100);
  16091. sse.set_max_reconnect_attempts(3);
  16092. sse.start_async();
  16093. // Wait for at least 2 connections
  16094. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16095. sse.stop();
  16096. // Verify behavior
  16097. std::lock_guard<std::mutex> lock(id_mutex);
  16098. EXPECT_GE(received_last_event_ids.size(), 2u);
  16099. // First connection should have no Last-Event-ID
  16100. if (!received_last_event_ids.empty()) {
  16101. EXPECT_EQ(received_last_event_ids[0], "");
  16102. }
  16103. // Second connection should have Last-Event-ID from first connection
  16104. if (received_last_event_ids.size() >= 2) {
  16105. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16106. }
  16107. }
  16108. // Test: set_headers updates headers used on reconnect
  16109. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16110. std::vector<std::string> received_tokens;
  16111. std::mutex token_mutex;
  16112. // Endpoint that captures Authorization header
  16113. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16114. {
  16115. std::lock_guard<std::mutex> lock(token_mutex);
  16116. received_tokens.push_back(req.get_header_value("Authorization"));
  16117. }
  16118. res.set_chunked_content_provider(
  16119. "text/event-stream", [](size_t offset, DataSink &sink) {
  16120. if (offset == 0) {
  16121. std::string event = "data: hello\n\n";
  16122. sink.write(event.data(), event.size());
  16123. }
  16124. return false; // Close connection to trigger reconnect
  16125. });
  16126. });
  16127. Client client("localhost", get_port());
  16128. Headers headers = {{"Authorization", "Bearer old-token"}};
  16129. sse::SSEClient sse(client, "/auth-check", headers);
  16130. // Update headers on each successful connection
  16131. sse.on_open(
  16132. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16133. sse.set_reconnect_interval(100);
  16134. sse.set_max_reconnect_attempts(3);
  16135. sse.start_async();
  16136. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16137. sse.stop();
  16138. std::lock_guard<std::mutex> lock(token_mutex);
  16139. ASSERT_GE(received_tokens.size(), 2u);
  16140. // First connection uses original header
  16141. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16142. // Second connection uses updated header from set_headers
  16143. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16144. }
  16145. // Test: 401 allows reconnection (so on_error can refresh headers)
  16146. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16147. std::atomic<int> connection_count{0};
  16148. // Endpoint: returns 401 on first attempt, 200 on second
  16149. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16150. int conn = connection_count.fetch_add(1);
  16151. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16152. res.status = StatusCode::Unauthorized_401;
  16153. res.set_content("Unauthorized", "text/plain");
  16154. return;
  16155. }
  16156. res.set_chunked_content_provider(
  16157. "text/event-stream", [](size_t offset, DataSink &sink) {
  16158. if (offset == 0) {
  16159. std::string event = "data: authenticated\n\n";
  16160. sink.write(event.data(), event.size());
  16161. }
  16162. return false;
  16163. });
  16164. });
  16165. Client client("localhost", get_port());
  16166. Headers headers = {{"Authorization", "Bearer expired"}};
  16167. sse::SSEClient sse(client, "/auth-retry", headers);
  16168. std::atomic<bool> message_received{false};
  16169. // Refresh token on error
  16170. sse.on_error(
  16171. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16172. sse.on_message([&](const sse::SSEMessage &msg) {
  16173. if (msg.data == "authenticated") { message_received.store(true); }
  16174. });
  16175. sse.set_reconnect_interval(100);
  16176. sse.set_max_reconnect_attempts(3);
  16177. sse.start_async();
  16178. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16179. sse.stop();
  16180. // Should have reconnected after 401 and succeeded with new token
  16181. EXPECT_GE(connection_count.load(), 2);
  16182. EXPECT_TRUE(message_received.load());
  16183. }
  16184. TEST(Issue2318Test, EmptyHostString) {
  16185. {
  16186. httplib::Client cli_empty("", PORT);
  16187. auto res = cli_empty.Get("/");
  16188. ASSERT_FALSE(res);
  16189. EXPECT_EQ(httplib::Error::Connection, res.error());
  16190. }
  16191. {
  16192. httplib::Client cli(" ", PORT);
  16193. auto res = cli.Get("/");
  16194. ASSERT_FALSE(res);
  16195. EXPECT_EQ(httplib::Error::Connection, res.error());
  16196. }
  16197. }
  16198. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16199. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16200. Server svr;
  16201. // Set a small payload limit (1KB)
  16202. svr.set_payload_max_length(1024);
  16203. svr.Post("/test", [&](const Request &req, Response &res) {
  16204. res.set_content("Body size: " + std::to_string(req.body.size()),
  16205. "text/plain");
  16206. });
  16207. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16208. auto se = detail::scope_exit([&] {
  16209. svr.stop();
  16210. listen_thread.join();
  16211. });
  16212. svr.wait_until_ready();
  16213. // Create data that compresses well but exceeds limit when decompressed
  16214. // 8KB of repeated null bytes compresses to a very small size
  16215. std::string original_data(8 * 1024, '\0');
  16216. // Compress the data using gzip
  16217. std::string compressed_data;
  16218. detail::gzip_compressor compressor;
  16219. compressor.compress(original_data.data(), original_data.size(), true,
  16220. [&](const char *data, size_t size) {
  16221. compressed_data.append(data, size);
  16222. return true;
  16223. });
  16224. // Verify compression worked (compressed should be much smaller)
  16225. ASSERT_LT(compressed_data.size(), original_data.size());
  16226. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16227. // Send compressed data with Content-Encoding: gzip
  16228. Client cli(HOST, PORT);
  16229. Headers headers = {{"Content-Encoding", "gzip"}};
  16230. auto res =
  16231. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16232. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16235. }
  16236. #endif
  16237. // ============================================================================
  16238. // OpenSSL-Specific Tests
  16239. // ============================================================================
  16240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16241. X509 *readCertificate(const std::string &strFileName) {
  16242. std::ifstream inStream(strFileName);
  16243. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16244. std::istreambuf_iterator<char>());
  16245. if (strCertPEM.empty()) return (nullptr);
  16246. BIO *pbCert = BIO_new(BIO_s_mem());
  16247. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16248. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16249. BIO_free(pbCert);
  16250. return (pCert);
  16251. }
  16252. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16253. std::ifstream inStream(strFileName);
  16254. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16255. std::istreambuf_iterator<char>());
  16256. if (strPrivateKeyPEM.empty()) return (nullptr);
  16257. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16258. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16259. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16260. BIO_free(pbPrivKey);
  16261. return (pPrivateKey);
  16262. }
  16263. TEST(BindServerTest, UpdateCerts) {
  16264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16265. int port = svr.bind_to_any_port("0.0.0.0");
  16266. ASSERT_TRUE(svr.is_valid());
  16267. ASSERT_TRUE(port > 0);
  16268. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16269. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16270. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16271. ASSERT_TRUE(cert != nullptr);
  16272. ASSERT_TRUE(ca_cert != nullptr);
  16273. ASSERT_TRUE(key != nullptr);
  16274. X509_STORE *cert_store = X509_STORE_new();
  16275. X509_STORE_add_cert(cert_store, ca_cert);
  16276. // svr.update_certs(cert, key, cert_store); // deprecated
  16277. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16278. CLIENT_CA_CERT_FILE);
  16279. ASSERT_TRUE(svr.is_valid());
  16280. svr.stop();
  16281. X509_STORE_free(cert_store);
  16282. X509_free(cert);
  16283. X509_free(ca_cert);
  16284. EVP_PKEY_free(key);
  16285. }
  16286. // Test that update_certs() updates client CA list correctly
  16287. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16288. // Start with file-based constructor
  16289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16290. ASSERT_TRUE(svr.is_valid());
  16291. // Initially no client CA list should be set
  16292. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16293. ASSERT_TRUE(ssl_ctx != nullptr);
  16294. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16295. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16296. EXPECT_EQ(0, count_before);
  16297. // Now update with client CA (PEM string)
  16298. std::string cert_pem, key_pem, ca_pem;
  16299. read_file(SERVER_CERT_FILE, cert_pem);
  16300. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16301. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16302. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16303. ASSERT_TRUE(svr.is_valid());
  16304. // Now client CA list should be set
  16305. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16306. ASSERT_TRUE(ca_list_after != nullptr);
  16307. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16308. }
  16309. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16310. // Test that the file-path SSLServer constructor properly sets the client CA
  16311. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16313. ASSERT_TRUE(svr.is_valid());
  16314. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16315. ASSERT_TRUE(ssl_ctx != nullptr);
  16316. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16317. ASSERT_TRUE(ca_list != nullptr);
  16318. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16319. }
  16320. #endif
  16321. // ============================================================================
  16322. // MbedTLS-Specific Tests
  16323. // ============================================================================
  16324. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16325. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16326. using namespace httplib::tls;
  16327. // Track if callback was invoked
  16328. bool callback_invoked = false;
  16329. // The callback receives void* ctx which is actually MbedTlsContext*
  16330. // We can access the mbedtls_ssl_config via the context
  16331. auto setup_callback = [&callback_invoked](void *ctx) {
  16332. callback_invoked = true;
  16333. // Cast to MbedTlsContext* to access the ssl config
  16334. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16335. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16336. // Use static variables to hold certificate data (simplified for test)
  16337. static mbedtls_x509_crt own_cert;
  16338. static mbedtls_pk_context own_key;
  16339. static mbedtls_x509_crt ca_chain;
  16340. static bool initialized = false;
  16341. if (!initialized) {
  16342. mbedtls_x509_crt_init(&own_cert);
  16343. mbedtls_pk_init(&own_key);
  16344. mbedtls_x509_crt_init(&ca_chain);
  16345. // Load server certificate
  16346. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16347. return false;
  16348. }
  16349. // Load server private key.
  16350. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16351. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16352. #if MBEDTLS_VERSION_MAJOR == 3
  16353. ,
  16354. mbedtls_ctr_drbg_random, nullptr
  16355. #endif
  16356. ) != 0) {
  16357. return false;
  16358. }
  16359. // Load CA chain for client verification
  16360. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16361. return false;
  16362. }
  16363. initialized = true;
  16364. }
  16365. // Configure the SSL config
  16366. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16367. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16368. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16369. // Set minimum TLS version using mbedTLS native API
  16370. #if MBEDTLS_VERSION_MAJOR >= 3
  16371. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16372. #else
  16373. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16374. MBEDTLS_SSL_MINOR_VERSION_3);
  16375. #endif
  16376. return true;
  16377. };
  16378. SSLServer svr(setup_callback);
  16379. ASSERT_TRUE(svr.is_valid());
  16380. ASSERT_TRUE(callback_invoked);
  16381. svr.Get("/test", [&](const Request &req, Response &res) {
  16382. res.set_content("test", "text/plain");
  16383. auto cert = req.peer_cert();
  16384. ASSERT_TRUE(static_cast<bool>(cert));
  16385. auto common_name = cert.subject_cn();
  16386. EXPECT_EQ("Common Name", common_name);
  16387. });
  16388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. });
  16394. svr.wait_until_ready();
  16395. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16396. cli.enable_server_certificate_verification(false);
  16397. cli.set_connection_timeout(30);
  16398. auto res = cli.Get("/test");
  16399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16400. ASSERT_EQ(StatusCode::OK_200, res->status);
  16401. }
  16402. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16403. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16404. // keep-alive SSL session, which reads through that config in
  16405. // mbedtls_ssl_close_notify.
  16406. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16408. ASSERT_TRUE(svr.is_valid());
  16409. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16410. res.set_content("test", "text/plain");
  16411. });
  16412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16413. auto se = detail::scope_exit([&] {
  16414. svr.stop();
  16415. t.join();
  16416. ASSERT_FALSE(svr.is_running());
  16417. });
  16418. svr.wait_until_ready();
  16419. {
  16420. SSLClient cli(HOST, PORT);
  16421. cli.enable_server_certificate_verification(false);
  16422. cli.set_keep_alive(true);
  16423. auto res = cli.Get("/test");
  16424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16425. ASSERT_EQ(StatusCode::OK_200, res->status);
  16426. // cli is destructed here with the keep-alive SSL session still open.
  16427. }
  16428. }
  16429. #endif
  16430. // WebSocket Tests
  16431. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16432. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16433. // defining the meaning of these bits has been negotiated.
  16434. auto make_frame = [](uint8_t first_byte) {
  16435. std::string frame;
  16436. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16437. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16438. frame += "Hello";
  16439. return frame;
  16440. };
  16441. // RSV1 set (0x40)
  16442. {
  16443. detail::BufferStream strm;
  16444. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16445. ws::Opcode opcode;
  16446. std::string payload;
  16447. bool fin;
  16448. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16449. false, 1024));
  16450. }
  16451. // RSV2 set (0x20)
  16452. {
  16453. detail::BufferStream strm;
  16454. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16455. ws::Opcode opcode;
  16456. std::string payload;
  16457. bool fin;
  16458. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16459. false, 1024));
  16460. }
  16461. // RSV3 set (0x10)
  16462. {
  16463. detail::BufferStream strm;
  16464. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16465. ws::Opcode opcode;
  16466. std::string payload;
  16467. bool fin;
  16468. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16469. false, 1024));
  16470. }
  16471. // No RSV bits set - should succeed
  16472. {
  16473. detail::BufferStream strm;
  16474. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16475. ws::Opcode opcode;
  16476. std::string payload;
  16477. bool fin;
  16478. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16479. false, 1024));
  16480. EXPECT_EQ(ws::Opcode::Text, opcode);
  16481. EXPECT_EQ("Hello", payload);
  16482. EXPECT_TRUE(fin);
  16483. }
  16484. }
  16485. TEST(WebSocketTest, ControlFrameValidation) {
  16486. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16487. // payload length <= 125.
  16488. // Ping with FIN=0 - must be rejected
  16489. {
  16490. detail::BufferStream strm;
  16491. std::string frame;
  16492. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16493. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16494. strm.write(frame.data(), frame.size());
  16495. ws::Opcode opcode;
  16496. std::string payload;
  16497. bool fin;
  16498. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16499. false, 1024));
  16500. }
  16501. // Close with FIN=0 - must be rejected
  16502. {
  16503. detail::BufferStream strm;
  16504. std::string frame;
  16505. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16506. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16507. strm.write(frame.data(), frame.size());
  16508. ws::Opcode opcode;
  16509. std::string payload;
  16510. bool fin;
  16511. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16512. false, 1024));
  16513. }
  16514. // Ping with payload_len=126 (extended length) - must be rejected
  16515. {
  16516. detail::BufferStream strm;
  16517. std::string frame;
  16518. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16519. frame += static_cast<char>(126); // payload_len=126 (>125)
  16520. frame += static_cast<char>(0x00); // extended length high byte
  16521. frame += static_cast<char>(126); // extended length low byte
  16522. frame += std::string(126, 'x');
  16523. strm.write(frame.data(), frame.size());
  16524. ws::Opcode opcode;
  16525. std::string payload;
  16526. bool fin;
  16527. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16528. false, 1024));
  16529. }
  16530. // Ping with FIN=1 and payload_len=125 - should succeed
  16531. {
  16532. detail::BufferStream strm;
  16533. std::string frame;
  16534. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16535. frame += static_cast<char>(125); // payload_len=125
  16536. frame += std::string(125, 'x');
  16537. strm.write(frame.data(), frame.size());
  16538. ws::Opcode opcode;
  16539. std::string payload;
  16540. bool fin;
  16541. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16542. false, 1024));
  16543. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16544. EXPECT_EQ(125u, payload.size());
  16545. EXPECT_TRUE(fin);
  16546. }
  16547. }
  16548. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16549. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16550. // length MUST be 0.
  16551. // MSB set - must be rejected
  16552. {
  16553. detail::BufferStream strm;
  16554. std::string frame;
  16555. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16556. frame += static_cast<char>(127); // 64-bit extended length
  16557. frame += static_cast<char>(0x80); // MSB set (invalid)
  16558. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16559. strm.write(frame.data(), frame.size());
  16560. ws::Opcode opcode;
  16561. std::string payload;
  16562. bool fin;
  16563. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16564. false, 1024));
  16565. }
  16566. // MSB clear - should pass length parsing (will be rejected by max_len,
  16567. // but that's a different check; use a small length to verify)
  16568. {
  16569. detail::BufferStream strm;
  16570. std::string frame;
  16571. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16572. frame += static_cast<char>(127); // 64-bit extended length
  16573. frame += std::string(7, '\0'); // high bytes = 0
  16574. frame += static_cast<char>(0x03); // length = 3
  16575. frame += "abc";
  16576. strm.write(frame.data(), frame.size());
  16577. ws::Opcode opcode;
  16578. std::string payload;
  16579. bool fin;
  16580. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16581. false, 1024));
  16582. EXPECT_EQ(ws::Opcode::Text, opcode);
  16583. EXPECT_EQ("abc", payload);
  16584. }
  16585. }
  16586. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16587. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16588. // Valid UTF-8
  16589. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16590. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16591. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16592. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16593. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16594. // Invalid UTF-8
  16595. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16596. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16597. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16598. EXPECT_FALSE(
  16599. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16600. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16601. }
  16602. TEST(WebSocketTest, ConnectAndDisconnect) {
  16603. Server svr;
  16604. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16605. std::string msg;
  16606. while (ws.read(msg)) {}
  16607. });
  16608. auto port = svr.bind_to_any_port(HOST);
  16609. std::thread t([&]() { svr.listen_after_bind(); });
  16610. svr.wait_until_ready();
  16611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16612. ASSERT_TRUE(client.connect());
  16613. EXPECT_TRUE(client.is_open());
  16614. client.close();
  16615. EXPECT_FALSE(client.is_open());
  16616. svr.stop();
  16617. t.join();
  16618. }
  16619. TEST(WebSocketTest, ValidURL) {
  16620. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16621. EXPECT_TRUE(ws1.is_valid());
  16622. ws::WebSocketClient ws2("ws://example.com/path");
  16623. EXPECT_TRUE(ws2.is_valid());
  16624. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16625. EXPECT_TRUE(ws3.is_valid());
  16626. #ifdef CPPHTTPLIB_SSL_ENABLED
  16627. ws::WebSocketClient wss1("wss://example.com/path");
  16628. EXPECT_TRUE(wss1.is_valid());
  16629. ws::WebSocketClient wss2("wss://example.com:443/path");
  16630. EXPECT_TRUE(wss2.is_valid());
  16631. #endif
  16632. }
  16633. TEST(WebSocketTest, InvalidURL) {
  16634. // No scheme
  16635. ws::WebSocketClient ws1("localhost:8080/path");
  16636. EXPECT_FALSE(ws1.is_valid());
  16637. // No path
  16638. ws::WebSocketClient ws2("ws://localhost:8080");
  16639. EXPECT_FALSE(ws2.is_valid());
  16640. // Empty string
  16641. ws::WebSocketClient ws3("");
  16642. EXPECT_FALSE(ws3.is_valid());
  16643. // Missing host
  16644. ws::WebSocketClient ws4("ws://:8080/path");
  16645. EXPECT_FALSE(ws4.is_valid());
  16646. // Port number overflow — should not crash
  16647. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16648. EXPECT_FALSE(ws5.is_valid());
  16649. // Port out of range
  16650. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16651. EXPECT_FALSE(ws6.is_valid());
  16652. }
  16653. TEST(WebSocketTest, UnsupportedScheme) {
  16654. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16655. ws::WebSocketClient ws1("http://localhost:8080/path");
  16656. EXPECT_FALSE(ws1.is_valid());
  16657. ws::WebSocketClient ws2("https://localhost:8080/path");
  16658. EXPECT_FALSE(ws2.is_valid());
  16659. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16660. EXPECT_FALSE(ws3.is_valid());
  16661. #else
  16662. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16663. std::invalid_argument);
  16664. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16665. std::invalid_argument);
  16666. #endif
  16667. }
  16668. TEST(WebSocketTest, ConnectWhenInvalid) {
  16669. ws::WebSocketClient ws("not a valid url");
  16670. EXPECT_FALSE(ws.is_valid());
  16671. EXPECT_FALSE(ws.connect());
  16672. }
  16673. TEST(WebSocketTest, DefaultPort) {
  16674. ws::WebSocketClient ws1("ws://example.com/path");
  16675. EXPECT_TRUE(ws1.is_valid());
  16676. // ws:// defaults to port 80 (verified by successful parse)
  16677. #ifdef CPPHTTPLIB_SSL_ENABLED
  16678. ws::WebSocketClient ws2("wss://example.com/path");
  16679. EXPECT_TRUE(ws2.is_valid());
  16680. // wss:// defaults to port 443 (verified by successful parse)
  16681. #endif
  16682. }
  16683. TEST(WebSocketTest, IPv6LiteralAddress) {
  16684. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16685. EXPECT_TRUE(ws1.is_valid());
  16686. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16687. EXPECT_TRUE(ws2.is_valid());
  16688. }
  16689. TEST(WebSocketTest, ComplexPath) {
  16690. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16691. EXPECT_TRUE(ws1.is_valid());
  16692. ws::WebSocketClient ws2("ws://localhost:8080/");
  16693. EXPECT_TRUE(ws2.is_valid());
  16694. }
  16695. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16696. Server svr;
  16697. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16698. std::string msg;
  16699. while (ws.read(msg)) {}
  16700. });
  16701. auto port = svr.bind_to_any_port(HOST);
  16702. std::thread t([&]() { svr.listen_after_bind(); });
  16703. svr.wait_until_ready();
  16704. auto another_host = "example.com";
  16705. auto wrong_ip = "192.0.2.1";
  16706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16707. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16708. ASSERT_TRUE(client.connect());
  16709. EXPECT_TRUE(client.is_open());
  16710. client.close();
  16711. svr.stop();
  16712. t.join();
  16713. }
  16714. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16715. Server svr;
  16716. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16717. std::string msg;
  16718. while (ws.read(msg)) {}
  16719. });
  16720. auto port = svr.bind_to_any_port(HOST);
  16721. std::thread t([&]() { svr.listen_after_bind(); });
  16722. svr.wait_until_ready();
  16723. auto wrong_ip = "192.0.2.1";
  16724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16725. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16726. client.set_connection_timeout(1);
  16727. client.set_read_timeout(1);
  16728. client.set_write_timeout(1);
  16729. EXPECT_FALSE(client.connect());
  16730. EXPECT_FALSE(client.is_open());
  16731. svr.stop();
  16732. t.join();
  16733. }
  16734. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16735. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16736. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16737. // (RFC 6761) is only a map key and the Host header value.
  16738. auto host = "target.invalid";
  16739. Server svr;
  16740. std::string received_host;
  16741. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16742. received_host = req.get_header_value("Host");
  16743. std::string msg;
  16744. while (ws.read(msg)) {}
  16745. });
  16746. auto port = svr.bind_to_any_port(HOST);
  16747. std::thread t([&]() { svr.listen_after_bind(); });
  16748. // ASSERT_* below returns from the test body, which would leave t joinable
  16749. // and make ~thread call std::terminate.
  16750. auto se = detail::scope_exit([&] {
  16751. svr.stop();
  16752. if (t.joinable()) { t.join(); }
  16753. });
  16754. svr.wait_until_ready();
  16755. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16756. std::to_string(port) + "/ws");
  16757. client.set_hostname_addr_map({{host, HOST}});
  16758. ASSERT_TRUE(client.connect());
  16759. EXPECT_TRUE(client.is_open());
  16760. client.close();
  16761. svr.stop();
  16762. t.join();
  16763. // The mapping only redirects the connection; the identity stays host_.
  16764. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16765. }
  16766. class WebSocketIntegrationTest : public ::testing::Test {
  16767. protected:
  16768. void SetUp() override {
  16769. server_ = httplib::detail::make_unique<Server>();
  16770. setup_server();
  16771. start_server();
  16772. }
  16773. void TearDown() override {
  16774. server_->stop();
  16775. if (server_thread_.joinable()) { server_thread_.join(); }
  16776. }
  16777. void setup_server() {
  16778. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16779. std::string msg;
  16780. ws::ReadResult ret;
  16781. while ((ret = ws.read(msg))) {
  16782. if (ret == ws::Binary) {
  16783. ws.send(msg.data(), msg.size());
  16784. } else {
  16785. ws.send(msg);
  16786. }
  16787. }
  16788. });
  16789. server_->WebSocket("/ws-echo-string",
  16790. [](const Request &, ws::WebSocket &ws) {
  16791. std::string msg;
  16792. while (ws.read(msg)) {
  16793. ws.send("echo: " + msg);
  16794. }
  16795. });
  16796. server_->WebSocket(
  16797. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16798. // Echo back request metadata
  16799. ws.send("path:" + req.path);
  16800. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16801. std::string msg;
  16802. while (ws.read(msg)) {}
  16803. });
  16804. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16805. std::string msg;
  16806. ws.read(msg); // wait for a message
  16807. ws.close();
  16808. });
  16809. server_->WebSocket("/ws-close-status",
  16810. [](const Request &, ws::WebSocket &ws) {
  16811. std::string msg;
  16812. ws.read(msg); // wait for a message
  16813. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16814. });
  16815. server_->WebSocket(
  16816. "/ws-subprotocol",
  16817. [](const Request &, ws::WebSocket &ws) {
  16818. std::string msg;
  16819. while (ws.read(msg)) {
  16820. ws.send(msg);
  16821. }
  16822. },
  16823. [](const std::vector<std::string> &protocols) -> std::string {
  16824. for (const auto &p : protocols) {
  16825. if (p == "graphql-ws") { return p; }
  16826. }
  16827. return "";
  16828. });
  16829. }
  16830. void start_server() {
  16831. port_ = server_->bind_to_any_port(HOST);
  16832. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16833. server_->wait_until_ready();
  16834. }
  16835. std::unique_ptr<Server> server_;
  16836. std::thread server_thread_;
  16837. int port_ = 0;
  16838. };
  16839. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16841. "/ws-echo");
  16842. ASSERT_TRUE(client.connect());
  16843. ASSERT_TRUE(client.is_open());
  16844. ASSERT_TRUE(client.send("Hello WebSocket"));
  16845. std::string msg;
  16846. EXPECT_EQ(ws::Text, client.read(msg));
  16847. EXPECT_EQ("Hello WebSocket", msg);
  16848. client.close();
  16849. }
  16850. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16852. "/ws-echo");
  16853. ASSERT_TRUE(client.connect());
  16854. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16855. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16856. std::string msg;
  16857. EXPECT_EQ(ws::Binary, client.read(msg));
  16858. EXPECT_EQ(binary_data, msg);
  16859. client.close();
  16860. }
  16861. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16862. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16863. "/ws-echo");
  16864. ASSERT_TRUE(client.connect());
  16865. for (int i = 0; i < 10; i++) {
  16866. auto text = "message " + std::to_string(i);
  16867. ASSERT_TRUE(client.send(text));
  16868. std::string msg;
  16869. ASSERT_TRUE(client.read(msg));
  16870. EXPECT_EQ(text, msg);
  16871. }
  16872. client.close();
  16873. }
  16874. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16876. "/ws-close");
  16877. ASSERT_TRUE(client.connect());
  16878. // Send a message to trigger the server to close
  16879. ASSERT_TRUE(client.send("trigger close"));
  16880. // The server will close, so read should return false
  16881. std::string msg;
  16882. EXPECT_FALSE(client.read(msg));
  16883. EXPECT_FALSE(client.is_open());
  16884. }
  16885. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16886. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16887. "/ws-echo");
  16888. ASSERT_TRUE(client.connect());
  16889. // 128KB message
  16890. std::string large_data(128 * 1024, 'X');
  16891. ASSERT_TRUE(client.send(large_data));
  16892. std::string msg;
  16893. ASSERT_TRUE(client.read(msg));
  16894. EXPECT_EQ(large_data, msg);
  16895. client.close();
  16896. }
  16897. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16899. "/ws-echo");
  16900. ASSERT_TRUE(client.connect());
  16901. const int num_threads = 4;
  16902. std::vector<std::thread> threads;
  16903. std::atomic<int> send_count{0};
  16904. for (int t = 0; t < num_threads; t++) {
  16905. threads.emplace_back([&client, &send_count, t]() {
  16906. for (int i = 0; i < 5; i++) {
  16907. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16908. if (client.send(text)) { send_count++; }
  16909. }
  16910. });
  16911. }
  16912. for (auto &th : threads) {
  16913. th.join();
  16914. }
  16915. int received = 0;
  16916. std::string msg;
  16917. while (received < send_count.load()) {
  16918. if (!client.read(msg)) { break; }
  16919. received++;
  16920. }
  16921. EXPECT_EQ(send_count.load(), received);
  16922. client.close();
  16923. }
  16924. TEST_F(WebSocketIntegrationTest, ReadString) {
  16925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16926. "/ws-echo-string");
  16927. ASSERT_TRUE(client.connect());
  16928. ASSERT_TRUE(client.send("hello"));
  16929. std::string msg;
  16930. ASSERT_TRUE(client.read(msg));
  16931. EXPECT_EQ("echo: hello", msg);
  16932. ASSERT_TRUE(client.send("world"));
  16933. ASSERT_TRUE(client.read(msg));
  16934. EXPECT_EQ("echo: world", msg);
  16935. client.close();
  16936. }
  16937. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16938. Headers headers = {{"X-Test-Header", "test-value"}};
  16939. ws::WebSocketClient client(
  16940. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16941. ASSERT_TRUE(client.connect());
  16942. std::string msg;
  16943. ASSERT_TRUE(client.read(msg));
  16944. EXPECT_EQ("path:/ws-request-info", msg);
  16945. ASSERT_TRUE(client.read(msg));
  16946. EXPECT_EQ("header:test-value", msg);
  16947. client.close();
  16948. }
  16949. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16951. "/ws-echo");
  16952. client.set_read_timeout(1, 0); // 1 second
  16953. ASSERT_TRUE(client.connect());
  16954. // Don't send anything — server echo handler waits for a message,
  16955. // so read() should time out and return false.
  16956. std::string msg;
  16957. EXPECT_FALSE(client.read(msg));
  16958. }
  16959. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16961. "/ws-echo");
  16962. client.set_read_timeout(5, 0);
  16963. ASSERT_TRUE(client.connect());
  16964. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16965. // The server should reject it and close the connection.
  16966. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16967. client.send(oversized);
  16968. // The server's read() should have failed due to payload limit,
  16969. // so our read() should return false (connection closed).
  16970. std::string msg;
  16971. EXPECT_FALSE(client.read(msg));
  16972. }
  16973. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16974. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16975. "/ws-echo");
  16976. client.set_read_timeout(10, 0);
  16977. ASSERT_TRUE(client.connect());
  16978. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16979. // This should succeed.
  16980. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16981. ASSERT_TRUE(client.send(at_limit));
  16982. std::string msg;
  16983. ASSERT_TRUE(client.read(msg));
  16984. EXPECT_EQ(at_limit.size(), msg.size());
  16985. client.close();
  16986. }
  16987. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16989. "/nonexistent");
  16990. EXPECT_FALSE(client.connect());
  16991. EXPECT_FALSE(client.is_open());
  16992. }
  16993. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16995. "/ws-echo");
  16996. ASSERT_TRUE(client.connect());
  16997. ASSERT_TRUE(client.send(""));
  16998. std::string msg;
  16999. EXPECT_EQ(ws::Text, client.read(msg));
  17000. EXPECT_EQ("", msg);
  17001. client.close();
  17002. }
  17003. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17005. "/ws-echo");
  17006. // First connection
  17007. ASSERT_TRUE(client.connect());
  17008. ASSERT_TRUE(client.send("first"));
  17009. std::string msg;
  17010. ASSERT_TRUE(client.read(msg));
  17011. EXPECT_EQ("first", msg);
  17012. client.close();
  17013. EXPECT_FALSE(client.is_open());
  17014. // Reconnect using the same client object
  17015. ASSERT_TRUE(client.connect());
  17016. ASSERT_TRUE(client.is_open());
  17017. ASSERT_TRUE(client.send("second"));
  17018. ASSERT_TRUE(client.read(msg));
  17019. EXPECT_EQ("second", msg);
  17020. client.close();
  17021. }
  17022. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17024. "/ws-close-status");
  17025. ASSERT_TRUE(client.connect());
  17026. // Trigger the server to close with GoingAway status
  17027. ASSERT_TRUE(client.send("trigger"));
  17028. // read() should return false after receiving the close frame
  17029. std::string msg;
  17030. EXPECT_FALSE(client.read(msg));
  17031. EXPECT_FALSE(client.is_open());
  17032. }
  17033. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17035. "/ws-echo");
  17036. ASSERT_TRUE(client.connect());
  17037. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17038. EXPECT_FALSE(client.is_open());
  17039. }
  17040. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17041. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17042. ws::WebSocketClient client(
  17043. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17044. ASSERT_TRUE(client.connect());
  17045. // Server should have selected graphql-ws
  17046. EXPECT_EQ("graphql-ws", client.subprotocol());
  17047. client.close();
  17048. }
  17049. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17050. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17051. ws::WebSocketClient client(
  17052. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17053. ASSERT_TRUE(client.connect());
  17054. // Server should not have selected any subprotocol
  17055. EXPECT_TRUE(client.subprotocol().empty());
  17056. client.close();
  17057. }
  17058. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17059. // Connect without requesting any subprotocol
  17060. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17061. "/ws-subprotocol");
  17062. ASSERT_TRUE(client.connect());
  17063. EXPECT_TRUE(client.subprotocol().empty());
  17064. client.close();
  17065. }
  17066. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17068. "/ws-echo");
  17069. client.set_tcp_nodelay(true);
  17070. client.set_connection_timeout(3, 0);
  17071. bool socket_options_called = false;
  17072. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17073. ASSERT_TRUE(client.connect());
  17074. ASSERT_TRUE(client.is_open());
  17075. EXPECT_TRUE(socket_options_called);
  17076. ASSERT_TRUE(client.send("hello"));
  17077. std::string msg;
  17078. auto result = client.read(msg);
  17079. EXPECT_EQ(result, ws::ReadResult::Text);
  17080. EXPECT_EQ(msg, "hello");
  17081. client.close();
  17082. }
  17083. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17085. "/ws-echo");
  17086. client.set_connection_timeout(std::chrono::seconds(3));
  17087. client.set_write_timeout(std::chrono::seconds(3));
  17088. // A sub-second remainder exercises the seconds/microseconds split.
  17089. client.set_read_timeout(std::chrono::milliseconds(1500));
  17090. ASSERT_TRUE(client.connect());
  17091. auto start = std::chrono::steady_clock::now();
  17092. std::string msg;
  17093. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17094. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17095. std::chrono::steady_clock::now() - start)
  17096. .count();
  17097. // Above 1s so that dropping the microseconds half of the split fails here,
  17098. // and well under the 300s default so that ignoring the setter fails too.
  17099. EXPECT_GE(elapsed, 1400);
  17100. EXPECT_LT(elapsed, 30000);
  17101. }
  17102. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17103. Server svr;
  17104. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17105. if (!req.has_header("Authorization")) {
  17106. res.status = StatusCode::Unauthorized_401;
  17107. res.set_content("Unauthorized", "text/plain");
  17108. return Server::HandlerResponse::Handled;
  17109. }
  17110. return Server::HandlerResponse::Unhandled;
  17111. });
  17112. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17113. std::string msg;
  17114. while (ws.read(msg)) {
  17115. ws.send(msg);
  17116. }
  17117. });
  17118. auto port = svr.bind_to_any_port("localhost");
  17119. std::thread t([&]() { svr.listen_after_bind(); });
  17120. svr.wait_until_ready();
  17121. // Without Authorization header - should be rejected before upgrade
  17122. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17123. EXPECT_FALSE(client1.connect());
  17124. // With Authorization header - should succeed
  17125. Headers headers = {{"Authorization", "Bearer token123"}};
  17126. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17127. headers);
  17128. ASSERT_TRUE(client2.connect());
  17129. ASSERT_TRUE(client2.send("hello"));
  17130. std::string msg;
  17131. ASSERT_TRUE(client2.read(msg));
  17132. EXPECT_EQ("hello", msg);
  17133. client2.close();
  17134. svr.stop();
  17135. t.join();
  17136. }
  17137. TEST(WebSocketTest, QueryStringInHandshake) {
  17138. Server svr;
  17139. std::mutex mtx;
  17140. std::string received_target;
  17141. std::string received_token;
  17142. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17143. {
  17144. std::lock_guard<std::mutex> lock(mtx);
  17145. received_target = req.target;
  17146. if (req.has_param("token")) {
  17147. received_token = req.get_param_value("token");
  17148. }
  17149. }
  17150. std::string msg;
  17151. while (ws.read(msg)) {
  17152. ws.send(msg);
  17153. }
  17154. });
  17155. auto port = svr.bind_to_any_port("localhost");
  17156. std::thread t([&]() { svr.listen_after_bind(); });
  17157. svr.wait_until_ready();
  17158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17159. "/ws?token=ABC&session=123");
  17160. ASSERT_TRUE(client.connect());
  17161. // Round-trip ensures the handler has run and captured the request.
  17162. ASSERT_TRUE(client.send("hello"));
  17163. std::string msg;
  17164. ASSERT_TRUE(client.read(msg));
  17165. EXPECT_EQ("hello", msg);
  17166. client.close();
  17167. {
  17168. std::lock_guard<std::mutex> lock(mtx);
  17169. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17170. EXPECT_EQ("ABC", received_token);
  17171. }
  17172. svr.stop();
  17173. t.join();
  17174. }
  17175. // Run a handshake against a throwaway server and hand the request the server
  17176. // received back to the caller, so tests can assert on the headers the client
  17177. // actually put on the wire.
  17178. static void capture_websocket_handshake_request(
  17179. const Headers &client_headers,
  17180. std::function<void(const Request &, int port)> verify) {
  17181. Server svr;
  17182. std::mutex mtx;
  17183. Request received;
  17184. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17185. {
  17186. std::lock_guard<std::mutex> lock(mtx);
  17187. received = req;
  17188. }
  17189. std::string msg;
  17190. while (ws.read(msg)) {
  17191. ws.send(msg);
  17192. }
  17193. });
  17194. auto port = svr.bind_to_any_port("localhost");
  17195. std::thread t([&]() { svr.listen_after_bind(); });
  17196. auto se = detail::scope_exit([&] {
  17197. svr.stop();
  17198. t.join();
  17199. });
  17200. svr.wait_until_ready();
  17201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17202. client_headers);
  17203. ASSERT_TRUE(client.connect());
  17204. ASSERT_TRUE(client.send("hello"));
  17205. std::string msg;
  17206. ASSERT_TRUE(client.read(msg));
  17207. client.close();
  17208. {
  17209. std::lock_guard<std::mutex> lock(mtx);
  17210. verify(received, port);
  17211. }
  17212. }
  17213. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17214. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17215. // Non-default port must be present in the Host header. Default ports
  17216. // (80/443) are omitted; that logic is covered by
  17217. // MakeHostAndPortStringTest.
  17218. EXPECT_EQ("localhost:" + std::to_string(port),
  17219. req.get_header_value("Host"));
  17220. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17221. req.get_header_value("User-Agent"));
  17222. EXPECT_FALSE(req.has_header("Accept"));
  17223. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17224. EXPECT_FALSE(req.has_header("Content-Length"));
  17225. });
  17226. }
  17227. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17228. capture_websocket_handshake_request(
  17229. {{"Host", "example.com"},
  17230. {"User-Agent", "custom-agent"},
  17231. {"X-Custom", "value"}},
  17232. [](const Request &req, int) {
  17233. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17234. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17235. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17236. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17237. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17238. });
  17239. }
  17240. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17241. capture_websocket_handshake_request(
  17242. {{"Upgrade", "bogus"},
  17243. {"Connection", "close"},
  17244. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17245. {"Sec-WebSocket-Version", "8"}},
  17246. [](const Request &req, int) {
  17247. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17248. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17249. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17250. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17251. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17252. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17253. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17254. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17255. req.get_header_value("Sec-WebSocket-Key"));
  17256. });
  17257. }
  17258. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17259. // A header the client refuses to send must abort the handshake before any
  17260. // part of it reaches the wire; a lone request line would otherwise sit in
  17261. // the peer's buffer as a truncated request.
  17262. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17263. ASSERT_NE(INVALID_SOCKET, srv);
  17264. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17265. sockaddr_in addr{};
  17266. addr.sin_family = AF_INET;
  17267. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17268. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17269. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17270. ASSERT_EQ(0, ::listen(srv, 1));
  17271. sockaddr_in bound{};
  17272. socklen_t bound_len = sizeof(bound);
  17273. ASSERT_EQ(
  17274. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17275. auto port = ntohs(bound.sin_port);
  17276. ssize_t received = -1;
  17277. std::thread t([&] {
  17278. // Bound every blocking call so a regression fails the test with a bad
  17279. // value instead of hanging the suite.
  17280. fd_set rfds;
  17281. FD_ZERO(&rfds);
  17282. FD_SET(srv, &rfds);
  17283. timeval tv{5, 0};
  17284. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17285. 0) {
  17286. return;
  17287. }
  17288. sockaddr_in cli_addr{};
  17289. socklen_t cli_len = sizeof(cli_addr);
  17290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17291. if (cli == INVALID_SOCKET) { return; }
  17292. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17293. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17294. char buf[4096];
  17295. received = ::recv(cli, buf, sizeof(buf), 0);
  17296. });
  17297. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17298. // connect() has already shut the socket down by the time it returns false,
  17299. // so the peer sees EOF without waiting for the client to be destroyed.
  17300. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17301. {{"X-Bad", "a\r\nInjected: 1"}});
  17302. EXPECT_FALSE(client.connect());
  17303. t.join();
  17304. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17305. EXPECT_EQ(0, received);
  17306. }
  17307. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17308. // The socket path doubles as the URL host, so it must not contain '/'.
  17309. const char *shard = getenv("GTEST_SHARD_INDEX");
  17310. const std::string sock_path =
  17311. shard ? std::string("httplib-ws-") + shard + ".sock"
  17312. : std::string("httplib-ws.sock");
  17313. std::remove(sock_path.c_str());
  17314. Server svr;
  17315. std::mutex mtx;
  17316. std::string received_host;
  17317. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17318. {
  17319. std::lock_guard<std::mutex> lock(mtx);
  17320. received_host = req.get_header_value("Host");
  17321. }
  17322. std::string msg;
  17323. while (ws.read(msg)) {
  17324. ws.send(msg);
  17325. }
  17326. });
  17327. svr.set_address_family(AF_UNIX);
  17328. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17329. auto se = detail::scope_exit([&] {
  17330. svr.stop();
  17331. t.join();
  17332. std::remove(sock_path.c_str());
  17333. });
  17334. svr.wait_until_ready();
  17335. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17336. client.set_address_family(AF_UNIX);
  17337. ASSERT_TRUE(client.connect());
  17338. ASSERT_TRUE(client.send("hello"));
  17339. std::string msg;
  17340. ASSERT_TRUE(client.read(msg));
  17341. client.close();
  17342. {
  17343. std::lock_guard<std::mutex> lock(mtx);
  17344. // There is no host:port for a Unix socket, so the same "localhost"
  17345. // placeholder the HTTP client uses is expected.
  17346. EXPECT_EQ("localhost", received_host);
  17347. }
  17348. }
  17349. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17350. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17351. protected:
  17352. void SetUp() override {
  17353. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17354. SERVER_PRIVATE_KEY_FILE);
  17355. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17356. std::string msg;
  17357. ws::ReadResult ret;
  17358. while ((ret = ws.read(msg))) {
  17359. if (ret == ws::Binary) {
  17360. ws.send(msg.data(), msg.size());
  17361. } else {
  17362. ws.send(msg);
  17363. }
  17364. }
  17365. });
  17366. port_ = server_->bind_to_any_port(HOST);
  17367. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17368. server_->wait_until_ready();
  17369. }
  17370. void TearDown() override {
  17371. server_->stop();
  17372. if (server_thread_.joinable()) { server_thread_.join(); }
  17373. }
  17374. std::unique_ptr<SSLServer> server_;
  17375. std::thread server_thread_;
  17376. int port_ = 0;
  17377. };
  17378. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17379. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17380. "/ws-echo");
  17381. client.enable_server_certificate_verification(false);
  17382. ASSERT_TRUE(client.connect());
  17383. ASSERT_TRUE(client.is_open());
  17384. ASSERT_TRUE(client.send("Hello WSS"));
  17385. std::string msg;
  17386. EXPECT_EQ(ws::Text, client.read(msg));
  17387. EXPECT_EQ("Hello WSS", msg);
  17388. client.close();
  17389. }
  17390. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17391. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17392. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17393. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17394. // client (without calling close() first) is the only path that runs
  17395. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17396. // bug exactly.
  17397. //
  17398. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17399. // when linked against an instrumented libssl; run under Valgrind to catch it
  17400. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17401. // suite (the freed session otherwise stalls on the close handshake) — this test
  17402. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17403. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17404. {
  17405. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17406. "/ws-echo");
  17407. client.enable_server_certificate_verification(false);
  17408. client.set_read_timeout(2, 0);
  17409. client.set_write_timeout(2, 0);
  17410. ASSERT_TRUE(client.connect());
  17411. ASSERT_TRUE(client.is_open());
  17412. ASSERT_TRUE(client.send("still open"));
  17413. // Intentionally do NOT call client.close(): leaving scope runs
  17414. // shutdown_and_close() with the WebSocket still open, which must send the
  17415. // close frame while the TLS session is still alive.
  17416. }
  17417. }
  17418. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17419. // shutdown_and_close() at the start of connect(), reproducing the same
  17420. // use-after-free within the test body rather than at scope exit. The second
  17421. // connect must succeed and echo, proving the close handshake ran over a live
  17422. // session. See the note above about memory-tool requirements.
  17423. TEST_F(WebSocketSSLIntegrationTest,
  17424. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17425. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17426. "/ws-echo");
  17427. client.enable_server_certificate_verification(false);
  17428. client.set_read_timeout(2, 0);
  17429. client.set_write_timeout(2, 0);
  17430. ASSERT_TRUE(client.connect());
  17431. ASSERT_TRUE(client.is_open());
  17432. ASSERT_TRUE(client.send("still open"));
  17433. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17434. // the still-open connection, which must not touch a freed TLS session.
  17435. ASSERT_TRUE(client.connect());
  17436. ASSERT_TRUE(client.is_open());
  17437. ASSERT_TRUE(client.send("after reconnect"));
  17438. std::string msg;
  17439. EXPECT_EQ(ws::Text, client.read(msg));
  17440. EXPECT_EQ("after reconnect", msg);
  17441. client.close();
  17442. }
  17443. #endif
  17444. #ifdef CPPHTTPLIB_SSL_ENABLED
  17445. class WebSocketSSLCATest : public ::testing::Test {
  17446. protected:
  17447. void SetUp() override {
  17448. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17449. SERVER_PRIVATE_KEY_FILE);
  17450. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17451. std::string msg;
  17452. while (ws.read(msg)) {
  17453. ws.send(msg);
  17454. }
  17455. });
  17456. port_ = server_->bind_to_any_port("127.0.0.1");
  17457. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17458. server_->wait_until_ready();
  17459. }
  17460. void TearDown() override {
  17461. server_->stop();
  17462. if (server_thread_.joinable()) { server_thread_.join(); }
  17463. }
  17464. std::string url() const {
  17465. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17466. }
  17467. std::unique_ptr<SSLServer> server_;
  17468. std::thread server_thread_;
  17469. int port_ = 0;
  17470. };
  17471. // A custom CA loaded as PEM verifies the server with full certificate
  17472. // verification enabled
  17473. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17474. ws::WebSocketClient client(url());
  17475. std::string cert;
  17476. read_file(SERVER_CERT2_FILE, cert);
  17477. client.load_ca_cert_store(cert.c_str(), cert.size());
  17478. ASSERT_TRUE(client.connect());
  17479. ASSERT_TRUE(client.send("hello"));
  17480. std::string msg;
  17481. EXPECT_EQ(ws::Text, client.read(msg));
  17482. EXPECT_EQ("hello", msg);
  17483. client.close();
  17484. }
  17485. // A custom CA that does not cover the server must fail verification (the
  17486. // custom CA is exclusive; system certs are not loaded alongside it)
  17487. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17488. ws::WebSocketClient client(url());
  17489. std::string cert;
  17490. read_file(CLIENT_CA_CERT_FILE, cert);
  17491. client.load_ca_cert_store(cert.c_str(), cert.size());
  17492. ASSERT_FALSE(client.connect());
  17493. }
  17494. // The same CA as a file path rather than PEM in memory
  17495. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  17496. ws::WebSocketClient client(url());
  17497. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17498. ASSERT_TRUE(client.connect());
  17499. ASSERT_TRUE(client.send("hello"));
  17500. std::string msg;
  17501. EXPECT_EQ(ws::Text, client.read(msg));
  17502. EXPECT_EQ("hello", msg);
  17503. client.close();
  17504. }
  17505. // ...and a CA file that does not cover the server still fails, so it is the
  17506. // path above that decides the outcome
  17507. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  17508. ws::WebSocketClient client(url());
  17509. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17510. ASSERT_FALSE(client.connect());
  17511. }
  17512. // Regression test: reconnecting with a native custom CA store used to reuse
  17513. // a store handle the previous TLS context had already freed (use-after-free
  17514. // under the OpenSSL backend). The context now lives as long as the client.
  17515. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17516. ws::WebSocketClient client(url());
  17517. std::string cert;
  17518. read_file(SERVER_CERT2_FILE, cert);
  17519. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17520. ASSERT_TRUE(client.connect());
  17521. client.close();
  17522. ASSERT_TRUE(client.connect());
  17523. ASSERT_TRUE(client.send("again"));
  17524. std::string msg;
  17525. EXPECT_EQ(ws::Text, client.read(msg));
  17526. EXPECT_EQ("again", msg);
  17527. client.close();
  17528. }
  17529. // Regression test: a certificate with a trusted chain but no identity match
  17530. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17531. // verification entirely for IP hosts, so this connection succeeded there.
  17532. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17533. // chain verification while the identity check must still fail.
  17534. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17536. ASSERT_TRUE(svr.is_valid());
  17537. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17538. std::string msg;
  17539. while (ws.read(msg)) {
  17540. ws.send(msg);
  17541. }
  17542. });
  17543. auto port = svr.bind_to_any_port("127.0.0.1");
  17544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17545. auto se = detail::scope_exit([&] {
  17546. svr.stop();
  17547. t.join();
  17548. });
  17549. svr.wait_until_ready();
  17550. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17551. "/echo");
  17552. std::string cert;
  17553. read_file(SERVER_CERT_FILE, cert);
  17554. client.load_ca_cert_store(cert.c_str(), cert.size());
  17555. ASSERT_FALSE(client.connect());
  17556. }
  17557. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  17558. // SNI, so nothing binds the host name to the TLS session. These bind the
  17559. // server to "localhost" instead, the only shape that exercises the SNI and
  17560. // hostname-verification path with certificate verification left enabled.
  17561. class WebSocketSSLDnsHostTest : public ::testing::Test {
  17562. protected:
  17563. void Start(const char *cert_file) {
  17564. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  17565. SERVER_PRIVATE_KEY_FILE);
  17566. ASSERT_TRUE(server_->is_valid());
  17567. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17568. std::string msg;
  17569. while (ws.read(msg)) {
  17570. ws.send(msg);
  17571. }
  17572. });
  17573. port_ = server_->bind_to_any_port("localhost");
  17574. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17575. server_->wait_until_ready();
  17576. }
  17577. void TearDown() override {
  17578. if (server_) { server_->stop(); }
  17579. if (server_thread_.joinable()) { server_thread_.join(); }
  17580. }
  17581. std::string url() const {
  17582. return "wss://localhost:" + std::to_string(port_) + "/echo";
  17583. }
  17584. std::unique_ptr<SSLServer> server_;
  17585. std::thread server_thread_;
  17586. int port_ = 0;
  17587. };
  17588. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  17589. // out and the connection is usable
  17590. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  17591. Start(SERVER_CERT2_FILE);
  17592. ws::WebSocketClient client(url());
  17593. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17594. ASSERT_TRUE(client.connect());
  17595. ASSERT_TRUE(client.send("hello"));
  17596. std::string msg;
  17597. EXPECT_EQ(ws::Text, client.read(msg));
  17598. EXPECT_EQ("hello", msg);
  17599. client.close();
  17600. }
  17601. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  17602. // while the identity check must still reject "localhost"
  17603. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  17604. Start(SERVER_CERT_FILE);
  17605. ws::WebSocketClient client(url());
  17606. client.set_ca_cert_path(SERVER_CERT_FILE);
  17607. ASSERT_FALSE(client.connect());
  17608. }
  17609. // A CA that did not sign the server certificate fails the chain, even though
  17610. // the name would match
  17611. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  17612. Start(SERVER_CERT2_FILE);
  17613. ws::WebSocketClient client(url());
  17614. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17615. ASSERT_FALSE(client.connect());
  17616. }
  17617. // With verification disabled, neither the chain nor the name is checked
  17618. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  17619. Start(SERVER_CERT_FILE);
  17620. ws::WebSocketClient client(url());
  17621. client.enable_server_certificate_verification(false);
  17622. ASSERT_TRUE(client.connect());
  17623. ASSERT_TRUE(client.send("hello"));
  17624. std::string msg;
  17625. EXPECT_EQ(ws::Text, client.read(msg));
  17626. EXPECT_EQ("hello", msg);
  17627. client.close();
  17628. }
  17629. #endif
  17630. #if !defined(_WIN32)
  17631. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17632. auto secret_dir = std::string("./symlink_test_secret");
  17633. auto served_dir = std::string("./symlink_test_served");
  17634. auto secret_file = secret_dir + "/secret.txt";
  17635. auto symlink_path = served_dir + "/escape";
  17636. // Setup: create directories and files
  17637. mkdir(secret_dir.c_str(), 0755);
  17638. mkdir(served_dir.c_str(), 0755);
  17639. {
  17640. std::ofstream ofs(secret_file);
  17641. ofs << "SECRET_DATA";
  17642. }
  17643. // Create symlink using absolute path so it resolves correctly
  17644. #ifdef PATH_MAX
  17645. char abs_secret[PATH_MAX];
  17646. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17647. #else
  17648. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17649. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17650. ASSERT_NE(nullptr, abs_secret);
  17651. #endif
  17652. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17653. auto se = detail::scope_exit([&] {
  17654. unlink(symlink_path.c_str());
  17655. unlink(secret_file.c_str());
  17656. rmdir(served_dir.c_str());
  17657. rmdir(secret_dir.c_str());
  17658. });
  17659. Server svr;
  17660. svr.set_mount_point("/", served_dir);
  17661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17662. auto se2 = detail::scope_exit([&] {
  17663. svr.stop();
  17664. listen_thread.join();
  17665. });
  17666. svr.wait_until_ready();
  17667. Client cli("localhost", PORT);
  17668. // Symlink pointing outside base dir should be blocked
  17669. auto res = cli.Get("/escape/secret.txt");
  17670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17671. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17672. }
  17673. #endif
  17674. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17675. // A GET request with Content-Length to a static file handler must have its
  17676. // body drained before the keep-alive connection is reused. Otherwise the
  17677. // unread body bytes are interpreted as the next HTTP request.
  17678. //
  17679. // The body is sent AFTER receiving the first response (as in the original
  17680. // PoC) so that the stream_line_reader cannot buffer it together with the
  17681. // headers of the first request.
  17682. Server svr;
  17683. svr.set_mount_point("/", "./www");
  17684. std::atomic<int> smuggled_count(0);
  17685. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17686. smuggled_count++;
  17687. res.set_content("oops", "text/plain");
  17688. });
  17689. auto port = svr.bind_to_any_port("localhost");
  17690. thread t = thread([&] { svr.listen_after_bind(); });
  17691. auto se = detail::scope_exit([&] {
  17692. svr.stop();
  17693. t.join();
  17694. });
  17695. svr.wait_until_ready();
  17696. auto error = Error::Success;
  17697. auto sock = detail::create_client_socket(
  17698. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17699. /*connection_timeout_sec=*/2, 0,
  17700. /*read_timeout_sec=*/2, 0,
  17701. /*write_timeout_sec=*/2, 0, std::string(), error);
  17702. ASSERT_NE(INVALID_SOCKET, sock);
  17703. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17704. // The "smuggled" request will be sent as the body of the outer GET
  17705. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17706. "Host: localhost\r\n"
  17707. "Connection: close\r\n"
  17708. "\r\n";
  17709. // Step 1: Send only the outer request headers (no body yet)
  17710. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17711. "Host: localhost\r\n"
  17712. "Content-Length: " +
  17713. std::to_string(smuggled.size()) +
  17714. "\r\n"
  17715. "\r\n";
  17716. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17717. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17718. // Step 2: Read the first response (server serves file without reading body)
  17719. std::string first_response;
  17720. char buf[4096];
  17721. for (;;) {
  17722. auto n = recv(sock, buf, sizeof(buf), 0);
  17723. if (n <= 0) break;
  17724. first_response.append(buf, static_cast<size_t>(n));
  17725. // Stop once we have a complete response (headers + body)
  17726. auto hdr_end = first_response.find("\r\n\r\n");
  17727. if (hdr_end != std::string::npos) {
  17728. // Check for Content-Length to know when the body is complete
  17729. auto cl_pos = first_response.find("Content-Length:");
  17730. if (cl_pos != std::string::npos) {
  17731. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17732. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17733. auto cl = std::stoul(
  17734. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17735. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17736. } else {
  17737. break; // No Content-Length, assume headers-only response
  17738. }
  17739. }
  17740. }
  17741. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17742. // Step 3: Now send the body, which looks like a new HTTP request.
  17743. // On a vulnerable server the keep-alive loop reads this as a second request.
  17744. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17745. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17746. // Step 4: Try to read a second response (should NOT exist after fix)
  17747. std::string second_response;
  17748. for (;;) {
  17749. auto n = recv(sock, buf, sizeof(buf), 0);
  17750. if (n <= 0) break;
  17751. second_response.append(buf, static_cast<size_t>(n));
  17752. }
  17753. // The smuggled request must NOT have been processed
  17754. EXPECT_EQ(0, smuggled_count.load());
  17755. }
  17756. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17757. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17758. // must be rejected with 400 Bad Request.
  17759. Server svr;
  17760. svr.Post("/test", [&](const Request &, Response &res) {
  17761. res.set_content("ok", "text/plain");
  17762. });
  17763. thread t = thread([&] { svr.listen(HOST, PORT); });
  17764. auto se = detail::scope_exit([&] {
  17765. svr.stop();
  17766. t.join();
  17767. ASSERT_FALSE(svr.is_running());
  17768. });
  17769. svr.wait_until_ready();
  17770. // Exact "chunked"
  17771. {
  17772. auto req = "POST /test HTTP/1.1\r\n"
  17773. "Host: localhost\r\n"
  17774. "Content-Length: 5\r\n"
  17775. "Transfer-Encoding: chunked\r\n"
  17776. "Connection: close\r\n"
  17777. "\r\n"
  17778. "hello";
  17779. std::string response;
  17780. ASSERT_TRUE(send_request(1, req, &response));
  17781. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17782. response.substr(0, response.find("\r\n")));
  17783. }
  17784. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17785. {
  17786. auto req = "POST /test HTTP/1.1\r\n"
  17787. "Host: localhost\r\n"
  17788. "Content-Length: 5\r\n"
  17789. "Transfer-Encoding: gzip, chunked\r\n"
  17790. "Connection: close\r\n"
  17791. "\r\n"
  17792. "hello";
  17793. std::string response;
  17794. ASSERT_TRUE(send_request(1, req, &response));
  17795. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17796. response.substr(0, response.find("\r\n")));
  17797. }
  17798. }
  17799. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17800. Server svr;
  17801. svr.Post("/test", [&](const Request &, Response &res) {
  17802. res.set_content("ok", "text/plain");
  17803. });
  17804. thread t = thread([&] { svr.listen(HOST, PORT); });
  17805. auto se = detail::scope_exit([&] {
  17806. svr.stop();
  17807. t.join();
  17808. ASSERT_FALSE(svr.is_running());
  17809. });
  17810. svr.wait_until_ready();
  17811. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17812. // length cannot be determined, so the server must answer 400 and close
  17813. // rather than treat the request as bodyless and leave the body in the
  17814. // socket for the next request to pick up.
  17815. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17816. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17817. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17818. std::string response;
  17819. ASSERT_TRUE(send_request(1, req, &response));
  17820. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17821. response.substr(0, response.find("\r\n")))
  17822. << transfer_encoding;
  17823. }
  17824. // RFC 9110 5.3: the codings may also be split across several
  17825. // Transfer-Encoding lines, which combine in the order they were received.
  17826. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17827. // just like the single-line "chunked, gzip" above.
  17828. {
  17829. auto req = "POST /test HTTP/1.1\r\n"
  17830. "Host: localhost\r\n"
  17831. "Transfer-Encoding: chunked\r\n"
  17832. "Transfer-Encoding: gzip\r\n"
  17833. "\r\n"
  17834. "0\r\n\r\n";
  17835. std::string response;
  17836. ASSERT_TRUE(send_request(1, req, &response));
  17837. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17838. response.substr(0, response.find("\r\n")));
  17839. }
  17840. // A sequence ending in chunked stays valid.
  17841. auto req = "POST /test HTTP/1.1\r\n"
  17842. "Host: localhost\r\n"
  17843. "Transfer-Encoding: gzip, chunked\r\n"
  17844. "Connection: close\r\n"
  17845. "\r\n"
  17846. "0\r\n\r\n";
  17847. std::string response;
  17848. ASSERT_TRUE(send_request(1, req, &response));
  17849. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17850. // ...including when it is spread over several lines.
  17851. auto split_req = "POST /test HTTP/1.1\r\n"
  17852. "Host: localhost\r\n"
  17853. "Transfer-Encoding: gzip\r\n"
  17854. "Transfer-Encoding: chunked\r\n"
  17855. "Connection: close\r\n"
  17856. "\r\n"
  17857. "0\r\n\r\n";
  17858. std::string split_response;
  17859. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17860. EXPECT_EQ("HTTP/1.1 200 OK",
  17861. split_response.substr(0, split_response.find("\r\n")));
  17862. }
  17863. // Regression for issue #2450: a DELETE without Content-Length on a
  17864. // keep-alive connection must not let the post-response drain consume the
  17865. // next request's bytes.
  17866. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17867. Server svr;
  17868. std::atomic<int> delete_count(0);
  17869. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17870. delete_count++;
  17871. res.status = StatusCode::NoContent_204;
  17872. });
  17873. auto port = svr.bind_to_any_port(HOST);
  17874. thread t = thread([&] { svr.listen_after_bind(); });
  17875. auto se = detail::scope_exit([&] {
  17876. svr.stop();
  17877. t.join();
  17878. });
  17879. svr.wait_until_ready();
  17880. auto error = Error::Success;
  17881. auto sock = detail::create_client_socket(
  17882. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17883. /*connection_timeout_sec=*/2, 0,
  17884. /*read_timeout_sec=*/2, 0,
  17885. /*write_timeout_sec=*/2, 0, std::string(), error);
  17886. ASSERT_NE(INVALID_SOCKET, sock);
  17887. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17888. auto send_request_and_read_response = [&](const std::string &req,
  17889. std::string &out) -> bool {
  17890. auto sent = send(sock, req.data(), req.size(), 0);
  17891. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17892. char buf[4096];
  17893. for (;;) {
  17894. auto n = recv(sock, buf, sizeof(buf), 0);
  17895. if (n <= 0) { return !out.empty(); }
  17896. out.append(buf, static_cast<size_t>(n));
  17897. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17898. }
  17899. };
  17900. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17901. "Host: localhost\r\n"
  17902. "\r\n";
  17903. std::string resp1;
  17904. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17905. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17906. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17907. "Host: localhost\r\n"
  17908. "Connection: close\r\n"
  17909. "\r\n";
  17910. std::string resp2;
  17911. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17912. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17913. EXPECT_EQ(2, delete_count.load());
  17914. }
  17915. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17916. Server svr;
  17917. svr.Post("/ingest", [&](const Request &, Response &res,
  17918. const ContentReader &content_reader) {
  17919. auto consumed = content_reader([](const char *, size_t) { return false; });
  17920. EXPECT_FALSE(consumed);
  17921. res.status = StatusCode::Conflict_409;
  17922. res.set_header("Connection", "close");
  17923. });
  17924. auto port = svr.bind_to_any_port(HOST);
  17925. thread t = thread([&] { svr.listen_after_bind(); });
  17926. auto se = detail::scope_exit([&] {
  17927. svr.stop();
  17928. t.join();
  17929. });
  17930. svr.wait_until_ready();
  17931. auto error = Error::Success;
  17932. auto sock = detail::create_client_socket(
  17933. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17934. /*connection_timeout_sec=*/2, 0,
  17935. /*read_timeout_sec=*/1, 0,
  17936. /*write_timeout_sec=*/2, 0, std::string(), error);
  17937. ASSERT_NE(INVALID_SOCKET, sock);
  17938. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17939. std::string request = "POST /ingest HTTP/1.1\r\n"
  17940. "Host: localhost\r\n"
  17941. "Transfer-Encoding: chunked\r\n"
  17942. "\r\n"
  17943. "4\r\n"
  17944. "data\r\n";
  17945. auto sent = send(sock, request.data(), request.size(), 0);
  17946. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17947. std::string response;
  17948. ssize_t received = 0;
  17949. do {
  17950. char buf[4096];
  17951. received = recv(sock, buf, sizeof(buf), 0);
  17952. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17953. } while (received > 0);
  17954. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17955. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17956. EXPECT_EQ(0, received);
  17957. }
  17958. namespace no_proxy_test {
  17959. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17960. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17961. // calling listen().
  17962. class ScopedServer {
  17963. public:
  17964. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17965. ~ScopedServer() {
  17966. svr_.stop();
  17967. if (th_.joinable()) { th_.join(); }
  17968. }
  17969. Server &svr() { return svr_; }
  17970. int port() const { return port_; }
  17971. void listen() {
  17972. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17973. svr_.wait_until_ready();
  17974. }
  17975. private:
  17976. Server svr_;
  17977. std::thread th_;
  17978. int port_ = 0;
  17979. };
  17980. class ProxyAndTargetServers {
  17981. public:
  17982. ProxyAndTargetServers() {
  17983. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17984. proxy_hits_++;
  17985. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17986. res.set_content("via-proxy", "text/plain");
  17987. });
  17988. target_.Get(".*", [this](const Request &req, Response &res) {
  17989. target_hits_++;
  17990. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17991. res.set_content("direct", "text/plain");
  17992. });
  17993. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17994. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17995. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17996. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17997. proxy_mock_.wait_until_ready();
  17998. target_.wait_until_ready();
  17999. }
  18000. ~ProxyAndTargetServers() {
  18001. proxy_mock_.stop();
  18002. target_.stop();
  18003. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18004. if (target_thread_.joinable()) { target_thread_.join(); }
  18005. }
  18006. Server &proxy_mock() { return proxy_mock_; }
  18007. Server &target() { return target_; }
  18008. int proxy_port() const { return proxy_port_; }
  18009. int target_port() const { return target_port_; }
  18010. int proxy_hits() const { return proxy_hits_.load(); }
  18011. int target_hits() const { return target_hits_.load(); }
  18012. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18013. void reset_counters() {
  18014. proxy_hits_ = 0;
  18015. target_hits_ = 0;
  18016. last_had_proxy_authz_ = false;
  18017. }
  18018. private:
  18019. Server proxy_mock_;
  18020. Server target_;
  18021. std::thread proxy_thread_;
  18022. std::thread target_thread_;
  18023. int proxy_port_ = 0;
  18024. int target_port_ = 0;
  18025. std::atomic<int> proxy_hits_{0};
  18026. std::atomic<int> target_hits_{0};
  18027. std::atomic<bool> last_had_proxy_authz_{false};
  18028. };
  18029. inline std::unique_ptr<Client> make_client(const std::string &host,
  18030. ProxyAndTargetServers &s) {
  18031. auto cli = detail::make_unique<Client>(host, s.target_port());
  18032. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18033. cli->set_proxy("127.0.0.1", s.proxy_port());
  18034. return cli;
  18035. }
  18036. } // namespace no_proxy_test
  18037. using no_proxy_test::make_client;
  18038. using no_proxy_test::ProxyAndTargetServers;
  18039. TEST(NoProxyTest, ExactHostnameBypasses) {
  18040. ProxyAndTargetServers s;
  18041. auto cli = make_client("example.com", s);
  18042. cli->set_no_proxy({"example.com"});
  18043. auto res = cli->Get("/");
  18044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18045. EXPECT_EQ(0, s.proxy_hits());
  18046. EXPECT_EQ(1, s.target_hits());
  18047. }
  18048. TEST(NoProxyTest, SubdomainBypasses) {
  18049. ProxyAndTargetServers s;
  18050. auto cli = make_client("foo.example.com", s);
  18051. cli->set_no_proxy({"example.com"});
  18052. auto res = cli->Get("/");
  18053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18054. EXPECT_EQ(0, s.proxy_hits());
  18055. EXPECT_EQ(1, s.target_hits());
  18056. }
  18057. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18058. // Regression guard: "evilexample.com" must not be considered a subdomain
  18059. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18060. // check would let traffic bypass the proxy and leak credentials direct
  18061. // to the attacker host.
  18062. ProxyAndTargetServers s;
  18063. auto cli = make_client("evilexample.com", s);
  18064. cli->set_no_proxy({"example.com"});
  18065. auto res = cli->Get("/");
  18066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18067. EXPECT_GE(s.proxy_hits(), 1);
  18068. EXPECT_EQ(0, s.target_hits());
  18069. }
  18070. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18071. ProxyAndTargetServers s;
  18072. auto cli = make_client("example.com.evil.com", s);
  18073. cli->set_no_proxy({"example.com"});
  18074. auto res = cli->Get("/");
  18075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18076. EXPECT_GE(s.proxy_hits(), 1);
  18077. EXPECT_EQ(0, s.target_hits());
  18078. }
  18079. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18080. ProxyAndTargetServers s;
  18081. auto cli = make_client("example.com", s);
  18082. cli->set_no_proxy({".example.com"});
  18083. auto res = cli->Get("/");
  18084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18085. EXPECT_EQ(0, s.proxy_hits());
  18086. EXPECT_EQ(1, s.target_hits());
  18087. }
  18088. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18089. ProxyAndTargetServers s;
  18090. auto cli = make_client("Example.COM", s);
  18091. cli->set_no_proxy({"EXAMPLE.com"});
  18092. auto res = cli->Get("/");
  18093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18094. EXPECT_EQ(0, s.proxy_hits());
  18095. EXPECT_EQ(1, s.target_hits());
  18096. }
  18097. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18098. ProxyAndTargetServers s;
  18099. auto cli = make_client("example.com.", s);
  18100. cli->set_no_proxy({"example.com"});
  18101. auto res = cli->Get("/");
  18102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18103. EXPECT_EQ(0, s.proxy_hits());
  18104. EXPECT_EQ(1, s.target_hits());
  18105. }
  18106. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18107. // Trailing dots must be normalized on BOTH sides — host and entry.
  18108. // An implementation that only strips the host-side trailing dot would
  18109. // fail to match host "example.com" against entry "example.com." because
  18110. // a literal substring search would compare 11 chars against 12.
  18111. ProxyAndTargetServers s;
  18112. auto cli = make_client("example.com", s);
  18113. cli->set_no_proxy({"example.com."});
  18114. auto res = cli->Get("/");
  18115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18116. EXPECT_EQ(0, s.proxy_hits());
  18117. EXPECT_EQ(1, s.target_hits());
  18118. }
  18119. TEST(NoProxyTest, WildcardBypassesEverything) {
  18120. ProxyAndTargetServers s;
  18121. auto cli = make_client("anything.invalid.test", s);
  18122. cli->set_no_proxy({"*"});
  18123. auto res = cli->Get("/");
  18124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18125. EXPECT_EQ(0, s.proxy_hits());
  18126. EXPECT_EQ(1, s.target_hits());
  18127. }
  18128. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18129. ProxyAndTargetServers s;
  18130. Client cli("127.0.0.1", s.target_port());
  18131. cli.set_proxy("127.0.0.1", s.proxy_port());
  18132. cli.set_no_proxy({"127.0.0.1"});
  18133. auto res = cli.Get("/");
  18134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18135. EXPECT_EQ(0, s.proxy_hits());
  18136. EXPECT_EQ(1, s.target_hits());
  18137. }
  18138. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18139. ProxyAndTargetServers s;
  18140. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18141. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18142. cli.set_proxy("127.0.0.1", s.proxy_port());
  18143. cli.set_no_proxy({"::1"});
  18144. auto res = cli.Get("/");
  18145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18146. EXPECT_EQ(0, s.proxy_hits());
  18147. EXPECT_EQ(1, s.target_hits());
  18148. }
  18149. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18150. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18151. // must still be recognized as IPv6 for CIDR matching. Implementations
  18152. // that detect IPv6 only when the host begins with '[' would parse the
  18153. // host as a hostname and miss the match.
  18154. ProxyAndTargetServers s;
  18155. Client cli("fe80::1", s.target_port());
  18156. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18157. cli.set_proxy("127.0.0.1", s.proxy_port());
  18158. cli.set_no_proxy({"fe80::/10"});
  18159. auto res = cli.Get("/");
  18160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18161. EXPECT_EQ(0, s.proxy_hits());
  18162. EXPECT_EQ(1, s.target_hits());
  18163. }
  18164. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18165. ProxyAndTargetServers s;
  18166. Client cli("::1", s.target_port());
  18167. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18168. cli.set_proxy("127.0.0.1", s.proxy_port());
  18169. cli.set_no_proxy({"[::1]"});
  18170. auto res = cli.Get("/");
  18171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18172. EXPECT_EQ(0, s.proxy_hits());
  18173. EXPECT_EQ(1, s.target_hits());
  18174. }
  18175. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18176. ProxyAndTargetServers s;
  18177. Client cli("fe80::1", s.target_port());
  18178. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18179. cli.set_proxy("127.0.0.1", s.proxy_port());
  18180. cli.set_no_proxy({"[fe80::]/10"});
  18181. auto res = cli.Get("/");
  18182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18183. EXPECT_EQ(0, s.proxy_hits());
  18184. EXPECT_EQ(1, s.target_hits());
  18185. }
  18186. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18187. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18188. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18189. // tricks via address-family conversion.
  18190. ProxyAndTargetServers s;
  18191. Client cli("::ffff:127.0.0.1", s.target_port());
  18192. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18193. cli.set_proxy("127.0.0.1", s.proxy_port());
  18194. cli.set_no_proxy({"127.0.0.1"});
  18195. auto res = cli.Get("/");
  18196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18197. EXPECT_GE(s.proxy_hits(), 1);
  18198. EXPECT_EQ(0, s.target_hits());
  18199. }
  18200. TEST(NoProxyTest, IPv4CidrMatch) {
  18201. ProxyAndTargetServers s;
  18202. Client cli("127.0.0.1", s.target_port());
  18203. cli.set_proxy("127.0.0.1", s.proxy_port());
  18204. cli.set_no_proxy({"127.0.0.0/8"});
  18205. auto res = cli.Get("/");
  18206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18207. EXPECT_EQ(0, s.proxy_hits());
  18208. EXPECT_EQ(1, s.target_hits());
  18209. }
  18210. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18211. ProxyAndTargetServers s;
  18212. Client cli("127.0.0.1", s.target_port());
  18213. cli.set_proxy("127.0.0.1", s.proxy_port());
  18214. cli.set_no_proxy({"10.0.0.0/8"});
  18215. auto res = cli.Get("/");
  18216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18217. EXPECT_GE(s.proxy_hits(), 1);
  18218. EXPECT_EQ(0, s.target_hits());
  18219. }
  18220. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18221. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18222. // IPv4 target matches.
  18223. ProxyAndTargetServers s;
  18224. Client cli("127.0.0.1", s.target_port());
  18225. cli.set_proxy("127.0.0.1", s.proxy_port());
  18226. cli.set_no_proxy({"0.0.0.0/0"});
  18227. auto res = cli.Get("/");
  18228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18229. EXPECT_EQ(0, s.proxy_hits());
  18230. EXPECT_EQ(1, s.target_hits());
  18231. }
  18232. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18233. ProxyAndTargetServers s;
  18234. Client cli("127.0.0.1", s.target_port());
  18235. cli.set_proxy("127.0.0.1", s.proxy_port());
  18236. cli.set_no_proxy({"127.0.0.1"});
  18237. auto res = cli.Get("/");
  18238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18239. EXPECT_EQ(0, s.proxy_hits());
  18240. EXPECT_EQ(1, s.target_hits());
  18241. }
  18242. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18243. ProxyAndTargetServers s;
  18244. Client cli("127.0.0.1", s.target_port());
  18245. cli.set_proxy("127.0.0.1", s.proxy_port());
  18246. cli.set_no_proxy({"127.0.0.0/33"});
  18247. auto res = cli.Get("/");
  18248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18249. EXPECT_GE(s.proxy_hits(), 1);
  18250. EXPECT_EQ(0, s.target_hits());
  18251. }
  18252. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18253. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18254. ProxyAndTargetServers s;
  18255. Client cli("127.0.0.1", s.target_port());
  18256. cli.set_proxy("127.0.0.1", s.proxy_port());
  18257. cli.set_no_proxy({"127.0.0.1/"});
  18258. auto res = cli.Get("/");
  18259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18260. EXPECT_GE(s.proxy_hits(), 1);
  18261. EXPECT_EQ(0, s.target_hits());
  18262. }
  18263. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18264. ProxyAndTargetServers s;
  18265. auto cli = make_client("internal.corp", s);
  18266. cli->set_proxy_basic_auth("u", "p");
  18267. cli->set_no_proxy({"internal.corp"});
  18268. auto res = cli->Get("/");
  18269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18270. EXPECT_EQ(1, s.target_hits());
  18271. EXPECT_EQ(0, s.proxy_hits());
  18272. EXPECT_FALSE(s.last_had_proxy_authz())
  18273. << "Proxy-Authorization must not be sent direct to the target";
  18274. }
  18275. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18276. ProxyAndTargetServers s;
  18277. auto cli = make_client("public.example", s);
  18278. cli->set_proxy_basic_auth("u", "p");
  18279. cli->set_no_proxy({"internal.corp"}); // does not match
  18280. auto res = cli->Get("/");
  18281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18282. EXPECT_GE(s.proxy_hits(), 1);
  18283. EXPECT_TRUE(s.last_had_proxy_authz());
  18284. }
  18285. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18286. ProxyAndTargetServers s;
  18287. auto cli = make_client("anything.test", s);
  18288. auto res = cli->Get("/");
  18289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18290. EXPECT_GE(s.proxy_hits(), 1);
  18291. EXPECT_EQ(0, s.target_hits());
  18292. }
  18293. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18294. ProxyAndTargetServers s;
  18295. auto cli = make_client("example.com", s);
  18296. cli->set_no_proxy({"example.com:8080"});
  18297. auto res = cli->Get("/");
  18298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18299. EXPECT_GE(s.proxy_hits(), 1);
  18300. EXPECT_EQ(0, s.target_hits());
  18301. }
  18302. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18303. ProxyAndTargetServers s;
  18304. auto cli = make_client("anything.test", s);
  18305. cli->set_no_proxy({"", " ", "\t"});
  18306. auto res = cli->Get("/");
  18307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18308. EXPECT_GE(s.proxy_hits(), 1);
  18309. EXPECT_EQ(0, s.target_hits());
  18310. }
  18311. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18312. // An entry with leading/trailing whitespace must still match — env-style
  18313. // values are commonly pasted with stray spaces and an implementation
  18314. // that feeds the raw token directly to inet_pton would fail to match
  18315. // valid CIDRs because of the spaces.
  18316. ProxyAndTargetServers s;
  18317. Client cli("127.0.0.1", s.target_port());
  18318. cli.set_proxy("127.0.0.1", s.proxy_port());
  18319. cli.set_no_proxy({" 127.0.0.0/8 "});
  18320. auto res = cli.Get("/");
  18321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18322. EXPECT_EQ(0, s.proxy_hits());
  18323. EXPECT_EQ(1, s.target_hits());
  18324. }
  18325. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18326. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18327. // go direct and must NOT carry Proxy-Authorization.
  18328. std::atomic<int> proxy_hits{0};
  18329. std::atomic<int> target_hits{0};
  18330. std::atomic<bool> target_saw_authz{false};
  18331. no_proxy_test::ScopedServer proxy_mock, target;
  18332. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18333. proxy_hits++;
  18334. res.status = 302;
  18335. res.set_header("Location", "http://127.0.0.1:" +
  18336. std::to_string(target.port()) + "/landed");
  18337. });
  18338. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18339. target_hits++;
  18340. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18341. res.set_content("direct", "text/plain");
  18342. });
  18343. proxy_mock.listen();
  18344. target.listen();
  18345. Client cli("public.example", target.port());
  18346. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18347. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18348. cli.set_proxy_basic_auth("u", "p");
  18349. cli.set_no_proxy({"127.0.0.1"});
  18350. cli.set_follow_location(true);
  18351. auto res = cli.Get("/redir");
  18352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18353. EXPECT_GE(proxy_hits.load(), 1);
  18354. EXPECT_GE(target_hits.load(), 1);
  18355. EXPECT_FALSE(target_saw_authz.load());
  18356. }
  18357. #ifdef CPPHTTPLIB_SSL_ENABLED
  18358. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18359. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18360. // proxy creds would be sent to the (possibly hostile) origin.
  18361. std::atomic<int> target_hits{0};
  18362. std::atomic<bool> target_saw_proxy_authz{false};
  18363. no_proxy_test::ScopedServer target;
  18364. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18365. target_hits++;
  18366. if (req.has_header("Proxy-Authorization")) {
  18367. target_saw_proxy_authz = true;
  18368. }
  18369. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18370. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18371. "nonce=\"abc\", algorithm=MD5");
  18372. });
  18373. target.listen();
  18374. // The proxy address is set to the target's port: the bypass MUST kick in;
  18375. // if it doesn't, the test still routes "via proxy" to the same server and
  18376. // the Proxy-Authorization assertion below catches the leak.
  18377. Client cli("evil.example", target.port());
  18378. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18379. cli.set_proxy("127.0.0.1", target.port());
  18380. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18381. cli.set_no_proxy({"evil.example"});
  18382. auto res = cli.Get("/x");
  18383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18384. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18385. EXPECT_EQ(1, target_hits.load());
  18386. EXPECT_FALSE(target_saw_proxy_authz.load());
  18387. }
  18388. #endif
  18389. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18390. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18391. std::atomic<int> proxy_hits{0};
  18392. std::atomic<int> bypass_hits{0};
  18393. std::atomic<bool> proxy_saw_c_url{false};
  18394. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18395. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18396. proxy_hits++;
  18397. if (req.path.find("/start") != std::string::npos) {
  18398. res.status = 302;
  18399. res.set_header("Location", "http://127.0.0.1:" +
  18400. std::to_string(bypass_server.port()) +
  18401. "/middle");
  18402. return;
  18403. }
  18404. if (req.path.find("/end") != std::string::npos) {
  18405. proxy_saw_c_url = true;
  18406. res.set_content("c-via-proxy", "text/plain");
  18407. return;
  18408. }
  18409. res.set_content("unexpected", "text/plain");
  18410. });
  18411. // public.example's "advertised" port is arbitrary (the request never lands
  18412. // there — it goes through the proxy), but use a dynamic value to stay
  18413. // friendly with sharded parallel runs.
  18414. int public_port = bypass_server.port();
  18415. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18416. bypass_hits++;
  18417. res.status = 302;
  18418. res.set_header("Location", "http://public.example:" +
  18419. std::to_string(public_port) + "/end");
  18420. });
  18421. proxy_mock.listen();
  18422. bypass_server.listen();
  18423. Client cli("public.example", public_port);
  18424. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18425. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18426. cli.set_no_proxy({"127.0.0.1"});
  18427. cli.set_follow_location(true);
  18428. auto res = cli.Get("/start");
  18429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18430. EXPECT_EQ(StatusCode::OK_200, res->status);
  18431. EXPECT_EQ("c-via-proxy", res->body);
  18432. EXPECT_GE(proxy_hits.load(), 2);
  18433. EXPECT_GE(bypass_hits.load(), 1);
  18434. EXPECT_TRUE(proxy_saw_c_url.load());
  18435. }
  18436. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18437. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18438. // request reconnects to the correct endpoint.
  18439. std::atomic<int> proxy_hits{0};
  18440. std::atomic<int> target_hits{0};
  18441. no_proxy_test::ScopedServer proxy_mock, target;
  18442. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18443. proxy_hits++;
  18444. res.set_content("via-proxy", "text/plain");
  18445. });
  18446. target.svr().Get(".*", [&](const Request &, Response &res) {
  18447. target_hits++;
  18448. res.set_content("direct", "text/plain");
  18449. });
  18450. proxy_mock.listen();
  18451. target.listen();
  18452. Client cli("public.example", target.port());
  18453. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18454. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18455. cli.set_keep_alive(true);
  18456. auto res1 = cli.Get("/a");
  18457. ASSERT_TRUE(res1);
  18458. EXPECT_EQ("via-proxy", res1->body);
  18459. EXPECT_EQ(1, proxy_hits.load());
  18460. EXPECT_EQ(0, target_hits.load());
  18461. cli.set_no_proxy({"public.example"});
  18462. auto res2 = cli.Get("/b");
  18463. ASSERT_TRUE(res2);
  18464. EXPECT_EQ("direct", res2->body);
  18465. EXPECT_EQ(1, proxy_hits.load());
  18466. EXPECT_EQ(1, target_hits.load());
  18467. }
  18468. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18469. namespace proxy_tunnel_test {
  18470. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18471. class ScopedSSLServer {
  18472. public:
  18473. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18474. port_ = svr_.bind_to_any_port("127.0.0.1");
  18475. }
  18476. ~ScopedSSLServer() {
  18477. svr_.stop();
  18478. if (th_.joinable()) { th_.join(); }
  18479. }
  18480. SSLServer &svr() { return svr_; }
  18481. int port() const { return port_; }
  18482. void listen() {
  18483. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18484. svr_.wait_until_ready();
  18485. }
  18486. private:
  18487. SSLServer svr_;
  18488. std::thread th_;
  18489. int port_ = 0;
  18490. };
  18491. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18492. class ScopedConnectProxy {
  18493. public:
  18494. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18495. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18496. if (listen_fd_ < 0) { return; }
  18497. int yes = 1;
  18498. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18499. sockaddr_in a{};
  18500. a.sin_family = AF_INET;
  18501. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18502. a.sin_port = 0;
  18503. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18504. return;
  18505. }
  18506. socklen_t alen = sizeof(a);
  18507. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18508. 0) {
  18509. return;
  18510. }
  18511. port_ = ntohs(a.sin_port);
  18512. if (::listen(listen_fd_, 1) != 0) { return; }
  18513. th_ = std::thread([this] { run(); });
  18514. }
  18515. ~ScopedConnectProxy() {
  18516. stop_ = true;
  18517. if (listen_fd_ >= 0) {
  18518. ::shutdown(listen_fd_, SHUT_RDWR);
  18519. ::close(listen_fd_);
  18520. }
  18521. if (th_.joinable()) { th_.join(); }
  18522. }
  18523. int port() const { return port_; }
  18524. int connect_hits() const { return connect_hits_.load(); }
  18525. private:
  18526. void run() {
  18527. while (!stop_.load()) {
  18528. fd_set rfds;
  18529. FD_ZERO(&rfds);
  18530. FD_SET(listen_fd_, &rfds);
  18531. timeval tv{0, 100 * 1000};
  18532. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18533. if (sel <= 0) { continue; }
  18534. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18535. if (client_fd < 0) { continue; }
  18536. std::string req;
  18537. char buf[2048];
  18538. while (req.find("\r\n\r\n") == std::string::npos) {
  18539. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18540. if (n <= 0) { break; }
  18541. req.append(buf, static_cast<size_t>(n));
  18542. }
  18543. if (req.compare(0, 7, "CONNECT") != 0) {
  18544. ::close(client_fd);
  18545. continue;
  18546. }
  18547. connect_hits_++;
  18548. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18549. ::send(client_fd, ok, std::strlen(ok), 0);
  18550. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18551. sockaddr_in o{};
  18552. o.sin_family = AF_INET;
  18553. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18554. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18555. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18556. 0) {
  18557. ::close(client_fd);
  18558. ::close(origin_fd);
  18559. continue;
  18560. }
  18561. auto forward = [](int from, int to) {
  18562. char b[8192];
  18563. for (;;) {
  18564. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18565. if (n <= 0) { break; }
  18566. ssize_t off = 0;
  18567. while (off < n) {
  18568. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18569. if (s <= 0) {
  18570. off = n;
  18571. break;
  18572. }
  18573. off += s;
  18574. }
  18575. }
  18576. ::shutdown(to, SHUT_WR);
  18577. };
  18578. std::thread t1([&] { forward(client_fd, origin_fd); });
  18579. std::thread t2([&] { forward(origin_fd, client_fd); });
  18580. t1.join();
  18581. t2.join();
  18582. ::close(client_fd);
  18583. ::close(origin_fd);
  18584. }
  18585. }
  18586. int forward_port_ = -1;
  18587. int listen_fd_ = -1;
  18588. int port_ = 0;
  18589. std::thread th_;
  18590. std::atomic<bool> stop_{false};
  18591. std::atomic<int> connect_hits_{0};
  18592. };
  18593. } // namespace proxy_tunnel_test
  18594. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18595. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18596. // retry; otherwise proxy creds would be sent to the origin.
  18597. std::atomic<int> origin_hits{0};
  18598. std::atomic<bool> origin_saw_proxy_authz{false};
  18599. proxy_tunnel_test::ScopedSSLServer origin;
  18600. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18601. origin_hits++;
  18602. if (req.has_header("Proxy-Authorization")) {
  18603. origin_saw_proxy_authz = true;
  18604. }
  18605. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18606. res.set_header("Proxy-Authenticate",
  18607. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18608. "algorithm=MD5");
  18609. });
  18610. origin.listen();
  18611. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18612. ASSERT_NE(0, proxy.port());
  18613. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18614. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18615. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18616. // and answer with its own status, making this test flaky.
  18617. SSLClient cli("127.0.0.1", origin.port());
  18618. cli.enable_server_certificate_verification(false);
  18619. cli.set_proxy("127.0.0.1", proxy.port());
  18620. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18621. auto res = cli.Get("/x");
  18622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18623. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18624. EXPECT_EQ(1, origin_hits.load());
  18625. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18626. EXPECT_EQ(1, proxy.connect_hits());
  18627. }
  18628. #endif